flask 数据库全局变量

flask database global variable

在我的 Flask 应用程序中,我使用的是 mongoDB,在主页上,我有一个表单 returning 该特定数据库中的所有已知集合。我要求用户选择他们想要使用的集合,因为我将使用该集合设置为 return 其他路由或视图中的所有文档。

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

例如在索引页上我可以 select 一个集合,然后在提交时它会重定向我查看 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)