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

Python session.has_key函数代码示例

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

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



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

示例1: makecomplaint

 def makecomplaint (self):
     order = meta.Session.query(model.Order).filter_by(id=self.form_result['id']).first()
     if order is None:
         abort(404)
     if order.deleted:
         abort(410)
     # Теперь - проверка прав доступа (ответственный подразделения, подавшего эту заявку)
     if not (session.has_key('division') and session['division']):
         abort(401)
     if not (h.have_role('creator') and order.cust_id == session['division']):
         abort(403)
     complaint = model.Action()
     complaint.order_id = order.id
     complaint.status = meta.Session.query(model.Status).get(6)
     complaint.div_id = session['division']
     perf = meta.Session.query(model.Person).get(session['id'])
     complaint.performers.append(perf)
     # Если претензию подаёт оператор, то и его добавим
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         complaint.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     complaint.description = self.form_result['description']
     meta.Session.add (complaint)
     order.status = meta.Session.query(model.Status).get(6)
     # Обновляем создателей заявки
     if perf not in order.customers:
         order.customers.append(perf)
     meta.Session.commit()
     h.flashmsg (u"Жалоба подана. Всех лишат зарплаты. Дело заявки № " + h.strong(order.id) + u" будет сделано.")
     redirect_to(h.url_for(controller='order', action='view', id=order.id)) 
开发者ID:AmurSU,项目名称:orderman,代码行数:29,代码来源:action.py


示例2: index

 def index(self):
     c.clients_quan = meta.Session.query(sidb.Client).count()
     c.sorts = [('name', sidb.Client.name), ('prdate', sidb.Tmppricesstorage.price_date), ('tmpitems', sidb.Tmppricesstorage.tmpitems_quan)]
     c.sort_col = request.GET.get("sort_field", 'name')
     sort_field = dict(c.sorts).get(c.sort_col)
     c.sort_rule = request.GET.get("sort_rule", 'asc')
     sort_field = (c.sort_rule == 'desc' and  sort_field.desc() or sort_field.asc())
     for key, value in request.POST.iteritems():
         if key in ['s_name', 's_country', 's_city']: session[key] = value  
     session.save()
     c.s_name = session.has_key('s_name') and session.get('s_name') or u''
     c.s_country = session.has_key('s_country') and session.get('s_country') or u''
     c.s_city = session.has_key('s_city') and session.get('s_city') or u''
     clients_list = meta.Session.query(sidb.Client, sidb.City, sidb.Country, sidb.Clientlogo, sidb.User, sidb.Tmppricesstorage.rid.label('storage_rid'),
                                         sidb.Tmppricesstorage.tmpitems_quan, sidb.Tmppricesstorage.price_date).\
                                        join((sidb.City, sidb.Client._cities_rid == sidb.City.rid)).\
                                        join((sidb.Region, sidb.City._regions_rid == sidb.Region.rid)).\
                                        join((sidb.Country, sidb.Region._countries_rid == sidb.Country.rid)).\
                                        outerjoin((sidb.User, sidb.User._clients_rid == sidb.Client.rid)).\
                                        outerjoin((sidb.Clientlogo, sidb.Clientlogo._clients_rid == sidb.Client.rid)).\
                                        outerjoin((sidb.Tmppricesstorage, sidb.Tmppricesstorage._clients_rid == sidb.Client.rid)).\
                                        group_by(sidb.Client.rid).order_by(sort_field)
                     
     if c.s_name: clients_list = clients_list.filter(sidb.Client.name.like('%'+c.s_name+'%'))
     if c.s_country: clients_list = clients_list.filter(sidb.Country.name.like('%'+c.s_country+'%'))
     if c.s_city: clients_list = clients_list.filter(sidb.City.name.like('%'+c.s_city+'%'))
     page = paginate.Page(clients_list, items_per_page=15, page=request.GET.get("page", 1), sort_col=c.sort_col, sort_rule=c.sort_rule)
     c.pager = page.pager()
     c.clients_list = page.items
     c.subtempl = 'clients_list'
     return render('be/layouts/clients.html')
开发者ID:whocarez,项目名称:saleinform,代码行数:31,代码来源:clients.py


示例3: authenticated_user

