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


Python models.DBSession类代码示例

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


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

示例1: get_userperm

    def get_userperm(self, perm_name):
        # import pdb; pdb.set_trace()
        with transaction.manager:
            need_permission, action = perm_name.split(':')
            permission = DBSession.query(TapPermission).filter_by(
                name=need_permission).first()
            user_perm = DBSession.query(TapUserPermission).filter_by(
                user_id=self.request.user.id, permission_id=permission.id).first()

            user_perm = TempPermission(user_perm)

            if not need_permission.startswith('SYS') and '.' in need_permission:
                # if parent-permission has the authorization,
                # also child-permission has it.
                permissions = need_permission.split('.')
                for i in range(len(permissions)):
                    permission = '.'.join(permissions[:i+1])
                    permission = DBSession.query(TapPermission).filter_by(
                        name=permission
                    ).first()
                    if not permission:
                        continue
                    _perm = DBSession.query(TapUserPermission).filter_by(
                        user_id=self.request.user.id,
                        permission_id=permission.id
                    ).first()
                    if _perm:
                        user_perm.a_add = (user_perm.a_add or _perm.a_add)
                        user_perm.a_edit = (user_perm.a_edit or _perm.a_edit)
                        user_perm.a_delete = (user_perm.a_delete or
                                              _perm.a_delete)
                        user_perm.a_view = (user_perm.a_view or _perm.a_view)
            return user_perm
开发者ID:vincentwyshan,项目名称:tap,代码行数:33,代码来源:security.py

示例2: release_save

    def release_save(self):
        result = dict(success=0, message="")
        request = self.request
        try:

            with transaction.manager:
                api_id = request.params.get('api_id')
                api_id = int(api_id)
                api = DBSession.query(TapApi).get(api_id)

                # auth type, change api
                auth_type = request.params['auth_type']
                if auth_type != api.auth_type:
                    api.auth_type = auth_type

                release = TapApiRelease()
                release.api_id = api.id
                release.project_name = api.project.name
                release.api_name = api.name
                # release.dbconn_id = api.dbconn_id
                release.version = request.params['version']
                release.notes = request.params['notes']
                release.uid_release = request.userid
                release.content = json.dumps(api2dict(api), cls=TapEncoder)
                DBSession.add(release)
                api.status = 'RELEASE'
                result["success"] = 1
        except BaseException, e:
            import traceback; traceback.print_exc()
            result["message"] = str(e)
开发者ID:vincentwyshan,项目名称:tap,代码行数:30,代码来源:actions.py

示例3: project_save

 def project_save(self):
     result = dict(success=0, message="")
     try:
         with transaction.manager:
             project = None
             project_id = self.request.params.get('id')
             if project_id:
                 project = DBSession.query(TapProject).get(project_id)
             else:
                 name_valid(self.request.params.get('name'))
                 assert self.request.params.get('cnname') not in ('', None), "名称不能为空"
                 project = TapProject()
                 DBSession.add(project)
                 project.uid_create = self.request.userid
                 project.uid_owner = self.request.userid
                 project.name = self.request.params.get('name').strip().upper()
                 project.cnname = self.request.params.get('cnname').strip()
                 project.description = self.request.params.get('description')  or ''
                 permission = add_permission(
                     project.name, u'项目:' + project.name)
                 DBSession.flush()
                 add_user_permission(self.request.user, permission,
                                     True, True, True, True)
             if 'name' in self.request.params:
                 name_valid(self.request.params.get('name'))
                 project.name = self.request.params.get('name').strip().upper()
             obj_setattr(project, 'cnname', self.request)
             obj_setattr(project, 'description', self.request)
         result["success"] = 1
     except BaseException, e:
         result["message"] = str(e)
开发者ID:vincentwyshan,项目名称:tap,代码行数:31,代码来源:actions.py

示例4: gen_breadcrumbs

