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


Python DBSession.query方法代码示例

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


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

示例1: get_menu_desc

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def get_menu_desc(menu, for_calendar):
    desc = ''
    json_result = []
    if len(menu.menus) < 1:
        return ''
    for menu_item_id in menu.menus.split(' '):
        menu_item = DBSession.query(MenuItem).filter(MenuItem.id==menu_item_id).one()
        allergens = DBSession.query(Allergen).filter(Allergen.menu_item_id==menu_item.id).all()
        allergen_string = ', '.join([a.allergen for a in allergens])
        desc = '\n' + desc
        menu_item_name = menu_item.name.decode('utf8')
        desc = desc + menu_item_name
        if  menu_item.healthy:
            if for_calendar:
                desc = desc + '\n' + health_icon[menu_item.healthy-1].decode('utf8') + ' ' + HEALTHY_FACTOR[menu_item.healthy-1] + ' '
            else:
                desc = desc + '\n' + '(' + HEALTHY_FACTOR[menu_item.healthy-1] + ') '

        desc = desc + '\n'
        menu_item_desc = ''
        if len(menu_item.description.decode('utf8')):
            menu_item_desc = menu_item.description.decode('utf8')
            desc = desc + menu_item_desc + '\n'
        if len(allergen_string):
            desc = desc + '(' + allergen_string + ')\n\n'
        json_result.append((menu_item_name, menu_item_desc))
    return desc.strip('\n')
开发者ID:tinawen,项目名称:menu,代码行数:29,代码来源:gcalendar.py

示例2: attach_pictures

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def attach_pictures(request):
    menu_query = DBSession.query(Menu).filter(Menu.id==request.matchdict['menu_id'])
    images_id = menu_query.one().images_id
    images_id = images_id.split(' ') if images_id else []
    if images_id:
        images = DBSession.query(Image).filter(Image.id.in_(images_id)).all()
    added_thumbs = []
    if "data" in request.params:
        data = json.loads(request.params["data"])
        for image_info in data:
            image, thumb = image_info
            if not image or not thumb:
                continue
            ext = os.path.splitext(image)[-1].lower()
            if ext in (".jpg", ".jpeg", ".png"):
                new_image = Image(image_url=image, thumb_url=thumb)
                added_thumbs.append(thumb)
                DBSession.add(new_image)
                DBSession.flush()
                DBSession.refresh(new_image)
                images_id.append(new_image.id)
        menu_query.update({
                "images_id": ' '.join([str(i) for i in images_id]),
                })
    return json.dumps(added_thumbs)
开发者ID:tinawen,项目名称:menu,代码行数:27,代码来源:views.py

示例3: user_get

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def user_get(request):
    dbsession = DBSession()
    name = clean_matchdict_value(request, 'user')
    user = dbsession.query(User).filter(User.name == name).one()
    user_data = dbsession.query(UserData).filter(UserData.user_id == user.id).one()
    user_json = convert.decodeUser(request, dbsession, user, user_data)
    return {'status': 'success', 'user': user_json}
开发者ID:vishakh,项目名称:metamkt,代码行数:9,代码来源:views.py

示例4: is_allowed

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def is_allowed(request, routename, method='ALL', check_route=True):
    """
    Given a request_object, routename and method; returns True if current user has access to that route,
    otherwise returns False.

    If check_route if False, does not check the DB to see if the route is in the list of protected routes
    """

    if check_route:
        route = DBSession.query(RoutePermission).filter_by(route_name=routename).first()
        if not route:
            return True

    if not isinstance(method, list):
        method = [method, ]

    user_permissions = request.session.get('auth_user_permissions', [])
    if request.session.get('auth_static_permission', None):
        user_permissions.append(request.session.get('auth_static_permission', None))

    has_permission = DBSession.query(func.count(RoutePermission.permission)).filter(
                                            RoutePermission.route_name == routename).filter(
                                            RoutePermission.method.in_(method)).filter(
                                            RoutePermission.permission.in_(user_permissions)).scalar()

    if has_permission > 0:
        return True
    else:
        return False
开发者ID:AnamAtiq,项目名称:CDSR,代码行数:31,代码来源:auth.py

