【问题标题】:flask database global variable烧瓶数据库全局变量
【发布时间】:2017-10-09 20:48:49
【问题描述】:

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

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

例如,在索引页面上,我可以选择一个集合,然后在提交时它会将我重定向到查看 db_selected 我试图将 selected_collection 设为全局变量,但如果我进入 about 视图,它会得到一个相关的错误到

我想我应该使用 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>

【问题讨论】:

    标签: flask flask-wtforms flask-login


    【解决方案1】:

    只是为我最终放置的全局变量回答这个问题

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多