瓶数据库全局变量

问题描述:

在我的烧瓶应用程序我正在使用mongoDB,并在主页上我有一个窗体返回该特定数据库中的所有已知集合。我要求用户选择他们想要使用的集合,因为我将使用该集合集来返回其他路径或视图中的所有文档。瓶数据库全局变量

我正在努力如何使这个全局“selected_collection”成为所有路线和视图可以使用的全局变量。

例如在索引页上我能够选择一个集合,然后在提交它会重定向我查看db_selected那里我试图使selected_collection全局变量,但如果我到了关于视图它会得到一个错误有关

我想我应该使用flask.g,但我不知道如何让它工作。我已经阅读了一些文件,但他们对我有点模糊。

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%} 

db_query_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> 

只是为了回答这个问题的全局变量我最终配售

app.selected_collection = "Some Value" 

在我的烧瓶代码的顶部,这将创建一个全局变量,我可以在所有视图中使用。

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)