示例5: job_archive

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
    def job_archive():
        """
        Returns the job archive from the database
        :return:
        """
        jobs_stmt = DBSession.query(Job).order_by(Job.updatetime.desc()).all()
        jobs_dict = []
        for jobs in jobs_stmt:
            job_outputs = DBSession.query(JobOutput).filter(JobOutput.jobid == jobs.id).all()
            jobs = jobs.__dict__

            if 'jobinfo' in jobs and jobs['jobinfo'] is not None:
                obj = jsonpickle.decode(jobs['jobinfo'])
                try:
                    jobs.update(obj)
                except BaseException as e:
                    print(str(e))

            if 'jobdetails' in jobs and jobs['jobdetails'] is not None:
                obj = jsonpickle.decode(jobs['jobdetails'])
                try:
                    jobs.update(obj)
                except BaseException as e:
                    print(str(e))
            jobs['number_of_joboutputs'] = len(job_outputs)
            jobs['joboutputs'] = []
            for outputs in job_outputs:
                jobs['joboutputs'].append(outputs.__dict__)
            jobs_dict.append(jobs)
        return jobs_dict
开发者ID:meyerjo,项目名称:ClusterJobMonitor,代码行数:32,代码来源:job_database_wrapper.py

示例6: login

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def login(request):
    """Returns a tuple of (authenticated) uid, and a message string.
    If the user could not be authenticated (or they didn't try), the uid
    will be None. If the user successfully logged in, sets a session
    cookie for this session."""
    
    session = DBSession()

    uid = authenticated_userid(request)
    if uid:
        return session.query(User).get(uid), None

    if 'user' in request.params and 'passwd' in request.params:
        uid = request.params['user']
        passwd = request.params['passwd']
        user = session.query(User).get(uid)
        if not user:
            return None, "Invalid user or password."

        if user.check_pw(passwd):
            headers = remember(request, uid)
            request.response.headerlist.extend(headers)
            return user, "Logged in Successfully"
        else:
            return None, "Invalid user or password."
    else:
        return None, None
开发者ID:pflarr,项目名称:basic_site,代码行数:29,代码来源:security.py

示例7: update_menu_item_desc

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def update_menu_item_desc(request):
    menu_item_id = request.matchdict['menu_item_id']
    menuItem = DBSession.query(MenuItem).filter(MenuItem.id==menu_item_id)
    new_desc = urllib.unquote(request.json_body).encode('utf8')
    menuItem.update({"description":new_desc})
    menu = DBSession.query(Menu).filter(Menu.id==menuItem.one().menu_id).one()
    update_gcalendar(menu)
    return 'ok'
开发者ID:tinawen,项目名称:menu,代码行数:10,代码来源:views.py

示例8: auth_request

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
    def auth_request(request):

        response = None

        # ignore static routes for authentication
        if 'static' in request.path.split('/'):
            return handler(request)

        logged_in_user = request.session.get('logged_in_user', None)

        protected_routes = []
        routes = DBSession.query(RoutePermission.route_name).distinct().all()

        for R in routes:
            protected_routes.append(R[0])

        #print(protected_routes)
        matched_routename = None

        for r in request.registry.introspector.get_category('routes'):
            R = r['introspectable']

            matcher, generator = _compile_route(R['pattern'])

            if type(matcher(request.path)) == types.DictionaryType:
                #print(R['name'] + ':' + R['pattern'])
                matched_routename = R['name']
                break

        # Check routes from protected routes here.
        if matched_routename and matched_routename in protected_routes:
            # first check if there is any static permission given and if yes then validate routes against that permission
            user_permissions = []
            if request.session.get('auth_static_permission', None):
                user_permissions.append(request.session.get('auth_static_permission', None))
            else:
                if not logged_in_user:
                    return HTTPForbidden()

                # get user permissions
                user_permissions = request.session.get('auth_user_permissions', [])

            # get route permissions for the current route
            # match if there are any common permissions and check for all matching request methods
            has_permission = DBSession.query(func.count(RoutePermission.permission)).filter(
                                            RoutePermission.route_name == matched_routename).filter(
                                            or_(RoutePermission.method == 'ALL',
                                                RoutePermission.method == request.method)).filter(
                                            RoutePermission.permission.in_(user_permissions)).scalar()

            if has_permission > 0:
                return handler(request)
            else:
                return HTTPForbidden()

        else:
            return handler(request)
开发者ID:DroneOs,项目名称:SpyCar,代码行数:59,代码来源:auth.py

