flask数据库全局变量
在我的flask应用程序中,我正在使用mongoDB,在主页上,我有一个表单返回该特定数据库中的所有已知集合。我要求用户选择他们想要使用的集合,因为我将使用该集合集返回其他路由或视图中的所有文档 我正在努力使这个全局“selected_collection”成为所有路由和视图都可以使用的全局变量 例如,在“索引”页面上,我可以选择一个集合,然后在“提交”页面上,它会将我重定向到视图db_selected那里,我试图使所选的_集合成为一个全局变量,但如果我转到“关于”视图,则会得到一个与之相关的错误 我想我应该用flask.g,但我不知道如何让它工作。我看过一些文件,但对我来说有点模糊flask数据库全局变量,flask,flask-wtforms,flask-login,Flask,Flask Wtforms,Flask Login,在我的flask应用程序中,我正在使用mongoDB,在主页上,我有一个表单返回该特定数据库中的所有已知集合。我要求用户选择他们想要使用的集合,因为我将使用该集合集返回其他路由或视图中的所有文档 我正在努力使这个全局“selected_collection”成为所有路由和视图都可以使用的全局变量 例如,在“索引”页面上,我可以选择一个集合,然后在“提交”页面上,它会将我重定向到视图db_selected那里,我试图使所选的_集合成为一个全局变量,但如果我转到“关于”视图,则会得到一个与之相关的错
AttributeError: '_AppCtxGlobals' object has no attribute 'selected_collection'
我怎样才能做到这一点
app.py文件:
# INDEX
@app.route('/', methods=['GET', 'POST'])
def index():
coll_name = get_db_collection()
return render_template('index.html', coll_name=coll_name)
# LOGIN
@app.route('/db_selected', methods=['GET', 'POST'])
def db_selected():
if request.method == 'POST':
selected_collection = request.form['Item_4']
selected_collection = g.selected_collection
return render_template('db_selected.html',
selected_collection=selected_collection)
@app.route('/about')
def about():
app.logger.info('selected_collection is {}'.format(g.selected_collection))
return render_template('about.html')
index.html文件:
{%extends 'layout.html'%}
{%block body%}
<div class="jumbotron text-center">
<h1>Welcome to the index.html file !</h1>
</div>
<div class="container">
{% include 'db_query_bar.html' %}
</div>
{%endblock%}
{%extends'layout.html%}
{%block body%}
欢迎使用index.html文件!
{%include'db\u query\u bar.html%}
{%endblock%}
db\u query\u bar.html
<form class="form-horizontal" action="{{ url_for('db_selected') }}" name="Item_1" method="POST">
<fieldset>
<legend>Select DB</legend>
<div class="form-group">
<label for="select" class="col-lg-2 control-label">Database Collection:</label>
<select id="DB" class="form-control" name="Item_4" style="width: 70%" >
<!-- <option value="">All</option> -->
{% for item in coll_name %}
<option value="{{item}}">{{item}}</option>
{% endfor %}
</select>
<br>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
选择数据库
数据库收集:
{coll_name%}中的项为%
{{item}}
{%endfor%}
提交
为了回答这个问题,我最后放置了一个全局变量
app.selected_collection = "Some Value"
在我的flask代码的顶部,这将创建一个全局变量,我可以在所有视图中使用它
app = Flask(__name__)
# CONFIG MONGO CONNECTION DETAILS
app.config['MONGO_HOST'] = 'DB-Host'
app.config['MONGO_DBNAME'] = 'DB-Collection'
app.selected_collection = "Some Value"
# INIT MONGODB
mongo = PyMongo(app)