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


Python HTTPFound.set_cookie方法代码示例

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


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

示例1: skip_persona_selection

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
 def skip_persona_selection(self):
     # set cookie and redirect
     response = HTTPFound(location=get_redirect_url(self.request))
     response.set_cookie(
         PERSONA_COOKIE_NAME, value=PERSONA_SKIP_COOKIE_VALUE,
         max_age=ONE_YEAR)
     return response
开发者ID:universalcore,项目名称:springboard-iogt,代码行数:9,代码来源:views.py

示例2: lang

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def lang(request):
    # Set language
    code = request.matchdict['code']
    # TODO redirect where we came_from
    response = HTTPFound(location='/')
    response.set_cookie('lang', value=code, max_age=31536000) # max_age = year
    return response
开发者ID:tojuhaka,项目名称:easyblog,代码行数:9,代码来源:views.py

示例3: account_verify_email

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def account_verify_email(request):
    login_store = request.find_service(name="redis_login")

    try:
        user_id = int(request.GET["user_id"].strip())
        email_address = request.GET["email_address"].strip()
        token = request.GET["token"].strip()
    except (KeyError, ValueError):
        raise HTTPNotFound
    stored_token = login_store.get("verify_email:%s:%s" % (user_id, email_address))
    if not user_id or not email_address or not token or not stored_token:
        raise HTTPNotFound

    stored_token = stored_token.decode("utf-8")

    if not stored_token == token:
        raise HTTPNotFound

    try:
        db = request.find_service(name="db")
        user = db.query(User).filter(User.id == user_id).one()
    except NoResultFound:
        raise HTTPNotFound

    user.email = email_address

    response = HTTPFound(request.route_path("account", _query={"saved": "email_address"}))

    if not request.user or request.user.id != user.id:
        new_session_id = str(uuid4())
        login_store.set("session:" + new_session_id, user.id)
        response.set_cookie("cherubplay", new_session_id, 31536000)

    return response
开发者ID:tehdragonfly,项目名称:cherubplay,代码行数:36,代码来源:account.py

示例4: fbauth

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def fbauth(request):
    code = request.params['code']
    fb_user = User.fb_user(code)
    user_id = str(fb_user.id)
    response = HTTPFound(location="/")
    response.set_cookie('user_id', value=user_id, max_age=31536000)
    return response
开发者ID:theseansy,项目名称:swoll,代码行数:9,代码来源:login.py

示例5: logout

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def logout(request):
    next = request.params.get('next') or request.route_url('index')
    if not authenticated_userid(request):
        return HTTPFound(location=request.route_url('login'))
    headers = forget(request)
    response = HTTPFound(location=next, headers=headers)
    response.set_cookie('csrf_token', value=None)
    return response
开发者ID:aape,项目名称:m4ed,代码行数:10,代码来源:auth.py

示例6: login

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def login(request):
    username = request.params.get('username', None)
    password = request.params.get('password', None)
    session = DBSession()
    user = session.query(User).filter(User.username==username).first()
    if user is not None and user.password == password:
        response = HTTPFound('/')
        # totally insecure, TODO in workshop: use auth token or something
        response.set_cookie('user_id', str(user.id), max_age=timedelta(30))
        return response
    return {'username': username}
开发者ID:antoineleclair,项目名称:OpenCode20111201,代码行数:13,代码来源:sessions.py

示例7: auth

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
    def auth(self):
        self.twitter = Twython(APP_KEY, APP_SECRET)
        auth = self.twitter.get_authentication_tokens(callback_url=CALLBACK_URL)
        OAUTH_TOKEN = auth['oauth_token']
        OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
        auth_url = auth['auth_url']

        # set cookies and redirect
        response = HTTPFound(location=auth_url)
        response.set_cookie('oauth_token', OAUTH_TOKEN, max_age=86400)
        response.set_cookie('oauth_token_secret', OAUTH_TOKEN_SECRET, max_age=86400)
        return response
开发者ID:utada,项目名称:twittpane-pyramid,代码行数:14,代码来源:views.py

示例8: change_profile

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def change_profile(request, profile):
    """
    Sets a cookie for the given profile and deletes any location set in the
    cookies.
    Returns a response which directs to the map view.
    """
    response = HTTPFound(location=request.route_url('map_view'))
    response.set_cookie('_PROFILE_', profile, timedelta(days=90))

    if '_LOCATION_' in request.cookies:
        response.delete_cookie('_LOCATION_')

    return response
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:15,代码来源:views.py