示例9: make_session

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def make_session(user, sessionid=None, expires_in=3600):
    if not sessionid:
        sessionid = str(uuid.uuid4())
    DBSession.query(Session).filter(Session.sessionid == sessionid).delete()
    logging.debug("making session for %s with sessionid %s" % (user.username, sessionid))
    s = Session(user_id=user.id, sessionid=sessionid, expires=datetime.datetime.now() + datetime.timedelta(0, expires_in))
    DBSession.add(s)
    DBSession.flush()
    DBSession.expunge(s)
    return s
开发者ID:wayetender,项目名称:corvorant,代码行数:12,代码来源:db.py

示例10: get_entries

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def get_entries(request):		
	#todo this searching is terrible but it's a POC
	if not any(param == 'search' for param in request.params) or request.GET['search'] == '':
		data = DBSession.query(m.Entry).order_by(m.Entry.start_datetime.desc()).slice(0, 10).all()
	else:		
		searchExpression = '%' + request.GET['search'] + '%'
		data = DBSession.query(m.Entry) \
			.filter((m.Entry.content.ilike(searchExpression) | m.Entry.title.ilike(searchExpression))) \
			.all()
	return utilities.serialize(data)
开发者ID:aarongreenwald,项目名称:pim,代码行数:12,代码来源:views.py

示例11: refresh_menu

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def refresh_menu(menu):
    menu_items = []
    allergens = []
    for menu_item_id in menu.menus and menu.menus.split(' '):
        menu_item = DBSession.query(MenuItem).filter(MenuItem.id==menu_item_id).one()
        allergen_array = DBSession.query(Allergen).filter(Allergen.menu_item_id==menu_item.id).all()
        menu_items.append(menu_item)
        allergens.append([a.allergen for a in allergen_array])

    return dict(menu_items=menu_items, allergens=allergens, menu=menu, three_meals=THREE_MEALS)
开发者ID:tinawen,项目名称:menu,代码行数:12,代码来源:views.py

示例12: changeUserPassword

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def changeUserPassword(user,password):
    mySession = DBSession()
    try:
        transaction.begin()
        mySession.query(User).filter_by(user_name = user).update({"user_password": encodeData(password)})
        transaction.commit()
        mySession.close()
        return True
    except:
        transaction.abort()
        mySession.close()
        return False
开发者ID:BioversityCostaRica,项目名称:CLIMMOBNET_V3,代码行数:14,代码来源:dbuserfunctions.py

示例13: put

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
 def put(self, catid):
     session = DBSession()
     category = session.query(models.Category).filter_by(id=catid).first()
     args = parser.parse_args()
     if args['name'] and len(args['name']):
         category.name = args['name']
     if args['order'] and len(args['order']):
         neworder = args['order']
         other = session.query(models.Category).filter_by(order=neworder).first()
         if other:
             other.order = category.order
             category.order = neworder
     session.commit()
开发者ID:varesa,项目名称:hakulistaserver,代码行数:15,代码来源:resources.py

示例14: get_menu_json

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def get_menu_json(menu):
    json_result = []
    if len(menu.menus) < 1:
        return ''
    for menu_item_id in menu.menus.split(' '):
        menu_item = DBSession.query(MenuItem).filter(MenuItem.id==menu_item_id).one()
        allergens = DBSession.query(Allergen).filter(Allergen.menu_item_id==menu_item.id).all()
        allergen_string = ', '.join([a.allergen for a in allergens])
        menu_item_name = menu_item.name.decode('utf8')
        if len(menu_item.description.decode('utf8')):
            menu_item_desc = menu_item.description.decode('utf8')
        json_result.append((menu_item_name, menu_item_desc))
        return json.dumps(json_result)
开发者ID:tinawen,项目名称:menu,代码行数:15,代码来源:gcalendar.py

示例15: delete_picture

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import query [as 别名]
def delete_picture(request):
    menu_query = DBSession.query(Menu).filter(Menu.id==request.matchdict['menu_id'])
    images_id = menu_query.one().images_id
    images_id = images_id.split(' ') if images_id else []

    if "data" in request.params:
        thumb_url = json.loads(request.params["data"])
        image = DBSession.query(Image).filter(Image.thumb_url==thumb_url).filter(Image.id.in_(images_id)).one()
        images_id.remove(str(image.id))
        images_id = ' '.join([str(i) for i in images_id])
        menu_query.update({"images_id": images_id}, synchronize_session=False)
        DBSession.delete(image)
        return thumb_url
开发者ID:tinawen,项目名称:menu,代码行数:15,代码来源:views.py


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