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

Python response.set_cookie函数代码示例

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

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



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

示例1: try_pagecache

    def try_pagecache(self):
        # check content cache
        if request.method.upper() == "GET" and not c.user_is_loggedin:
            r = g.pagecache.get(self.request_key())
            if r:
                r, c.cookies = r
                response = c.response
                response.headers = r.headers
                response.content = r.content

                for x in r.cookies.keys():
                    if x in cache_affecting_cookies:
                        cookie = r.cookies[x]
                        response.set_cookie(
                            key=x,
                            value=cookie.value,
                            domain=cookie.get("domain", None),
                            expires=cookie.get("expires", None),
                            path=cookie.get("path", None),
                            secure=cookie.get("secure", False),
                            httponly=cookie.get("httponly", False),
                        )

                response.status_code = r.status_code
                request.environ["pylons.routes_dict"]["action"] = "cached_response"
                c.request_timer.name = request_timer_name("cached_response")

                # make sure to carry over the content type
                c.response_content_type = r.headers["content-type"]
                c.used_cache = True
                # response wrappers have already been applied before cache write
                c.response_wrappers = []
开发者ID:qdkll,项目名称:reddit,代码行数:32,代码来源:reddit_base.py


示例2: try_pagecache

    def try_pagecache(self):
        #check content cache
        if request.method.upper() == 'GET' and not c.user_is_loggedin:
            r = g.pagecache.get(self.request_key())
            if r:
                r, c.cookies = r
                response.headers = r.headers
                response.content = r.content

                for x in r.cookies.keys():
                    if x in cache_affecting_cookies:
                        cookie = r.cookies[x]
                        response.set_cookie(key=x,
                                            value=cookie.value,
                                            domain=cookie.get('domain', None),
                                            expires=cookie.get('expires', None),
                                            path=cookie.get('path', None),
                                            secure=cookie.get('secure', False),
                                            httponly=cookie.get('httponly', False))

                response.status_code = r.status_code
                request.environ['pylons.routes_dict']['action'] = 'cached_response'
                c.request_timer.name = request_timer_name("cached_response")

                # make sure to carry over the content type
                response.content_type = r.headers['content-type']
                c.used_cache = True
                # response wrappers have already been applied before cache write
                c.response_wrapper = None
开发者ID:briankiewel,项目名称:reddit,代码行数:29,代码来源:reddit_base.py


示例3: login

    def login(self):

        if request.cookies.get('userid'):
            return render('login.mako')        
        else:
            db = dbConnect()
            dbCursor = db.cursor()
            if 'username' in request.params:
                username = request.params['username']
                password = request.params['password']
            else:
                username = ''
                password = ''
            
            dbCursor.execute("""SELECT count(*) as numRows FROM users where username=%s AND password=%s""", (username, password))
            data = dbCursor.fetchone()

            if data[0] != 0:
                response.set_cookie('userid', username, max_age=180*24*3600 )
                return render('login.mako')
            else:
                c.loginError = 1
                c.deleteAll = 0
                c.toDelete = 0
                c.newUserSet = 0
                c.userAdded = 0
                c.userDeleted = 0
                c.addError = ''
                c.user = getUsers(db)
                return render('users.mako')
开发者ID:ddekroon,项目名称:school,代码行数:30,代码来源:mainController.py


示例4: localize

def localize(f, *args, **kwargs):
    if 'lang' in session:
        lang = session['lang']
        set_lang(lang)
    else:
        suport_lang = ['ru','en','uk']
        suport_domain = ['cleverad.yt:5000','10.0.0.8:5000']
        default_lang = 'ru'
        lang_cookie = request.cookies.get('lang', None)
        if not lang_cookie in suport_lang:
            lang_cookie = None
        domain = request.environ.get('HTTP_HOST', None)
        if not domain in suport_domain:
            domain = None
        if lang_cookie != None:
            lang = lang_cookie
        else:
            if domain == 'cleverad.yt:5000':
                lang = 'en'
            elif domain == '10.0.0.8:5000':
                lang = 'uk'
            elif domain == '10.0.0.8':
                lang = 'ru'
            else:
                lang = default_lang
        session['lang'] = lang
        session.save()
        set_lang(lang)
    response.set_cookie('lang', lang, max_age=360*24*3600 )
    return f(*args, **kwargs)
