当前位置: 首页>>代码示例>>Python>>正文


Python orm.ORM类代码示例

本文整理汇总了Python中baph.db.orm.ORM的典型用法代码示例。如果您正苦于以下问题:Python ORM类的具体用法?Python ORM怎么用?Python ORM使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ORM类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_from_argv

 def run_from_argv(self, argv):
     """
     Set up any environment changes requested (e.g., Python path
     and Django settings), then run this command. If the
     command raises a ``CommandError``, intercept it and print it sensibly
     to stderr.
     """
     parser = self.create_parser(argv[0], argv[1])
     options, args = parser.parse_args(argv[2:])
     handle_default_options(options)
     try:
         self.execute(*args, **options.__dict__)
     except Exception as e:
         raise
         # self.stderr is not guaranteed to be set here
         stderr = getattr(self, 'stderr', OutputWrapper(sys.stderr, self.style.ERROR))
         if options.traceback:
             stderr.write(traceback.format_exc())
         else:
             stderr.write('%s: %s' % (e.__class__.__name__, e))
         sys.exit(1)
     finally:
         orm = ORM.get()
         try:
             session = orm.sessionmaker()
             session.rollback()
             session.close()
         except:
             pass
开发者ID:devhub,项目名称:baph,代码行数:29,代码来源:base.py

示例2: test_readonly_orm_creation

 def test_readonly_orm_creation(self):
     orm = ORM.get()
     session = orm.sessionmaker()
     result = session.execute('SELECT 1').fetchone()
     self.assertEqual(result, (1,))
     session = orm.sessionmaker(readonly=True)
     result = session.execute('SELECT 1').fetchone()
     self.assertEqual(result, (1,))
开发者ID:alvaromartin,项目名称:baph,代码行数:8,代码来源:test_orm.py

示例3: register

    def register(self, request, oauth_token, oauth_verifier, given_name,
                 family_name, email):
        if hasattr(request, 'orm'):
            session = request.orm.sessionmaker()
        else:
            from baph.db.orm import ORM
            session = ORM.get().sessionmaker()
        request_token = request.session.pop(SESSION_KEY, None)
        if request_token and request_token.key == oauth_token:
            twitter = Twitter(request_token)
            access_token = twitter.get_access_token(oauth_verifier)
            if not access_token:
                return False
            profile = session.query(TwitterProfile) \
                             .filter_by(key=access_token.key,
                                        secret=access_token.secret) \
                             .first()
            if profile:
                user_obj = profile.user
            else:
                # Check that the username is unique, and if so, create a user
                # and profile
                twitter_user = twitter.user
                username = 'twitter:%s' % twitter_user.id
                user_ct = session.query(User) \
                                 .filter_by(username=username) \
                                 .count()
                if user_ct == 0:
                    user_obj = User.create_user(username=username,
                                                email=email,
                                                password=None,
                                                session=session)
                    user_obj.first_name = given_name
                    user_obj.last_name = family_name
                    profile = TwitterProfile(user=user_obj,
                                             uid=twitter_user.id,
                                             username=twitter.username,
                                             access_token=access_token)
                    session.add(profile)
                    session.commit()
                else:
                    # Should we redirect here, or return False and redirect in
                    # post_registration_redirect?
                    return False

            signals.user_registered.send(sender=self.__class__, user=user_obj,
                                         request=request)

            user = authenticate(oauth_token=access_token.key,
                                uid=twitter_user.id, session=session)
            login(request, user)
        elif request.user.is_authenticated():
            user_obj = request.user
        else:
            # Perhaps we should handle this differently?
            user_obj = AnonymousUser()
        return user_obj
开发者ID:alvaromartin,项目名称:baph,代码行数:57,代码来源:__init__.py

示例4: register

    def register(self, request, **kwargs):
        if hasattr(request, 'orm'):
            session = request.orm.sessionmaker()
        else:
            from baph.db.orm import ORM
            session = ORM.get().sessionmaker()
        params = get_user_from_cookie(request.COOKIES,
                                      settings.FACEBOOK_APP_ID,
                                      settings.FACEBOOK_SECRET_KEY)
        if params and 'uid' in params:
            uid = params['uid']
            profile = session.query(FacebookProfile) \
                             .filter_by(uid=uid) \
                             .first()
            if profile:
                user_obj = profile.user
            else:
                # Check that the username is unique, and if so, create a user
                # and profile
                username = 'fb:%s' % uid
                user_ct = session.query(User) \
                                 .filter_by(username=username) \
                                 .count()
                if user_ct == 0:
                    fb = Facebook(params['access_token'])
                    fb_user = fb.user
                    user_obj = User.create_user(username=username,
                                                email=fb_user['email'],
                                                password=None,
                                                session=session)
                    user_obj.first_name = fb_user['first_name']
                    user_obj.last_name = fb_user['last_name']
                    profile = FacebookProfile(
                        user=user_obj,
                        uid=uid,
                        access_token=params['access_token'],
                        expires_in=params['expires'],
                    )
                    session.add(profile)
                    session.commit()
                else:
                    # Should we redirect here, or return False and redirect in
                    # post_registration_redirect?
                    return False

            signals.user_registered.send(sender=self.__class__, user=user_obj,
                                         request=request)

            user = authenticate(uid=uid, session=session)
            login(request, user)
        elif request.user.is_authenticated():
            user_obj = request.user
        else:
            # Perhaps we should handle this differently?
            user_obj = AnonymousUser()
        return user_obj
