Python 使用flask.request.create\u app()内部是否安全

Python 使用flask.request.create\u app()内部是否安全,python,flask,request,Python,Flask,Request,我们希望根据Flask应用程序是在HTTP上运行还是在HTTPS上运行,对其进行不同的配置 以下代码将引发运行时错误 如何动态配置Flask 每次部署时手动更改不同的设置有点麻烦。自动解决方案优先。奇怪的是,烧瓶在运行之前并没有知道它运行在哪台机器上的机制。也许你的要求是错误的 我阅读和阅读 错误详细信息 运行时错误:在请求上下文之外工作 这通常意味着您试图使用 需要一个活动的HTTP请求。查阅有关测试的文档 有关如何避免此问题的信息 另一次尝试基于。收到相同的运行时错误 # Configura

我们希望根据Flask应用程序是在HTTP上运行还是在HTTPS上运行,对其进行不同的配置

以下代码将引发运行时错误

如何动态配置Flask

每次部署时手动更改不同的设置有点麻烦。自动解决方案优先。奇怪的是,烧瓶在运行之前并没有知道它运行在哪台机器上的机制。也许你的要求是错误的

我阅读和阅读

错误详细信息

运行时错误:在请求上下文之外工作

这通常意味着您试图使用 需要一个活动的HTTP请求。查阅有关测试的文档 有关如何避免此问题的信息

另一次尝试基于。收到相同的运行时错误

# Configuration Options
class Config(object):
    DEBUG = False
    TESTING = False
    FLASKS3_BUCKET_NAME = 'nueverest'
    FLASKS3_USE_HTTPS = True
    USE_S3_DEBUG = False


class Production(Config):
    pass


class Development(Config):
    DEBUG = True
    USE_S3_DEBUG = True


app = Flask(__name__)         # Initialize Application

if request.is_secure:               # Select Configuration
    app.config.from_object(Production)
else:
    app.config.from_object(Development)

正如Daniel Roseman解释的那样,不能使用flask.request,因为请求必须首先发生在鸡和蛋之间

解决方案:使用uuid.getnode来唯一地标识 代码正在上运行

为了使其可扩展,每个开发人员必须创建自己的secrets.py文件。该文件不应添加到VCS中,因为它对每个开发人员都是唯一的。看起来像这样

import uuid


def is_production():
    """ Determines if app is running on the production server via uuid comparison.

    HOW TO USE:
    Open a terminal
    > python
    > import uuid
    > uuid.getnode()
    12345678987654321  <-- Copy whatever is returned and replace 111111111 with this.

    Compare uuid for the machine against the known uuid(s) of your development machine(s).
    :return: (bool) True if code is running on the production server, and False otherwise.
    """
    developer_machines = [111111111, ]
    return uuid.getnode() not in developer_machines
可伸缩性:每个开发人员管理自己的secrets.py文件。这是 可扩展到任意数量的开发人员,并且不需要使用 环境变量会使测试、开发和测试复杂化 部署


在有任何请求之前,您如何期望访问请求对象?这很有意义。我不完全理解请求对象是如何工作的。@PJSantoro问题中已经提供了该链接。否决投票人解释你为什么否决投票。
import uuid


def is_production():
    """ Determines if app is running on the production server via uuid comparison.

    HOW TO USE:
    Open a terminal
    > python
    > import uuid
    > uuid.getnode()
    12345678987654321  <-- Copy whatever is returned and replace 111111111 with this.

    Compare uuid for the machine against the known uuid(s) of your development machine(s).
    :return: (bool) True if code is running on the production server, and False otherwise.
    """
    developer_machines = [111111111, ]
    return uuid.getnode() not in developer_machines
from flask import Flask
from secrets import is_production


def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = not is_production()
    return app


# Initialize App
app = create_app()