def authenticated_user(reload=False):
    """
    Returns reference to AuthenticatedUser which is stored in session.
    If it's not in session method will add it and save session, then return object.
    """

    AUTHENTICATED_USER = "AUTHENTICATED_USER"

    # Create authenticated user if it doesn't exist
    if request.environ.has_key('REMOTE_USER'):
        if reload or not session.has_key(AUTHENTICATED_USER) \
            or session[AUTHENTICATED_USER] == None \
            or session[AUTHENTICATED_USER].username != request.environ['REMOTE_USER']:
            model = request.environ['sqlalchemy.model']
            db = request.environ['sqlalchemy.session']

            try:
                authenticated_user = db.query(model.AuthenticatedUser).filter_by(username=request.environ['REMOTE_USER']).one()
            except:
                authenticated_user = model.AuthenticatedUser(
                    username = request.environ['REMOTE_USER'], email = request.environ['REMOTE_USER'])
                db.save(authenticated_user)
                db.commit()
                log.info(_("Created an %s" % (str(authenticated_user))))
            db.expunge(authenticated_user)
            session[AUTHENTICATED_USER] = authenticated_user
            session.save()
    
        return session[AUTHENTICATED_USER]

    if session.has_key(AUTHENTICATED_USER):
        session.pop(AUTHENTICATED_USER, None)
        session.save()

    return None
开发者ID:pawelniewie,项目名称:5groszy.pl,代码行数:35,代码来源:helpers.py


示例4: makethank

 def makethank (self):
     order = meta.Session.query(model.Order).filter_by(id=self.form_result['id']).first()
     if order is None:
         abort(404)
     if order.deleted:
         abort(410)
     # Теперь - проверка прав доступа (ответственный подразделения, подавшего эту заявку)
     if not (session.has_key('division') and session['division']):
         abort(401)
     if not (h.have_role('creator') and order.cust_id == session['division']):
         abort(403)
     thank = model.Action()
     thank.order_id = order.id
     thank.status = meta.Session.query(model.Status).get(14)
     thank.div_id = session['division']
     perf = meta.Session.query(model.Person).get(session['id'])
     thank.performers.append(perf)
     # Если претензию подаёт оператор, то и его добавим
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         thank.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     thank.description = self.form_result['description']
     meta.Session.add (thank)
     meta.Session.commit()
     h.flashmsg (u"Спасибо за " + h.literal("«") + u"спасибо" + h.literal("»") + "!")
     redirect_to(h.url_for(controller='order', action='view', id=order.id)) 
开发者ID:AmurSU,项目名称:orderman,代码行数:25,代码来源:action.py


示例5: save

 def save(self, id):
     order = h.checkorder(id)
     # Теперь - проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     if not (h.have_role('admin') or h.have_role('operator') or (session.has_key('division') and (h.have_role('creator') and order.cust_id==session['division']) or (h.have_role('responsible') and order.perf_id==session['division']))):
         abort(401)
     for key, value in self.form_result.items():
         if getattr(order, key) != value and key not in ['inventories', 'urgent']:
             setattr(order, key, value)
     # Не все могут помечать заявку важной
     if h.have_role('admin') or (session.has_key('division') and h.have_role('responsible') and order.perf_id==session['division']):
         setattr(order, 'urgent', bool(self.form_result.get('urgent')))
     # Проверяем права
     # Изменяем отношения заявка <-> инвентарники
     for item in order.inventories: # Удаляем уже неактуальные отношения (удалённые при редактировании инвентарники)
         if item.id not in self.form_result['inventories']:
             order.inventories.remove(item)
     for inv in self.form_result['inventories']: # Добавляем новые отношения
         item = meta.Session.query(model.Inventory).get(inv);
         if not item:
             # <TODO text="Убрать добавление инвентарников в базу после введения проверок!">
             item = model.Inventory()
             item.id = inv
             meta.Session.add(item)
             # </TODO>
         if item not in order.inventories:
             order.inventories.append(item)
     meta.Session.commit()
     h.flashmsg (u"Заявка была изменена")
     redirect_to(h.url_for(controller='order', action='view', id=order.id))
开发者ID:Envek,项目名称:orderman,代码行数:29,代码来源:order.py