开发者ID:alvaromartin,项目名称:baph,代码行数:56,代码来源:__init__.py

示例5: test_readonly_session_rollback

 def test_readonly_session_rollback(self):
     orm = ORM.get()
     session = orm.sessionmaker(readonly=True)
     sql = 'SELECT col FROM nonexistent_baph_table'
     try:
         result = session.execute(sql).fetchone()
     except SQLAlchemyError:
         orm.sessionmaker_rollback()
     result = session.execute('SELECT 1').fetchone()
     self.assertEqual(result, (1,))
开发者ID:alvaromartin,项目名称:baph,代码行数:10,代码来源:test_orm.py

示例6: setUpClass

 def setUpClass(cls):
     super(RegistrationModelTests, cls).setUpClass()
     Site.__table__.create()
     User.__table__.create()
     orm = ORM.get()
     cls.session = orm.sessionmaker()
     cls.user_info['session'] = cls.session
     site = Site(id=settings.SITE_ID, domain='example.com',
                 name=u'example.com')
     cls.session.add(site)
     cls.session.commit()
开发者ID:alvaromartin,项目名称:baph,代码行数:11,代码来源:test_models.py

示例7: key_to_value

def key_to_value(obj, key, raw=False):
    """
    Evaluate chained relations against a target object
    """
    from baph.db.orm import ORM

    frags = key.split('.')
    if not raw:
        col_key = frags.pop()
    current_obj = obj
    
    while frags:
        if not current_obj:
            # we weren't able to follow the chain back, one of the 
            # fks was probably optional, and had no value
            return None
        
        attr_name = frags.pop(0)
        previous_obj = current_obj
        previous_cls = type(previous_obj)
        current_obj = getattr(previous_obj, attr_name)

        if current_obj:
            # proceed to next step of the chain
            continue

        # relation was empty, we'll grab the fk and lookup the
        # object manually
        attr = getattr(previous_cls, attr_name)
        prop = attr.property

        related_cls = class_resolver(prop.argument)
        related_col = prop.local_remote_pairs[0][0]
        attr_ = column_to_attr(previous_cls, related_col)
        related_key = attr_.key
        related_val = getattr(previous_obj, related_key)
        if related_val is None:
            # relation and key are both empty: no parent found
            return None

        orm = ORM.get()
        session = orm.sessionmaker()
        current_obj = session.query(related_cls).get(related_val)

    if raw:
        return current_obj

    value = getattr(current_obj, col_key, None)
    if value:
        return str(value).strip()
    return None
开发者ID:devhub,项目名称:baph,代码行数:51,代码来源:utils.py

示例8: setUpClass

    def setUpClass(cls):
        ORM._database = None
        cls.orm = ORM.get()
        cls.session = cls.orm.sessionmaker()
        cls.session.execute('''\
CREATE TABLE test_baph_mapify (
    id INTEGER PRIMARY KEY,
    string VARCHAR(16),
    number_with_decimal_point REAL(10)
);''')
        cls.session.execute('''\
CREATE TABLE test_baph_mapify_join (
    foreign_key INTEGER PRIMARY KEY REFERENCES test_baph_mapify(id),
    other_string VARCHAR(16)
);''')
开发者ID:alvaromartin,项目名称:baph,代码行数:15,代码来源:test_orm.py

示例9: facebook_login

def facebook_login(request):
    if hasattr(request, 'orm'):
        session = request.orm.sessionmaker()
    else:
        from baph.db.orm import ORM
        session = ORM.get().sessionmaker()
    params = get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID,
                                  settings.FACEBOOK_SECRET_KEY)
    if params:
        user = authenticate(uid=params['uid'], session=session)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect(settings.LOGIN_REDIRECT_URL, {}, ())
            else:
                # Disabled account, redirect and notify?
                return redirect('/', {}, ())
        else:
            # Invalid user, redirect and notify?
            return redirect('/', {}, ())
    elif request.user.is_authenticated():
        return redirect(settings.LOGIN_REDIRECT_URL, {}, ())
    else:
        return redirect('/account/register/', {}, ())