def gen_breadcrumbs(request):
    result = []
    if request.path.startswith('/management/database'):
        result.append(
            {"url": '/management/database', "class": "active", "text": u"数据库"}
        )
        if request.matchdict.get('dbconn_id') is not None:
            with transaction.manager:
                dbconn_id = request.matchdict['dbconn_id']
                dbconn = DBSession.query(TapDBConn).get(dbconn_id)
                result.append(
                    {"class": "active", "text": dbconn.name}
                )
    elif request.path == '/management/project':
        result.append(
            {"url": '/management/project', "class": "active", "text": u"项目"}
        )
    elif re.match(ur"/management/project/\d+", request.path):
        project_id = re.findall(r'\d+', request.path)[0]
        with transaction.manager:
            project = DBSession.query(TapProject).get(project_id)
            result.append(
                {"url": '/management/project', "class": "", "text": u"项目"},
            )
            result.append(
                {"class": "active", "text": project.cnname},
            )
开发者ID:vincentwyshan,项目名称:tap,代码行数:27,代码来源:uicontrol.py

示例5: user_save

 def user_save(self):
     result = dict(success=0, message="")
     try:
         with transaction.manager:
             user = None
             user_id = self.request.params.get('id')
             if user_id:
                 user = DBSession.query(TapUser).get(user_id)
             else:
                 name_valid(self.request.params['name'])
                 user = DBSession.query(TapUser).filter_by(
                     name=self.request.params['name']).first()
                 if user:
                     raise Exception("用户名重复")
                 user = TapUser()
                 DBSession.add(user)
                 user.name = self.request.params.get('name').strip()
             obj_setattr(user, 'full_name', self.request)
             obj_setattr(user, 'description', self.request)
             if 'is_admin' in self.request.params:
                 user.is_admin = int(self.request.params['is_admin'])
             if 'password' in self.request.params:
                 password = self.request.params.get('password').strip()
                 assert len(password) >= 6, '密码长度最少为6'
                 if 'password-repeat' in self.request.params:
                     password_repeat = self.request.params['password-repeat']
                     assert password == password_repeat, "两次输入密码不匹配"
                 user.password = encrypt_password(password.encode('utf8'))
         result["success"] = 1
     except BaseException, e:
         result["message"] = str(e)
开发者ID:vincentwyshan,项目名称:tap,代码行数:31,代码来源:actions.py