开发者ID:testTemtProj,项目名称:OLD_PROJECT,代码行数:30,代码来源:helpers.py


示例5: me

	def me(self):
		if (request.method == "GET"):
			cookie = request.cookies.get("GFB_Cookie")	
			if(cookie == None):
				return ''
			else:
				decode = Cookie.decryptCookie(cookie)
				return json.dumps(decode)
		else: #open host site
			cookie = request.cookies.get("GFB_Cookie")	
			if(cookie == None):
				return ''
			else:
				encode = {}
				decode = Cookie.decryptCookie(cookie)
				encode['role'] = decode['role']
				encode['user_name'] = decode['user_name']
				encode['email'] = decode['email']
				
				if (request.params['changed'] == 'true'):
					encode['host_site'] = request.params['siteID']
				else:
					encode['host_site'] = ''
					
				cookie = Cookie(encode['user_name'],encode['email'], encode['role'], encode['host_site'])
				response.delete_cookie('GFB_Cookie')
				response.set_cookie("GFB_Cookie", cookie.encryptCookie(), max_age=180*24*3600)
									
				return render('/tools/distOrders.mako')
开发者ID:maxgardiner,项目名称:Garden-Fresh-Box,代码行数:29,代码来源:users.py


示例6: add_transient_message

def add_transient_message(cookie_name, message_title, message_text):
    """Add a message dict to the serialized list of message dicts stored in
    the named cookie.

    If there is no existing cookie, create one.
    If there is an existing cookie, assumes that it will de-serialize into
    a list object.
    """

    time = datetime.now().strftime('%H:%M, %B %d, %Y')
    msg = dict(
        time = time,
        title = message_title,
        text = message_text,
    )
    old_data = request.cookies.get(cookie_name, None)

    if old_data is not None:
        response.delete_cookie(cookie_name)

    if old_data:
        msgs = simplejson.loads(unquote(old_data))
    else:
        msgs = []
    msgs.append(msg)
    new_data = quote(simplejson.dumps(msgs))
    response.set_cookie(cookie_name, new_data, path='/')
开发者ID:86me,项目名称:mediacore,代码行数:27,代码来源:helpers.py


示例7: _upload

	def _upload(self):
		if request.POST['type']:
			response.set_cookie('source_type', request.POST['type'])

		try:
			file = request.POST['source']

			if request.POST['type'] != '*':
				file.filename += "."+request.POST['type']

			size = len(file.value)
			fileName = file.filename.replace(" ", "_").encode('ascii', 'ignore')
			fileValue = file.value
		except:
			if request.POST['code'] != '' and request.POST['type'] != '*':
				fileName = b16encode(request.POST['code'])[:16]+"."+request.POST['type']
				fileValue = request.POST['code'] 
				size = len(fileValue)
			else:
				return False


		if size>1024*10: # 10 kB 
			return False

		if not self.source:
			self.source = Source(self.task.contest_id, self.task.id, self.user.id, fileName)
			Session.add(self.source)

		self.source.file = fileName
		self.source.source = fileValue
		self.source.commit()
		return True
开发者ID:Administrator37157192201,项目名称:DevContest,代码行数:33,代码来源:task.py