开发者ID:alvaromartin,项目名称:baph,代码行数:24,代码来源:views.py

示例10: process_request

 def process_request(self, request):
     request.orm = ORM.get()
开发者ID:devhub,项目名称:baph,代码行数:2,代码来源:orm.py

示例11: test_create_url

 def test_create_url(self):
     # URLs taken from: http://www.sqlalchemy.org/docs/05/dbengine.html
     test_data = [
         {
             'expected': 'postgres://scott:[email protected]/mydatabase',
             'params': {
                 'ENGINE': 'postgres',
                 'USER': 'scott',
                 'PASSWORD': 'tiger',
                 'HOST': 'localhost',
                 'NAME': 'mydatabase',
             },
         },
         {
             'expected': 'postgres://[email protected]/mydatabase',
             'params': {
                 'ENGINE': 'postgres',
                 'USER': 'scott',
                 'HOST': 'localhost',
                 'NAME': 'mydatabase',
             },
         },
         {
             'expected': 'postgres://[email protected]/mydatabase',
             'params': {
                 'ENGINE': 'postgres',
                 'USER': 'scott',
                 'PASSWORD': '',
                 'HOST': 'localhost',
                 'NAME': 'mydatabase',
             },
         },
         {
             'expected': 'oracle://scott:[email protected]',
             'params': {
                 'ENGINE': 'oracle',
                 'USER': 'scott',
                 'PASSWORD': 'tiger',
                 'HOST': 'tnsname',
             },
         },
         {
             'expected': 'mssql://mydsn',
             'params': {
                 'ENGINE': 'mssql',
                 'HOST': 'mydsn',
             },
         },
         {
             'expected': 'sqlite:///foo.db',
             'params': {
                 'ENGINE': 'sqlite',
                 'NAME': 'foo.db',
             },
         },
         {
             'expected': 'sqlite:////absolute/path/to/foo.db',
             'params': {
                 'ENGINE': 'sqlite',
                 'NAME': '/absolute/path/to/foo.db',
             },
         },
         {
             'expected': 'sqlite:////absolute/path/to/foo.db',
             'params': {
                 'ENGINE': 'sqlite',
                 'USER': '',
                 'PASSWORD': '',
                 'HOST': '',
                 'NAME': '/absolute/path/to/foo.db',
             },
         },
         {
             'expected': 'sqlite://',
             'params': {
                 'ENGINE': 'sqlite',
             },
         },
     ]
     for data in test_data:
         self.assertEqual(ORM._create_url(data['params']),
                          data['expected'])
开发者ID:alvaromartin,项目名称:baph,代码行数:82,代码来源:test_orm.py

示例12: setUpClass

 def setUpClass(cls):
     super(RegistrationViewTests, cls).setUpClass()
     User.__table__.create()
     orm = ORM.get()
     cls.session = orm.sessionmaker()
开发者ID:saebyn,项目名称:baph,代码行数:5,代码来源:test_views.py

