• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.DBSession类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: validate

def validate(captcha_id, code):
    with transaction.manager:
        captcha = DBSession.query(CaptchaCode).get(captcha_id)
        if not captcha:
            return False
        # 大约有 1% 的概率,执行清除一天前的旧数据任务
        if random.random() < 0.01:
            today = datetime.date.today()
            today = datetime.datetime(today.year, today.month, today.day)
            DBSession.query(CaptchaCode).filter(
                CaptchaCode.created<today).delete()

        result = captcha.code.lower() == code.lower()
        DBSession.delete(captcha)
        return result
开发者ID:vincentwyshan,项目名称:tap,代码行数:15,代码来源:tcaptcha.py


示例17: valid_key

def valid_key(key, config):
    """
    :param key: access_key
    :return: (bool, client_id)
    """
    if not key:
        return False, None

    if not config.auth_clients:
        return False, None

    # TODO Performance improvement. support redis/memcached/mongodb
    cache_client_id = get_val(key, expire=3600)
    if cache_client_id is not None:
        for auth in config.auth_clients:
            if auth.client_id == cache_client_id:
                return True, auth.client_id

    with transaction.manager:
        for auth in config.auth_clients:
            access_key = DBSession.query(TapApiAccessKey).filter_by(
                access_key=key, client_id=auth.client_id).first()
            if not access_key:
                # return False, None
                continue

            expire = access_key.access_expire
            if expire >= time.time():
                # set key again
                set_val(key, access_key.client_id)
                return True, access_key.client_id
        return False, access_key.client_id
开发者ID:vincentwyshan,项目名称:tap,代码行数:32,代码来源:auth.py


示例18: gen_active

def gen_active(request):
    result = dict()
    if request.path.startswith('/management/database'):
        result['active_database'] = True
    elif request.path.startswith('/management/project'):
        result['active_project'] = True
        try:
            result['current_project_id'] = int(request.matchdict['project_id'])
        except:
            pass
    elif request.path.startswith('/management/api'):
        result['active_project'] = True
        api_id = int(request.matchdict['api_id'])
        with transaction.manager:
            try:
                api = DBSession.query(TapApi).get(api_id)
                result['current_project_id'] = api.project.id
            except:
                pass
    elif request.path == '/':
        result['active_home'] = True
    elif request.path.startswith('/management/client'):
        result['active_client'] = True
    elif request.path.startswith('/management/user'):
        result['active_users'] = True
    elif request.path.startswith('/management/docs'):
        result['active_docs'] = True
    return result
开发者ID:vincentwyshan,项目名称:tap,代码行数:28,代码来源:uicontrol.py


示例19: para_new

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

            with transaction.manager:
                api_id = int(api_id)
                para = TapParameter(api_id=api_id, name='__None__')
                DBSession.add(para)
                DBSession.flush()
                result["para_id"] = para.id
                result["para_name"] = '__None__'
                result["success"] = 1
        except BaseException, e:
            result["message"] = str(e)
开发者ID:vincentwyshan,项目名称:tap,代码行数:16,代码来源:actions.py


示例20: client_paranew

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

            with transaction.manager:
                auth_id = int(auth_id)
                para = TapApiClientCustomPara(customauth_id=auth_id,
                                              name='__None__')
                DBSession.add(para)
                DBSession.flush()
                result["para_id"] = para.id
                result["para_name"] = '__None__'
                result["success"] = 1
        except BaseException, e:
            result["message"] = str(e)
开发者ID:vincentwyshan,项目名称:tap,代码行数:17,代码来源:actions.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python parser.Parser类代码示例发布时间:2022-05-27
下一篇:
Python tankcore.AbstractPlugin类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap