python - flask中不同路由之間傳遞參數(shù)
問題描述
最近用flask開發(fā)一個web應(yīng)用,其中有一個搜索頁面和結(jié)果頁面,搜索頁面有多個表單,目前在搜索頁面的路由函數(shù)中已經(jīng)成功處理這些表單,得到的結(jié)果存儲在了一個list類型的變量里面,我想將這個變量傳遞到另一個頁面也就是結(jié)果頁面中,將結(jié)果顯示出來,有什么路由之間傳遞參數(shù)的方法嗎
@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁面def fsearch(): .... if request.method == ’POST’:results = multiselect(request) #這是處理表單的函數(shù),reslults為list類型變量... return render_template('new.html') @app.route(’/result’, methods=[’get’, ’post’]) #這是結(jié)果頁面def fresult(): ... return render_template('result.html')
問題解答
回答1:用個全局變量
results = None@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁面def fsearch(): .... if request.method == ’POST’:global resultsresults = multiselect(request) #這是處理表單的函數(shù),reslults為list類型變量... return render_template('new.html') @app.route(’/result’, methods=[’get’, ’post’]) #這是結(jié)果頁面def fresult(): global results print results return render_template('result.html')回答2:
請求直接對應(yīng)結(jié)果。為什么一個請求結(jié)束后還要再去做一個請求得到結(jié)果?
回答3:用redirect函數(shù)return redirect(url_for(’fresult’)),函數(shù)里面就能追加參數(shù)了。
回答4:@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁面def fsearch(): .... if request.method == ’POST’:results = multiselect(request) #這是處理表單的函數(shù),reslults為list類型變量....return return render_template('result.html', results=results) return render_template('new.html')回答5:
為什么一定要用post呢,可以參考我的實現(xiàn)
class SearchView(MethodView): def get(self):query_dict = request.datapage, number = self.page_infokeyword = query_dict.pop(’keyword’, None)include = query_dict.pop(’include’, ’0’)if keyword and len(keyword) >= 2: fields = None if include == ’0’:fields = [’title’, ’content’] elif include == ’1’:fields = [’title’] elif include == ’2’:fields = [’content’] results = Topic.query.msearch(keyword, fields=fields).paginate(page, number, True) data = {’title’: ’Search’, ’results’: results, ’keyword’: keyword} return render_template(’search/result.html’, **data)data = {’title’: ’Search’}return render_template(’search/search.html’, **data)
demo
相關(guān)文章:
1. 查詢mysql數(shù)據(jù)庫中指定表指定日期的數(shù)據(jù)?有詳細2. mysql - 怎么生成這個sql表?3. mysql儲存json錯誤4. php - 公眾號文章底部的小程序二維碼如何統(tǒng)計?5. mysql - 表名稱前綴到底有啥用?6. mysql - 數(shù)據(jù)庫表中,兩個表互為外鍵參考如何解決7. Navicat for mysql 中以json格式儲存的數(shù)據(jù)存在大量反斜杠,如何去除?8. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現(xiàn)存在即更新應(yīng)該使用哪個標(biāo)簽?9. mysql - 數(shù)據(jù)庫建字段,默認(rèn)值空和empty string有什么區(qū)別 11010. sql語句 - 如何在mysql中批量添加用戶?