示例9: login

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def login(request):
    """
    Login view.
        request - Reads AJAX request to get user data and checks permissions on database.
    """
    try:

        login_url = route_url('login', request)

        referrer = request.url

        if referrer == login_url:
            referrer = '/'

        came_from = request.params.get('came_from', referrer)

        message = ''
        email = ''
        password = ''

        if 'form.submitted' in request.params:

            login = request.params['login']
            password = request.params['password']

            permissions = groupfinder(login, password, request)

            if permissions is None:
                message = 'BŁĘDNE HASŁO.'
            elif permissions is []:
                message = 'UŻYTKOWNIK %s NIE JEST ZAREJESTROWANY.' % email
            elif 'permission:' in permissions:
                headers = remember(request, permissions)

                response = HTTPFound(location=came_from, headers=headers)

                #Add user cookie
                response.set_cookie('user', value=login, max_age=31536000)

                return response

        return dict(
            message=message,
            url=request.application_url + '/login',
            came_from=came_from,
            login=email,
            password=password, )

    except DBAPIError, ex:
        print ex
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
开发者ID:trojanowski-radek,项目名称:bergamotka,代码行数:53,代码来源:views.py

示例10: sudo_employer

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
    def sudo_employer(self):
        employer_id = self.request.matchdict['id']
        employer = DBSession.query(Employer).get(employer_id)
        if not employer:
            raise HTTPNotFound('Unknown employer id')
        else:
            self.request.session['employer_id'] = employer.id

        location = self.request.params.get('furl')
        if not location:
            location = 'http://%s/employer' % self.request.frontend_domain
        response = HTTPFound(location=location)
        response.set_cookie('__admin__', value='true') # max_age = year
        return response
开发者ID:iwein,项目名称:temp,代码行数:16,代码来源:views.py

示例11: sudo_candidate

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
    def sudo_candidate(self):
        candidate_id = self.request.matchdict['id']
        candidate = DBSession.query(Candidate).get(candidate_id)
        if not candidate:
            raise HTTPNotFound('Unknown candidate id')
        else:
            self.request.session['candidate_id'] = candidate.id

        location = self.request.params.get('furl')
        if not location:
            location = 'http://%s/candidate' % self.request.frontend_domain
        response = HTTPFound(location=location)
        response.set_cookie('__admin__', value='true') # max_age = year
        return response
开发者ID:iwein,项目名称:temp,代码行数:16,代码来源:views.py

示例12: order

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def order(request): 
	server = Settings.Session.query(Server).filter(Server.id == request.matchdict['server']).scalar()
	item = Settings.Session.query(Item).filter(Item.id == request.matchdict['product']).scalar()
	path = [{"href": request.route_url('home'), "name": "Home", "active": False}, 
			{"href": '{href}?sid={sid}'.format(href=request.route_url('home'), sid=server.id), "name": server.name, "active": False},
			{"href": request.route_url('order', server=server.id, product=item.id), "name": item.name, "active": True}]
	errors = []
	if not server or not item or not item in [servitem.item for servitem in server.items]:
		return HTTPFound(location=request.route_url('home'))
	price = item.price
	for promotion in [promo.promotion for promo in item.promotions if promo.promotion.type == 1 and '%' not in promo.promotion.value and time.time() < promo.promotion.expires]:
		try:
			price = price - float(promotion.value)
		except:
			continue
	for promotion in [promo.promotion for promo in item.promotions if promo.promotion.type == 1 and '%' in promo.promotion.value and time.time() < promo.promotion.expires]:
		try:
			price = price - (price * (float(promotion.value.replace('%', '')) / 100))
		except:
			continue;
	if price < 0:
		price = 0
	if 'form.submitted' in request.params:
		try:
			steamid = SteamIDToCommunityID(request.params['input.steamid'])
		except SteamFormatException:
			errors.append('steamid')
		if not re.match(r'[^@][email protected][^@]+\.[^@]+', request.params['input.email']):
			errors.append('email')
		if request.params['input.code'].strip():
			print "Code: %s" % request.params['input.code']
			code = None
			for promotion in [promo.promotion for promo in item.promotions if promo.promotion.type == 2 and time.time() < promo.promotion.expires]:
				if promotion.code == request.params['input.code']:
					code = promotion
					break
			if not code:
				errors.append('promo')
		if not errors:
			order = {'steamid': request.params['input.steamid'], 'email': request.params['input.email'], 
					'promocode': request.params['input.code'], 'server': server.id, 'item': item.id}
			response = HTTPFound(location=request.route_url('confirm'))
			response.set_cookie('order', value=json.dumps(order), max_age=300)
			return response

	path = [{"href": request.route_url('home'), "name": "Home", "active": False}, 
			{"href": '{href}?sid={sid}'.format(href=request.route_url('home'), sid=server.id), "name": server.name, "active": False},
			{"href": request.route_url('order', server=server.id, product=item.id), "name": item.name, "active": True}]
	return {'community': Settings.Community, 'item': item, 'server': server, 'path': path, 'errors': errors, 'price': round(price,2), 'path': path}