示例6: index

    def index(self):
        qorder = meta.Session.query(model.Order).filter_by(deleted=False)
        # Filter old orders (more than 1 year old)
        max_age = request.params.get('max_age_in_days', '365')
        if len(max_age) and max_age != 'unlimited':
            qorder = qorder.filter("age(orders.created) < interval ':age days'").params(age=int(max_age))
        freeorders = qorder.filter_by(status_id=1)  # .limit(10) #
        if (session.get('preferences') or dict()).get('upcat') is not None:
            c.upcat = meta.Session.query(model.UpperCategory).filter_by(url_text=session['preferences']['upcat']).one()
            freeorders = freeorders.filter_by(upcat_id=c.upcat.id)
        c.numfree = freeorders.count()
        c.freeorders = freeorders.order_by(model.sql.desc(model.Order.created))[:10]
        if session.has_key('division') and h.have_role('performer'): #session.has_key('performer') and session['performer']:
            # Заявки, выполняемые моим подразделением
            c.mydivorders = qorder.filter("status_id<>:value and perf_id=:perf").params(value=4, perf=session['division']).order_by(model.sql.desc(model.Order.created))[:10]
            # Заявки, выполняемые мной
            myperf = qorder.filter(model.sql.not_(model.Order.status_id.in_([1, 3, 4, 5])))
            myperf = myperf.filter(model.Order.performers.any(id=session['id']))
            c.myperforming = myperf.order_by(model.Order.created)[:10]
            # Жалобы!
            c.complaints = qorder.filter("status_id=:value and perf_id=:perf").params(value=6, perf=session['division']).order_by(model.Order.created).all()
        if session.has_key('division') and session.has_key('creator') and session['creator']:
            c.myownorders = qorder.filter("cust_id=:div").params(div=session['division']).order_by(model.sql.desc(model.Order.created))[:10]
            orderstoapprove = qorder.filter("status_id=:value and cust_id=:perf").params(value=3, perf=session['division'])
            c.orderstoapprove = orderstoapprove.order_by(model.Order.created)[:10]
            c.numtoapprove = orderstoapprove.count()
        # Немножко статистики на главную
        c.ordercount = meta.Session.query(model.Order).filter_by(deleted=False).count()
        statuses = meta.Session.query(model.Status).filter(model.Status.redirects==model.Status.id)\
            .order_by(model.Status.id).all()
        c.ordercountbystatus = [(unicode(status.title), status.ordercount) for status in statuses]

        return render('/main.html')
开发者ID:AmurSU,项目名称:orderman,代码行数:33,代码来源:main.py


示例7: list

    def list(self,id=None,page=1): 
        if "repoze.who.identity" in request.environ:
            user = request.environ.get('repoze.who.identity')['user']
            wholesale_tag = Session.query(UserTag).filter_by(tag='wholesale').one()
            if wholesale_tag in user.tags:
                c.wholesale=True
        c.tags = Session.query(ProductTag).all()
        c.menu_items = h.top_menu(self.menu_items,_('Shop online'))

        if session.has_key('product_querystr'):
            if session.has_key('paliasedtags'):
                for item in session['paliasedtags']:
                    exec(item)
            products = eval(session['product_querystr']+".filter(Product.deleted==False)")
            c.paginator = paginate.Page(products,
                                        page=int(request.params.get('page', page)),
                                        items_per_page = 10)
            html = render('/derived/product/list.html')
            return htmlfill.render(html,defaults=session['product_search_values'])
        else:
            products = Session.query(Product).filter_by(deleted=False)
            c.paginator = paginate.Page(products,
                                        page=int(request.params.get('page', page)),
                                        items_per_page = 10)
            return render('/derived/product/list.html')
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:25,代码来源:product.py


示例8: revoke

 def revoke(self, id=None):
     """Отзыв заявки её создателем (например, решили проблему сами или «ложная тревога»)."""
     order = h.checkorder(id)
     # Заявка должна быть свободна!
     if order.status.id != 1:
         abort(403)
     # Проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     if not (
         h.have_role("admin")
         or (
             session.has_key("division")
             and session.has_key("creator")
             and session["creator"]
             and order.cust_id == session["division"]
         )
     ):
         abort(401)
     # Заявка готова, но никто её не сделал
     order.status = meta.Session.query(model.Status).get(15)
     order.performers = []
     order.performer = None
     # Добавление записи в журнал действий над заявкой
     act = model.Action()
     act.order_id = order.id
     act.status = meta.Session.query(model.Status).get(15)
     act.division = meta.Session.query(model.Division).get(session["division"])
     act.performers.append(meta.Session.query(model.Person).get(session["id"]))
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         act.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     meta.Session.add(act)
     # Готово
     meta.Session.commit()
     h.flashmsg(u"Заявка № " + h.strong(order.id) + u" отозвана.")
     redirect_to(h.url_for(controller="order", action="view", id=order.id))
