python - 如何配置单个 flask 应用程序来处理多个域?

标签 python flask

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

app.config.from_object(设置)

在设置对象中:

SESSION_COOKIE_DOMAIN = ".first.com"

我现在想做的是动态设置 session cookie 域来处理例如来自 www.first.com 和 www.second.com 的请求。请注意,我说的是域而不是子域。谢谢。

最佳答案

Grepping SESSION_COOKIE_DOMAIN 通过 Flask 的 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)

    ...

好的。现在我们只需要找出使用什么域名即可。深挖docscode您会看到在请求上下文中调用了 save_session()。所以你只需要从 flask 模块导入 request 对象:

from flask import request

并在 save_session() 中使用它来确定 cookie 的域名(例如,从 Host header ),如下所示:

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 header 可能不存在。

要连接整个东西,您需要指定 SecureCookieSessionInterface 的版本(子类):

app = Flask(__name__)
app.session_interface = MySessionInterface()

更多文档链接:

关于python - 如何配置单个 flask 应用程序来处理多个域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26738641/

相关文章:

python - 如果其他列值不满足条件,Pandas 会更改列的值

python - 名字和姓氏未以 django 形式显示

python - celery |发现 Flask 错误 : expected a bytes-like object, AsyncResult

python - 无法使用flask_sqlalchemy获得一对多关系,得到sqlalchemy.exc.InvalidRequestError

javascript - 在Python中将二进制字符串解释为图像,由Javascript native 方法生成

python beautifulsoup 提取文本

python - 如何使用 numba 更改数组中的索引

python - 无法在 python selenium 中使用 is_displayed 属性

python - 获取按钮名称作为输入

python - 在 Flask 应用程序的多个页面中从服务器获取数据