如何配置单个烧瓶应用程序来处理多个域?

时间:2014-11-04 15:16:03

标签: python flask

目前,我的烧瓶应用程序(使用会话)执行以下操作来处理一个域:

app.config.from_object(设置)

并在设置对象中:

SESSION_COOKIE_DOMAIN =" .first.com"

我现在要做的是动态设置会话cookie域,以处理来自www.first.com和www.second.com的请求。请注意,我说的是域名,但不是子域名。谢谢。

1 个答案:

答案 0 :(得分:6)

通过Flask的Github回购提示SESSION_COOKIE_DOMAIN可以看到它像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)

    ...

行。现在我们只需要找出要使用的域名。通过挖掘docscode,您会看到在请求上下文中调用save_session()。因此,您只需要从request模块中导入flask对象:

from flask import request

并在save_session()内使用它来确定Cookie的域名(例如来自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()

更多文档链接: