[英]Running a simple python flask application using .cfg config files. I can't seem to return the config values, getting a keying error with them
該程序的目的只是返回從名為'defaults.cfg'的.cfg配置文件傳遞的值。
我完全理解應該在此處傳遞的內容,老實說,從練習中復制了所有意圖和目的的代碼,但是失敗並出現“鍵控錯誤:(值)”(所有值都給出了鍵控錯誤,無論如何首先),我也不知道為什么。 我一直無法在線找到解決方案,並且該代碼在原理上與朋友的更復雜的程序運行相同的Web應用程序相同,並且他的工作還不錯。
顯然使用大寫字母作為配置鍵是一件事情,我已經做到了,並且我確定我已經安裝了所有必需的庫/二進制文件。
我正在Windows的Ubuntu上的Bash上執行此操作。
預先感謝您的考慮。
default.cfg中
[config]
DEBUG = True
IP_ADDRESS = 0.0.0.0
PORT = 5000
configuration.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(...)
下方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.