开发者ID:EasyDonate,项目名称:EasyDonate,代码行数:51,代码来源:EDViews.py

示例13: select_persona

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
    def select_persona(self):
        slug = self.request.matchdict['slug'].upper()
        if slug not in PERSONAE:
            raise HTTPNotFound

        # set cookie and redirect
        response = HTTPFound(location=get_redirect_url(self.request))
        response.set_cookie(PERSONA_COOKIE_NAME, value=slug, max_age=ONE_YEAR)

        # set persona dimension value on GA
        # NOTE: the persona dimension has to be configured with scope 'user'
        persona_dimension_id = self.settings.get('ga.persona_dimension_id')
        if persona_dimension_id:
            self.request.google_analytics[persona_dimension_id] = slug

        return response
开发者ID:universalcore,项目名称:springboard-iogt,代码行数:18,代码来源:views.py

示例14: sign_up

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
def sign_up(request):
    # Disable signing up in read-only mode.
    if "cherubplay.read_only" in request.registry.settings:
        raise HTTPForbidden
    # Make sure this IP address hasn't created an account recently.
    # Also don't explode if Redis is down.
    ip_check_key = "ip:" + request.environ["REMOTE_ADDR"]
    try:
        ip_check = request.login_store.get(ip_check_key)
    except ConnectionError:
        return {
            "sign_up_error": "We can't create your account because we're having problems with the login server. Please try again later."
        }
    if ip_check is not None:
        return {
            "sign_up_error": "An account has already been created from your IP address. Please try again in a few hours."
        }
    # Validate password.
    if request.POST["password"] == "":
        return {"sign_up_error": "Please don't use a blank password."}
    if request.POST["password"] != request.POST["password_again"]:
        return {"sign_up_error": "The two passwords didn't match."}
    # Make sure username hasn't been taken.
    username = request.POST["username"].lower()[:100]
    if username_validator.match(username) is None:
        return {"sign_up_error": "Usernames can only contain letters, numbers, hyphens and underscores."}
    existing_username = Session.query(User.id).filter(User.username == username).count()
    if existing_username == 1 or username in reserved_usernames:
        return {"sign_up_error": 'The username "%s" has already been taken.' % username}
    # Create the user.
    new_user = User(
        username=username,
        password=hashpw(request.POST["password"].encode(), gensalt()),
        last_ip=request.environ["REMOTE_ADDR"],
    )
    Session.add(new_user)
    Session.flush()
    # Generate session ID and add it to the login store.
    new_session_id = str(uuid.uuid4())
    request.login_store.set("session:" + new_session_id, new_user.id)
    # Remember their IP address for 12 hours.
    ip_check = request.login_store.set(ip_check_key, "1")
    ip_check = request.login_store.expire(ip_check_key, 43200)
    # Set cookie for session ID.
    response = HTTPFound(request.route_path("home"))
    response.set_cookie("cherubplay", new_session_id, 31536000)
    return response
开发者ID:bengoeswild,项目名称:cherubplay,代码行数:49,代码来源:__init__.py

示例15: login

# 需要导入模块: from pyramid.httpexceptions import HTTPFound [as 别名]
# 或者: from pyramid.httpexceptions.HTTPFound import set_cookie [as 别名]
 def login(self, request):
     if request.method == 'POST':
         login = request.POST.get('login')
         password = request.POST.get('password')
         if login and password:
             user = dbs.query(StaffModel).filter_by(name=login).first()
             if user and user.password == sha256(
                     password + user.salt).hexdigest():
                 now = datetime.datetime.utcnow()
                 csrf = sha256(str(now)).hexdigest()
                 val = signed_serialize({'time': now, 'csrf': csrf}, SECRET)
                 response = HTTPFound(request.route_url('admin.index'))
                 response.set_cookie('signed', val)
                 return response
             return dict(
                 error='Something went wrong. Try "admin" and "111111"')
     return {}
开发者ID:tark-hidden,项目名称:pyramid_igniter,代码行数:19,代码来源:views.py


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