目前,我的瓶的应用程序(使用会话)完成了如下处理一个域名:如何配置单个瓶子应用程序来处理多个域?
app.config.from_object(设置)
,并在设置对象:
SESSION_COOKIE_DOMAIN =”。 first.com“
我现在想要做的是动态设置会话cookie域来处理,例如,来自www.first.com和www.second.com的请求。请注意,我正在讨论域名,但不是子域名。谢谢。
目前,我的瓶的应用程序(使用会话)完成了如下处理一个域名:如何配置单个瓶子应用程序来处理多个域?
app.config.from_object(设置)
,并在设置对象:
SESSION_COOKIE_DOMAIN =”。 first.com“
我现在想要做的是动态设置会话cookie域来处理,例如,来自www.first.com和www.second.com的请求。请注意,我正在讨论域名,但不是子域名。谢谢。
Grepping SESSION_COOKIE_DOMAIN
通过瓶的GitHub库可以看出,它是用来像this:
def get_cookie_domain(self, app):
"""Helpful helper method that returns the cookie domain that should
be used for the session cookie if session cookies are used.
"""
if app.config['SESSION_COOKIE_DOMAIN'] is not None:
return app.config['SESSION_COOKIE_DOMAIN']
if app.config['SERVER_NAME'] is not None:
# chop of the port which is usually not supported by browsers
rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]
# Google chrome does not like cookies set to .localhost, so
# we just go with no domain then. Flask documents anyways that
# cross domain cookies need a fully qualified domain name
if rv == '.localhost':
rv = None
# If we infer the cookie domain from the server name we need
# to check if we are in a subpath. In that case we can't
# set a cross domain cookie.
if rv is not None:
path = self.get_cookie_path(app)
if path != '/':
rv = rv.lstrip('.')
return rv
做同样的事情与你get_cookie_domain(
会see:
def save_session(self, app, session, response):
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
...
确定。现在我们只需要找出使用哪个域名。通过docs或code挖掘,您会看到在请求上下文中调用save_session()
。所以,你只需要从flask
模块导入request
对象:
from flask import request
,并用它里面save_session()
确定域名饼干(例如,从Host
头)是这样的:
def save_session(self, app, session, response):
domain = '.' + request.headers['Host']
path = self.get_cookie_path(app)
# the rest of the method is intact
的只有当你需要指定cookie域的时候,你将它们发送回响应对象。
另外请注意,Host
标题可能不存在。
要连接你需要指定的SecureCookieSessionInterface
版本(子类)整个事情:
app = Flask(__name__)
app.session_interface = MySessionInterface()
更多文档链接:
嗨Tw,我明白你说的最后一点,除了最后一页艺术。我可以通过下面的方式获取域名: domain = request.headers ['Host'] 但是,我不明白你的意思,并在save_session()中使用它来确定cookie的域名“ 。我的问题是:一旦我得到域名,我在哪里/如何设置它?谢谢。 – 2014-11-05 18:21:13
请参阅更新的答案。希望你明白了。 – twil 2014-11-06 00:37:55
嗨,我是瓶/ python新手,但我明白了。我稍后会尝试将其连接起来,谢谢。 – 2014-11-06 11:51:49