开发者ID:AmurSU,项目名称:orderman,代码行数:34,代码来源:order.py


示例9: __before__

    def __before__(self, action, controller, *args, **kwargs):
        log.debug("Connection at %s.%s." % ( controller, action ) )

        # Global messages
        c.glob_messages = []

        # Detect global message passed in session (flash).
        if 'uimessage' in web_session:
            c.glob_messages.append(web_session['uimessage'])
            del web_session['uimessage']
            web_session.save()

        # Detect configuration changes.
        def config_has_changed():
            #model.new_engine() # not needed
            #model.init_local() # not needed
            kcd_model.new_engine()
            kcd_model.init_local()
            freemium_model.new_engine()
            freemium_model.init_local()
        detect_cached_config_change(config_has_changed)

        # Get cached master configuration.
        c.mc = get_cached_master_config()

        # Initialize models in local thread.
        #model.init_local() # not needed
        kcd_model.init_local()
        freemium_model.init_local()

        require_auth = None
        try:
            # Get the require_auth attribute.
            require_auth = getattr(self, 'require_auth')
        except AttributeError:
            # Class has no require_auth parameter.
            pass

        if require_auth and action in require_auth:
            # Object has a require_auth parameter.
            if not web_session.has_key('logged') or web_session['logged'] != True:
                # User is not logged.
                log.info("User not logged... redirecting to the login page.")
                return redirect(url_for('login'))

        c.logged = False
        if web_session.has_key('logged') and web_session['logged']:
            # Show logout button.
            c.logged = True

        # Get services objects.
        c.services = K2Services()

        # Load services status.
        for name, service in c.services.items():
            service.update_from_conf(c.mc)
开发者ID:fdgonthier,项目名称:kas,代码行数:56,代码来源:base.py


示例10: add

    def add(text, type="cool"):
        """ Add a message to the message queue.
        
        Concerning the message type, it can be anything but to have any
        relevance to the end user it should have the name of a class in the CSS
        file.
        
        By default the available message types are:
        - cool (green)
        - warning (yellow)
        - critical (red)
        
        Keyword arguments:
        text -- the text to show in the message
        type -- the type of message. default value is 'cool'
        
        """
        if len(type) == 0:
            type = "cool"

        if not session.has_key("swat_messages"):
            session["swat_messages"] = []

        session["swat_messages"].append({"text": text, "type": type})
        session.save()
开发者ID:jelmer,项目名称:swat2,代码行数:25,代码来源:helpers.py


示例11: session_test

 def session_test(self):
     key = "session_test"
     if not session.has_key(key):
         session[key] = 0
     else:
         session[key] = session[key]+1
     return str(session[key])
开发者ID:cemeyer2,项目名称:comoto,代码行数:7,代码来源:users.py


示例12: check_flash

def check_flash():
    # If the session data isn't of the particular format python has trouble.
    # So we check that it is a dict.
    if session.has_key("flash"):
        if type(session["flash"]) != dict:
            del session["flash"]
            session.save()
开发者ID:cafuego,项目名称:zookeepr,代码行数:7,代码来源:helpers.py


