2017-10-09 90 views
-1

在我的燒瓶應用程序我正在使用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> 

回答

0

只是爲了回答這個問題的全局變量我最終配售

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)