示例8: tw_callback

    def tw_callback(self):
        log.info('request %s' % request)
        verifier = request.GET.get('oauth_verifier')
        log.info('verifier [%s] session[%s]' % (verifier, session))
        auth = tweepy.OAuthHandler(TW_KEY, TW_SECRET)
        if 'request_token' in session:
            token = session['request_token']
            session['request_token'] = None
        else:
            log.error('oops request token not foudn in the session')
        #session.delete('request_token')
        auth.set_request_token(token[0], token[1])
        try:
            auth.get_access_token(verifier)
	except Exception: 
            log.exception('Veifier error')
            raise

        log.info('Ok. got the request token key[%s] and secret[%s]' % (auth.access_token.key, auth.access_token.secret))

        #check if user exists with given screen name

	#new_auth.set_access_token(auth.access_token.key, auth.access_token.secret)
	auth.set_access_token(auth.access_token.key, auth.access_token.secret)
        api = tweepy.API(auth)
        #api.update_status('testing' + 'tweepy' + 'oauth')
        tw_user = api.me()
        log.info('User info[%s] tw_id[%s]' % (tw_user.screen_name, tw_user.id))

        user = user_service.get_or_create_user(screen_name = tw_user.screen_name, \
						tw_id = str(tw_user.id), key = auth.access_token.key,\
						secret = auth.access_token.secret)
        #workflow to see if user exists or it is a first time user
        response.set_cookie(USER_INFO_COOKIE, tw_user.screen_name, max_age = 60*60*24)
	return 'Hi %s, your details token:[%s] and secret[%s]' % (tw_user.screen_name, auth.access_token.key, auth.access_token.secret)
开发者ID:droot,项目名称:tweetboard,代码行数:35,代码来源:main.py


示例9: post_login

    def post_login(self):
        """ Handle logic post a user's login

        I want to create a login_handler that's redirected to after login. This
        would check

        - if user was logged in, if not then send back to login
        - if user is admin, go to job list
        - if user can add joblist then go to *
        - if user is read only go to job list that's trimmed down a bit

        On the post login page adjust the max age on the existing cookie to XX
        remember me timeframe
        """
        if auth.check(not_anonymous()):
            log.debug('checked auth')
        else:
            # login failed, redirect back to login
            log.debug('failed auth')
            redirect(url(controller="accounts",
                action="login",
                login_failed=True)
            )

        # expire this cookie into the future
        ck = request.cookies['authtkt']
        response.set_cookie('authtkt', ck,
                max_age=60 * 60 * 24 * 7,
                path='/'
        )

        redirect(url('/page/test'))
开发者ID:adamlincoln,项目名称:Bookie,代码行数:32,代码来源:accounts.py


示例10: harviewer

    def harviewer(self):
        """HAR Viewer iframe"""

        # HAR Viewer customization via cookie
        response.set_cookie("phaseInterval", "-1", max_age=365*24*3600 )

        return render("/harviewer.html")
开发者ID:tepietrondi,项目名称:harstorage,代码行数:7,代码来源:results.py


示例11: touch_beta_cookie

def touch_beta_cookie():
    cookie_name = 'beta_' + c.beta
    response.set_cookie(
        key=cookie_name,
        value='1',
        domain=g.domain,
        expires=datetime.now() + timedelta(days=7),
    )
开发者ID:prodigeni,项目名称:reddit-plugin-betamode,代码行数:8,代码来源:betamode.py


示例12: forget

 def forget(controller_result, raised=None):
     """
     Check if the form's inputs can be forgotten, and set the cookie to forget if so.
     :param res: the result of the controller action
     :param raised: any error (redirect or exception) raised by the controller action
     """
     if _ok_to_forget(response, controller_result, raised):
         response.set_cookie('memorable_forget', request.path)
开发者ID:brondsem,项目名称:allura,代码行数:8,代码来源:decorators.py


示例13: sign_in_user

def sign_in_user(user, long_session=False):
    set_geolocation(user)

    session['login'] = user.id
    session['cookie_secret'] = ''.join(Random().sample(string.ascii_lowercase, 20))
    expiration_time = 3600*24*30 if long_session else None
    response.set_cookie('ututi_session_lifetime', session['cookie_secret'], max_age = expiration_time)
    session.save()
开发者ID:nous-consulting,项目名称:ututi,代码行数:8,代码来源:security.py


示例14: set_cookie_user