示例13: choose

 def choose (self, id=None):
     c.order = h.checkorder(id)
     # Теперь - проверка прав доступа (ответственный подразделения, выполняющего заявки)
     if not (h.have_role('admin') or ((h.have_role("appointer")) and session.has_key('division') and c.order.perf_id == session['division'])):
         abort(403)
     actionquery = meta.Session.query(model.Action)
     #if actionquery.filter_by(div_id=c.order.perf_id).all() is None:
     #    lastaction = None
     #else:
     #    lastaction = actionquery.filter_by(div_id=c.order.perf_id).order_by(model.sql.desc(model.Action.created)).first()
     lastaction = actionquery.filter_by(order_id=id).filter_by(div_id=c.order.perf_id).filter(model.Action.status_id != 16).order_by(model.sql.desc(model.Action.created)).first()
     c.actions = actionquery.filter_by(order_id=id).order_by(model.Action.created).all()
     # Статусы
     statuses = meta.Session.query(model.Status).order_by(model.Status.gui_priority)
     if h.have_role('admin'): excluded_statuses = [1, 4, 6, 11, 12, 14]
     else: excluded_statuses = [1, 2, 4, 6, 11, 12, 14]
     c.statuses = [["", u" -- выберите -- "]] + [[status.id, status.title] for status in statuses if status.id not in excluded_statuses]
     # Люди-исполнители
     performers = meta.Session.query(model.Person).filter_by(deleted=False).filter_by(performer=True).order_by(model.Person.surname, model.Person.name, model.Person.name)
     if h.have_role('admin') and lastaction is not None:
         performers = performers.filter_by(div_id=lastaction.div_id)
     else:
         performers = performers.filter_by(div_id=session['division'])
     c.performers = [[user.id, h.name(user)] for user in performers]
     if lastaction is not None:
         c.curperfs = [x.id for x in c.order.performers]
         c.curdiv = lastaction.div_id
     if h.have_role("admin"):
         divlist = [x.div_id for x in meta.Session.query(model.Person.div_id).filter_by(performer=True).all()]
         c.divisions = [[x.id, x.title] for x in meta.Session.query(model.Division).filter_by(deleted=False).filter(model.Division.id.in_(divlist)).all()]
     return render("/actions/choose.html")
开发者ID:AmurSU,项目名称:orderman,代码行数:31,代码来源:action.py


示例14: createbasket

    def createbasket(self):
        came_from = str(request.GET.get('came_from', ''))
        values = dict(request.params)
        for item in values:
            if item.startswith('product_id.'):
                id = int(item.split('.')[-1])
                try:
                    product = Session.query(Product).filter_by(id=id).one()
                except:
                    h.flash(_('No product exist with ID: %s')%id)
                    redirect(url(controller='product',action='list'))
        if values['quant']!='':
            quantity = int(values['quant'])
        else:
            quantity =1        

        if session.has_key('basket'):
            session['basket'][id]=quantity
        else:
            session['basket']={id:quantity}
        product = Session.query(Product).filter_by(id=id).one()
        h.flash(_('%s of product %s added to basket')%(quantity,product.name))
        if came_from !='':            
            return redirect(came_from)
        redirect(url(controller='product',action='list'))
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:25,代码来源:product.py


示例15: _gccom_jobs

    def _gccom_jobs(self, model_key, mode):
        c.jobstate          = 'build'
        c.jobmsg            = 'build: setting up the job. before submission.'
        c.model_key         = model_key
        c.mode              = mode
        c.error_flash       = None
        if session.has_key('error_flash'):
            c.error_flash = session['error_flash']
            try: del session['error_flash']
            except Exception as _: pass
        c.jobname           = '%s_%s' % (model_key, mode)
        c.cwuser            = session.get('user','user')
        c.acct              = Gccom.gccom_comm_acct
        c.model_param_hdrs  = Gccom.model_params['hdrs']
        c.model_params      = Gccom.model_params[c.model_key]
        c.model_desc        = str(Gccom.model_info[c.model_key]['desc'])
        c.title             = 'GCOM %s Simulation: Model:%s for JobName: %s' % (
                                   c.mode, str(c.model_desc), c.jobname)

        c.resources = h.get_user_resources(session.get('user_id'))
        c.hostname  = c.resources.keys()[0] if c.resources else ''     #used to init/set default host; reset later 

        c.grid_key          = Gccom.model_info[c.model_key]['grid_key']
        c.grid_imax         = Gccom.bath_grid[c.grid_key]['IMax']
        c.grid_jmax         = Gccom.bath_grid[c.grid_key]['JMax']
        c.grid_kmax         = Gccom.bath_grid[c.grid_key]['KMax']
        c.grid_name         = Gccom.bath_grid[c.grid_key]['name']
        c.grid_fname        = Gccom.bath_grid[c.grid_key]['fname']
        log.info( 'GCOM:: gccom_jobs:  building form data for model_key=%s, desc=%s, jobstate= %s, jobname= %s, gridname= %s, gridfnam=%s' % (c.model_key, c.model_desc,c.jobstate, c.jobname, c.grid_name, c.grid_fname))
        return render('/gcem/gccom/app_' + c.mode.lower() + '.mako')