示例6: main

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    global globalsettings
    globalsettings = settings

    engine = engine_from_config(settings, 'sqlalchemy.', pool_recycle=1800)
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    config = Configurator(settings=settings)

    from tap.security import groupfinder, get_user, get_user_id

    # attach shortcut property
    config.add_request_method(get_user, 'user', reify=True)
    config.add_request_method(get_user_id, 'userid', reify=True)

    # template
    config.include('pyramid_mako')
    config.add_mako_renderer('.html')

    # Security policies
    authn_policy = AuthTktAuthenticationPolicy(
        settings['tap.secret'], callback=groupfinder, hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    add_route(config)
    add_srv_route(config)

    config.scan()
    return config.make_wsgi_app()
开发者ID:vincentwyshan,项目名称:tap,代码行数:34,代码来源:__init__.py

示例7: initdb

def initdb():
    config_uri = sys.argv[1]
    # options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
开发者ID:vincentwyshan,项目名称:tap,代码行数:8,代码来源:dbtools.py

示例8: gen_captcha

def gen_captcha():
    with transaction.manager:
        code = random.sample(chars, 5)
        captcha = CaptchaCode()
        captcha.code = unicode(''.join(code))
        DBSession.add(captcha)
        DBSession.flush()
        assert captcha.id is not None
        return captcha.id
开发者ID:vincentwyshan,项目名称:tap,代码行数:9,代码来源:tcaptcha.py

示例9: setUp

 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from .models import (
         Base,
         MyModel,
         )
     DBSession.configure(bind=engine)
开发者ID:vincentwyshan,项目名称:tap,代码行数:9,代码来源:tests.py

示例10: add_user_permission

def add_user_permission(user, permission, view=False, edit=False,
                        add=False, delete=False):
    user_permission = TapUserPermission()
    user_permission.user_id = user.id
    user_permission.permission_id = permission.id
    user_permission.a_view = view
    user_permission.a_edit = edit
    user_permission.a_add = add
    user_permission.a_delete = delete
    DBSession.add(user_permission)
开发者ID:vincentwyshan,项目名称:tap,代码行数:10,代码来源:initializedb.py

示例11: add_permission

def add_permission(name, desc):
    permission = DBSession.query(TapPermission).filter_by(
        name=name).first()
    if permission:
        return
    permission = TapPermission()
    permission.name = name
    permission.description = desc
    DBSession.add(permission)
    return permission
开发者ID:vincentwyshan,项目名称:tap,代码行数:10,代码来源:initializedb.py

示例12: require_key

def require_key(request):
    """
    :param request: token[token string], expire[expire time int]
    :return: access_key, expire_time
    """
    token = request.params['token']
    expire = int(request.params.get('expire', 600))
    if expire < 600:
        expire = 600
    with transaction.manager:
        # access_key 不应该与 api 挂钩
        client = DBSession.query(TapApiClient).filter_by(token=token).first()
        if not client:
            raise TapAuthFail

        if client.auth_type == 'TOKEN':
            pass
        elif client.auth_type == 'CUSTOM':
            container = {}
            source = client.custom_auth.source.encode('utf8')
            paras = ParaHandler.prepare(request.params,
                                            client.custom_auth.paras)
            variables = {}
            for k, v in paras.items():
                if k in ('main', '__builtins__'):
                    continue
                variables[k] = v
            exec source in container
            container.update(variables)
            check = False
            try:
                check = container['main']()
            except BaseException as error:
                return response_err(str(error), 500)
            if check is not True:
                return response_err('Auth Failed', 403)

        key = str(uuid.uuid4())
        access_key = TapApiAccessKey()
        # access_key.api_id = auth.api_id
        # access_key.auth_id = auth.id
        access_key.client_id = client.id
        access_key.access_key = key
        access_key.access_expire = int(time.time()) + expire
        DBSession.add(access_key)

        # TODO Performance improvement. support redis/memcached/mongodb
        # insert access_key to redis/memcached/mongodb
        set_val(key, client.id)

        result = dict(access_key=key, expire_time=access_key.access_expire)
        response = Response(json.dumps(result),
                            headerlist=[('Access-Control-Allow-origin', '*',)])
        response.content_type = "application/json"
        return response
开发者ID:vincentwyshan,项目名称:tap,代码行数:55,代码来源:auth.py

示例13: client_paradelete

    def client_paradelete(self):
        result = dict(success=0, message="")
        request = self.request
        para_id = request.params.get('id')
        try:

            with transaction.manager:
                para_id = int(para_id)
                para = DBSession.query(TapApiClientCustomPara).get(para_id)
                DBSession.delete(para)
                result["success"] = 1
        except BaseException, e:
            result["message"] = str(e)
开发者ID:vincentwyshan,项目名称:tap,代码行数:13,代码来源:actions.py

示例14: cache_get

 def cache_get(self):
     result = dict(success=0, message="")
     api_id = int(self.request.params['api_id'])
     version = int(self.request.params['version'])
     with transaction.manager:
         api = DBSession.query(TapApi).get(api_id)
         release = DBSession.query(TapApiRelease)\
             .filter_by(api_id=api.id, version=version).first()
         config = dict2api(json.loads(release.content))
         data = cache_get(config, release.version, dict(self.request.params))
         result['data'] = data
     result['success'] = 1
     return result
开发者ID:vincentwyshan,项目名称:tap,代码行数:13,代码来源:actions.py

示例15: main_service

def main_service(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    config = Configurator(settings=settings)

    add_srv_route(config)

    config.scan()
    return config.make_wsgi_app()
开发者ID:vincentwyshan,项目名称:tap,代码行数:13,代码来源:__init__.py


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