python - flask中不同路由之間傳遞參數
問題描述
最近用flask開發一個web應用,其中有一個搜索頁面和結果頁面,搜索頁面有多個表單,目前在搜索頁面的路由函數中已經成功處理這些表單,得到的結果存儲在了一個list類型的變量里面,我想將這個變量傳遞到另一個頁面也就是結果頁面中,將結果顯示出來,有什么路由之間傳遞參數的方法嗎
@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁面def fsearch(): .... if request.method == ’POST’:results = multiselect(request) #這是處理表單的函數,reslults為list類型變量... return render_template('new.html') @app.route(’/result’, methods=[’get’, ’post’]) #這是結果頁面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) #這是處理表單的函數,reslults為list類型變量... return render_template('new.html') @app.route(’/result’, methods=[’get’, ’post’]) #這是結果頁面def fresult(): global results print results return render_template('result.html')回答2:
請求直接對應結果。為什么一個請求結束后還要再去做一個請求得到結果?
回答3:用redirect函數return redirect(url_for(’fresult’)),函數里面就能追加參數了。
回答4:@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁面def fsearch(): .... if request.method == ’POST’:results = multiselect(request) #這是處理表單的函數,reslults為list類型變量....return return render_template('result.html', results=results) return render_template('new.html')回答5:
為什么一定要用post呢,可以參考我的實現
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
相關文章:
1. java - new + 類名,一定需要申明一個對象嗎?2. javascript - 前端開發 本地靜態文件頻繁修改,預覽時的緩存怎么解決?3. java - public <T> T findOne(T record) 這是什么意思4. android - 優酷的安卓及蘋果app還在使用flash技術嗎?5. docker不顯示端口映射呢?6. mysql數據庫每次查詢是一條線程嗎?7. python - linux怎么在每天的凌晨2點執行一次這個log.py文件8. javascript - 我的站點貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?9. 如何分別在Windows下用Winform項模板+C#,在MacOSX下用Cocos Application項目模板+Objective-C實現一個制作游戲的空的黑窗口?10. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發現
