我希望我的Flask应用程序在localhost上运行时以及在线托管时具有不同的行为。如何在烧瓶应用程序中检测它何时在localhost上以及何时部署?
答案 0 :(得分:3)
这是一种做法。关键是将当前根网址flask.request.url_root
与您要匹配的已知网址值进行比较。
摘录自github repo https://github.com/nueverest/vue_flask
from flask import Flask, request
def is_production():
""" Determines if app is running on the production server or not.
Get Current URI.
Extract root location.
Compare root location against developer server value 127.0.0.1:5000.
:return: (bool) True if code is running on the production server, and False otherwise.
"""
root_url = request.url_root
developer_url = 'http://127.0.0.1:5000/'
return root_url != developer_url
答案 1 :(得分:2)
您需要查看the configuration handling section of the docs,最具体地说,the part on dev / production。总结一下,你想要做的是:
代码中的一个例子:
from __future__ import absolute_imports
from flask import Flask
import .config # This is our default configuration
app = Flask(__name__)
# First, set the default configuration
app.config.from_object(config)
# Then, load the environment-specific information
app.config.from_envvar("MYAPP_CONFIG_PATH")
# Setup routes and then ...
if __name__ == "__main__":
app.run()
另请参阅:Flask.config