def set_cookie_user(user_id):
    thyme = time.time()
    secret_str = '%s:%d:%d' % (get_cookie_secret(user_id, thyme), thyme, user_id)
    user = model.User.get(user_id)
    user.token = secret_str
    model.Session.add(user)
    model.Session.commit()
    # expires in 15 days
    response.set_cookie('user_id', secret_str, max_age=1296000)
开发者ID:jsousa1919,项目名称:paypertrade,代码行数:9,代码来源:__init__.py


示例15: delete_beta_cookie

def delete_beta_cookie():
    cookie_name = 'beta_' + c.beta
    beta_cookie = request.cookies.get(cookie_name)
    if beta_cookie:
        response.set_cookie(
            key=cookie_name,
            value='',
            domain=g.domain,
            expires=DELETE_COOKIE,
        )
开发者ID:prodigeni,项目名称:reddit-plugin-betamode,代码行数:10,代码来源:betamode.py


示例16: signin

 def signin(self):
     if request.method == "GET":
         return render("sign_in.mako")
     email = self.form_result.get("email")
     password = self.form_result.get("password")
     pers = self.person_q.filter_by(email=email, password=md5(password)).first()
     if pers:
         response.set_cookie("email", email)
         response.set_cookie("password", md5(password))
         redirect("/chanel/main")
     return "Invalid user name and/or password %s" % dir
开发者ID:redvel2,项目名称:simple_pylon_chat,代码行数:11,代码来源:auth.py


示例17: login

    def login(self):
			global db
			global user
			if 'username' in request.params and 'password' in request.params:
				uname = request.params['username']
				passwd = request.params['password']

				if (user.login(uname, passwd, db)):
						response.set_cookie( "authenticated" , uname, max_age=180*24*3600 )
						return "Valid"
				else:
						return "Invalid"
开发者ID:drobin03,项目名称:Pylons-Web-Server,代码行数:12,代码来源:mainController.py


示例18: auth

 def auth(self):
     try:
         cursor.execute("select password from tbaronUsers where username = %s;", (request.params["username"]))
         conn.commit()
         result = cursor.fetchone()
         if result[0] == request.params["password"]:
             response.set_cookie("username", request.params["username"], max_age=180 * 24 * 3600)
             return {"success": True}
         else:
             return {"error": True}
     except:
         return {"error": True}
开发者ID:TrevorDev,项目名称:schoolWorkFall2013,代码行数:12,代码来源:users.py


示例19: login_user

    def login_user(self, username_lower):
        with self.lock:
            if username_lower in self.users:
                user = self.users[username_lower]
            else:
                try:
                    user = self._add_user(username_lower)
                    self._write_users()
                except ValueError as e:
                    raise BadRequest(str(e))

        # 315569260 seconds = 10 years
        response.set_cookie('local', username_lower, httponly=False, max_age=315569260)
        return user
开发者ID:ajbetteridge,项目名称:turbulenz_local,代码行数:14,代码来源:userlist.py


示例20: auth

	def auth(self):
		db = DB()
		if (request.method == "GET"):
			# Check if user's email and password are matched
			success = db.authUser(request.params['email'], request.params['password'])

			if(success):
				# Setup the cookie (encrypted) with useful information
				user = db.getUser(request.params['email'])
				cookie = Cookie(user.get('first_name'), user.get('email'), user.get('fk_credentials'), user.get('fk_hostsite_id'))
				response.set_cookie("GFB_Cookie", cookie.encryptCookie(), max_age=180*24*3600)
				return self.trueString
			else:
				return "{\"success\" : \"false\", \"message\" : \"Unable to login: bad username or password\"}"
		else:
			return "{\"success\" : \"false\", \"message\" : \"Bad request.\"}"
开发者ID:maxgardiner,项目名称:Garden-Fresh-Box,代码行数:16,代码来源:users.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python session.delete函数代码示例发布时间:2022-05-25
下一篇:
Python translation._get_translator函数代码示例发布时间: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