示例13: handle_noargs

    def handle_noargs(self, **options):

        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        show_traceback = options.get('traceback')
        load_initial_data = options.get('load_initial_data')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError as exc:
                # This is slightly hackish. We want to ignore ImportErrors
                # if the "management" module itself is missing -- but we don't
                # want to ignore the exception if the management module exists
                # but raises an ImportError for some reason. The only way we
                # can do this is to check the text of the exception. Note that
                # we're a bit broad in how we check the text, because different
                # Python implementations may not use the same text.
                # CPython uses the text "No module named management"
                # PyPy uses "No module named myproject.myapp.management"
                msg = exc.args[0]
                if not msg.startswith('No module named') or 'management' not in msg:
                    raise

        db = options.get('database')
        orm = ORM.get(db)
        engine = orm.engine
        default_schema = engine.url.database

        # the default db may not exist yet, so we remove it before connecting
        engine.url.database = None
        frags = str(engine.url).split('?')
        tmp_url = frags[0]
        if len(frags) == 2:
            if not tmp_url.endswith('/'):
                # query strings will break this if it doesn't end with a /
                tmp_url += '/'
            tmp_url += '?%s' % frags[1]
        engine.url.database = default_schema

        tmp_engine = create_engine(tmp_url)
        tmp_conn = tmp_engine.connect()
        existing_schemas = set([s[0] for s in tmp_conn.execute('show databases')])
        if not default_schema in existing_schemas:
            tmp_engine.execute(CreateSchema(default_schema))
            existing_schemas.add(default_schema)
        
        orm = ORM.get(db)

        # now reconnect with the default_db provided
        conn = engine.connect()
        Base.metadata.bind = engine
        
        if verbosity >= 3:
            self.stdout.write("Getting existing schemas...\n")
            for schema in existing_schemas:
                self.stdout.write("\t%s\n" % schema)
            else:
                self.stdout.write("\tNone\n")

        existing_tables = []
        if verbosity >= 1:
            self.stdout.write("Getting existing tables...\n")
        for schema in existing_schemas:
            for name in engine.engine.table_names(schema, connection=conn):
                existing_tables.append('%s.%s' % (schema,name))
                if verbosity >= 3:
                    self.stdout.write("\t%s.%s\n" % (schema,name))    

        existing_models = []
        if verbosity >= 1:
            self.stdout.write("Getting existing models...\n")
        for cls_name, cls in Base._decl_class_registry.items():
            tablename = get_tablename(cls)
            if tablename and tablename in existing_tables:
                existing_models.append(cls)
                if verbosity >= 3:
                    self.stdout.write("\t%s\n" % cls)

        all_tables = []
        if verbosity >= 1:
            self.stdout.write("Getting required tables...\n")
        for table in Base.metadata.sorted_tables:
            tablename = get_tablename(table)
            all_tables.append(tablename)
            if verbosity >= 3:
                self.stdout.write("\t%s\n" % tablename)

        all_models = []
        if verbosity >= 1:
            self.stdout.write("Getting required models...\n")
        for app in get_apps():
            for model in get_models(app, include_auto_created=True):
                app_name = app.__name__.rsplit('.',1)[0]
                all_models.append( (app_name, model) )
                if verbosity >= 3:
#.........这里部分代码省略.........
开发者ID:devhub,项目名称:baph,代码行数:101,代码来源:syncdb.py

示例14: test_readonly_session_remove

 def test_readonly_session_remove(self):
     # Please fix...this is not very useful IMO. -Mark
     orm = ORM.get()
     session = orm.sessionmaker(readonly=True)
     session.execute('SELECT 1')
     orm.sessionmaker_remove()
开发者ID:alvaromartin,项目名称:baph,代码行数:6,代码来源:test_orm.py

示例15: loaddata

    def loaddata(self, fixture_labels):
        #connection = connections[self.using]
        connection = orm = ORM.get(self.using)

        # Keep a count of the installed objects and fixtures
        self.fixture_count = 0
        self.loaded_object_count = 0
        self.fixture_object_count = 0
        self.models = set()

        self.serialization_formats = serializers.get_public_serializer_formats()
        # Forcing binary mode may be revisited after dropping Python 2 support (see #22399)
        self.compression_formats = {
            None: (open, 'rb'),
            'gz': (gzip.GzipFile, 'rb'),
            'zip': (SingleZipReader, 'r'),
        }
        if has_bz2:
            self.compression_formats['bz2'] = (bz2.BZ2File, 'r')

        '''
        with connection.constraint_checks_disabled():
            for fixture_label in fixture_labels:
                self.load_label(fixture_label)
        '''
        session = orm.sessionmaker()
        session.close()
        for fixture_label in fixture_labels:
            self.load_label(fixture_label)
        session.commit()

        # Since we disabled constraint checks, we must manually check for
        # any invalid keys that might have been added
        # TODO: implement this
        '''
        table_names = [model._meta.db_table for model in self.models]
        try:
            connection.check_constraints(table_names=table_names)
        except Exception as e:
            e.args = ("Problem installing fixtures: %s" % e,)
            raise
        '''

        # If we found even one object in a fixture, we need to reset the
        # database sequences.
        # TODO: implement this
        '''
        if self.loaded_object_count > 0:
            sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models)
            if sequence_sql:
                if self.verbosity >= 2:
                    self.stdout.write("Resetting sequences\n")
                cursor = connection.cursor()
                for line in sequence_sql:
                    cursor.execute(line)
                cursor.close()
        '''
        if self.fixture_count == 0 and self.hide_empty:
            pass
        elif self.fixture_object_count == self.loaded_object_count:
            logger.info("Installed %d object(s) from %d fixture(s)" %
                    (self.loaded_object_count, self.fixture_count))
        else:
            logger.info("Installed %d object(s) (of %d) from %d fixture(s)" %
                    (self.loaded_object_count, self.fixture_object_count,
                     self.fixture_count))
开发者ID:devhub,项目名称:baph,代码行数:66,代码来源:loaddata.py


注:本文中的baph.db.orm.ORM类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。