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


Python ORM.get方法代码示例

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


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

示例1: run_from_argv

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 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,代码行数:31,代码来源:base.py

示例2: test_readonly_orm_creation

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 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,代码行数:10,代码来源:test_orm.py

示例3: register

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
    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,代码行数:59,代码来源:__init__.py

示例4: register

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
    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,代码行数:58,代码来源:__init__.py

示例5: test_readonly_session_rollback

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 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,代码行数:12,代码来源:test_orm.py

示例6: setUpClass

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 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,代码行数:13,代码来源:test_models.py

示例7: key_to_value

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
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,代码行数:53,代码来源:utils.py

示例8: setUpClass

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
    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,代码行数:17,代码来源:test_orm.py

示例9: facebook_login

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
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,代码行数:26,代码来源:views.py

示例10: setUpClass

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 def setUpClass(cls):
     cls.orm = ORM.get()
开发者ID:alvaromartin,项目名称:baph,代码行数:4,代码来源:test_db.py

示例11: loaddata

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
    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,代码行数:68,代码来源:loaddata.py

示例12: handle_noargs

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
    def handle_noargs(self, **options):
        verbosity = 1 #int(options.get('verbosity'))
        interactive = options.get('interactive')
        show_traceback = options.get('traceback')

        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)
        db_info = orm.settings_dict
        is_test_db = db_info.get('TEST', False)
        if not is_test_db:
            print 'Database "%s" cannot be purged because it is not a test ' \
                  'database.\nTo flag this as a test database, set TEST to ' \
                  'True in the database settings.' % db
            sys.exit()

        if interactive:
            confirm = raw_input('\nYou have requested a purge of database ' \
                '"%s" (%s). This will IRREVERSIBLY DESTROY all data ' \
                'currently in the database, and DELETE ALL TABLES AND ' \
                'SCHEMAS. Are you sure you want to do this?\n\n' \
                'Type "yes" to continue, or "no" to cancel: ' \
                % (db, orm.engine.url))
        else:
            confirm = 'yes'

        if confirm == 'yes':
            # get a list of all schemas used by the app
            default_schema = orm.engine.url.database
            app_schemas = set(orm.Base.metadata._schemas)
            app_schemas.add(default_schema)

            url = deepcopy(orm.engine.url)
            url.database = None
            engine = create_engine(url)
            inspector = inspect(engine)

            # get a list of existing schemas
            db_schemas = set(inspector.get_schema_names())

            schemas = app_schemas.intersection(db_schemas)

            app_tables = set()
            for table in orm.Base.metadata.tables.values():
                schema = table.schema or default_schema
                app_tables.add('%s.%s' % (schema, table.name))

            metadata = MetaData()
            db_tables = []
            all_fks = []

            for schema in schemas:
                for table_name in inspector.get_table_names(schema):
                    fullname = '%s.%s' % (schema, table_name)
                    if fullname not in app_tables:
                        continue
                    fks = []
                    for fk in inspector.get_foreign_keys(table_name, schema=schema):
                        if not fk['name']:
                            continue
                        fks.append(ForeignKeyConstraint((),(),name=fk['name']))
                    t = Table(table_name, metadata, *fks, schema=schema)
                    db_tables.append(t)
                    all_fks.extend(fks)

            session = Session(bind=engine)
            for fkc in all_fks:
                session.execute(DropConstraint(fkc))
            for table in db_tables:
                session.execute(DropTable(table))
            for schema in schemas:
                session.execute(DropSchema(schema))
            session.commit()
            session.bind.dispose()

        else:
            self.stdout.write("Purge cancelled.\n")
开发者ID:devhub,项目名称:baph,代码行数:99,代码来源:purge.py

示例13: handle_noargs

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
    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,代码行数:103,代码来源:syncdb.py

示例14: test_readonly_session_remove

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 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,代码行数:8,代码来源:test_orm.py

示例15: setUpClass

# 需要导入模块: from baph.db.orm import ORM [as 别名]
# 或者: from baph.db.orm.ORM import get [as 别名]
 def setUpClass(cls):
     super(RegistrationViewTests, cls).setUpClass()
     User.__table__.create()
     orm = ORM.get()
     cls.session = orm.sessionmaker()
开发者ID:saebyn,项目名称:baph,代码行数:7,代码来源:test_views.py


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