开发者ID:sumukh210991,项目名称:Cyberweb,代码行数:30,代码来源:gccom.py


示例16: contact_insert

 def contact_insert(self):
     '''functional controller'''
     if session.has_key("edit"):
         session['update'] = {}
         for item in request.params.items():
             session['update'][item[0]] = item[1]
         session.save()
         return redirect_to(controller='uniaddbook', action='contact_update', method="post")
     else:
         meta.Session.begin()
         meta.Session.add(Contact(first_name = str(request.params['fname']),
                     middle_name = str(request.params['mname']),
                     last_name = str(request.params['lname']),
                     nick_name = str(request.params['nname']),
                     birthday = datetime(year=int(request.params['year']), month=int(request.params['month']), day=int(request.params['day'])),
                     street_address = str(request.params['street']),
                     country = str(request.params['country']),
                     city = str(request.params['city']),
                     zipcode = int(request.params['zipcode']),
                     state_id = int(request.params['State']),
                     relationship_id = int(request.params['relationship'])))
         meta.Session.commit()
         session["id"] = meta.Session.query(Contact).order_by("id DESC").all()[0].id
         session.save()
         return redirect_to(controller='uniaddbook', action='contact_show', method="post")
开发者ID:tdyhacker,项目名称:pythonexploration,代码行数:25,代码来源:uniaddbook.py


示例17: edit

 def edit(self, id):
     c.order = h.checkorder(id)
     # Теперь - проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     h.requirelogin()
     if not (
         h.have_role("admin")
         or h.have_role("operator")
         or (
             session.has_key("division")
             and (h.have_role("creator") and c.order.cust_id == session["division"])
             or (h.have_role("responsible") and c.order.perf_id == session["division"])
         )
     ):
         abort(403)
     work = meta.Session.query(model.Work).order_by(model.Work.id).all()
     c.work = []
     for i in work:
         c.work.append([i.id, i.title])
     category = (
         meta.Session.query(model.Category)
         .filter(model.Category.upcat_id == c.order.upper_category.id)
         .order_by(model.Category.id)
         .all()
     )
     c.category = []
     for i in category:
         c.category.append([i.id, i.title])
     upcategory = (
         meta.Session.query(model.UpperCategory).filter_by(deleted=False).order_by(model.UpperCategory.id).all()
     )
     c.upcategory = [[None, u" -- выберите надкатегорию -- "]]
     for i in upcategory:
         c.upcategory.append([i.id, i.title])
     return render("/orders/edit.html")
开发者ID:AmurSU,项目名称:orderman,代码行数:34,代码来源:order.py


示例18: news

    def news(self):
        # Gather the messages to be displayed
        num_messages = 50
        c.messages = []

        # select user messages AND generic messages
        if session.has_key('user_id') and session.has_key('user_groups'):
            messages = meta.Session.query(Message).filter(sa.or_(Message.recipient_group_id.in_(session['user_groups']), Message.recipient_user_id == session['user_id'], sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null()))).limit(num_messages)
        # select generic messages (user not logged in)
        else:
            messages = meta.Session.query(Message).filter(sa.and_(Message.recipient_group_id == sa.null(), Message.recipient_user_id == sa.null())).limit(num_messages)
        for i in messages:
            c.messages.append({'date':i.date.strftime("%b %d,%y %H:%M %p"), 'message':i.message})

        meta.Session.close()
        return render('/account/news.mako')    
开发者ID:sumukh210991,项目名称:Cyberweb,代码行数:16,代码来源:homepage.py


示例19: check_flash

def check_flash():
    """If the session data isn't of the particular format python has trouble.
    So we check that it is a dict."""
    if session.has_key('flash'):
        if type(session['flash']) != dict:
            del session['flash']
            session.save()
开发者ID:steven-ellis,项目名称:zookeepr,代码行数:7,代码来源:helpers.py


示例20: flash

def flash(msg, category="information"):
    check_flash()
    if not session.has_key('flash'):
        session['flash'] = {}
    if not session['flash'].has_key(category):
        session['flash'][category] = []
    session['flash'][category].append(msg)
    session.save()
开发者ID:steven-ellis,项目名称:zookeepr,代码行数:8,代码来源:helpers.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python session.pop函数代码示例发布时间:2022-05-25
下一篇:
Python session.get函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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