此程序的目的只是返回从名为"defaults.cfg"的.cfg配置文件传递的值。
我完全理解这里应该传递的内容,老实说,所有意图和目的的代码都是从练习中复制的,但它失败了,出现了"Keying error:(value("(所有值都给出了键控错误,它只是第一个(,我不知道为什么。我一直无法在网上找到解决方案,代码原则上与朋友的更复杂的程序相同,运行一个合适的网络应用程序,他的工作也很好。
显然,使用大写字母作为配置键是一件事,我已经做到了,我确信我已经安装了所有必要的库/二进制文件。
我在Ubuntu上的Windows上的Bash上做这件事。
提前感谢您的考虑。
default.cfg
[config]
DEBUG = True
IP_ADDRESS = 0.0.0.0
PORT = 5000
配置.py
import ConfigParser
from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
return "Sup! Hollerin' at ya from the configuration testing app"
@app.route('/WTF/')
def tellMeh():
return app.config['PORT']
@app.route('/config/')
def config():
str = []
str.append(app.config['DEBUG'])
str.append('port:'+app.config['PORT'])
str.append('ip_address:'+app.config['IP'])
return 't'.join(str)
def init(app):
config = ConfigParser.ConfigParser()
try:
config_location = "etc/defaults.cfg"
config.read(config_location)
app.config['DEBUG'] = config.get("config", "DEBUG")
app.config['IP'] = config.get("config", "IP_ADDRESS")
app.config['PORT'] = config.get("config", "PORT")
print "Succesfully read configs from: ", config_location
except:
print "Couldn't read configs from: ", config_location
if __name__ == '__main__':
init(app)
app.run(
host=app.config['IP'],
port=int(app.config['PORT']))
根据调用方式,您将从该代码中获得不同的行为。
FLASK_APP=configuration.py flask run
将跳过底部init(app)
被称为的部分
python configuration.py
将运行该部分,调用init(app)
。
您可能希望将呼叫移动到init()
,app = Flask(...)
正下方。