python - flask中不同路由之間傳遞參數(shù)
問(wèn)題描述
最近用flask開(kāi)發(fā)一個(gè)web應(yīng)用,其中有一個(gè)搜索頁(yè)面和結(jié)果頁(yè)面,搜索頁(yè)面有多個(gè)表單,目前在搜索頁(yè)面的路由函數(shù)中已經(jīng)成功處理這些表單,得到的結(jié)果存儲(chǔ)在了一個(gè)list類型的變量里面,我想將這個(gè)變量傳遞到另一個(gè)頁(yè)面也就是結(jié)果頁(yè)面中,將結(jié)果顯示出來(lái),有什么路由之間傳遞參數(shù)的方法嗎
@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁(yè)面def fsearch(): .... if request.method == ’POST’:results = multiselect(request) #這是處理表單的函數(shù),reslults為list類型變量... return render_template('new.html') @app.route(’/result’, methods=[’get’, ’post’]) #這是結(jié)果頁(yè)面def fresult(): ... return render_template('result.html')
問(wèn)題解答
回答1:用個(gè)全局變量
results = None@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁(yè)面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é)果頁(yè)面def fresult(): global results print results return render_template('result.html')回答2:
請(qǐng)求直接對(duì)應(yīng)結(jié)果。為什么一個(gè)請(qǐng)求結(jié)束后還要再去做一個(gè)請(qǐng)求得到結(jié)果?
回答3:用redirect函數(shù)return redirect(url_for(’fresult’)),函數(shù)里面就能追加參數(shù)了。
回答4:@app.route(’/search’, methods=[’get’, ’post’]) #這是搜索頁(yè)面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呢,可以參考我的實(shí)現(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. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)2. html按鍵開(kāi)關(guān)如何提交我想需要的值到數(shù)據(jù)庫(kù)3. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標(biāo)點(diǎn)符號(hào)?正則如何寫?4. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問(wèn)題 麻煩幫我看一下5. gvim - 誰(shuí)有vim里CSS的Indent文件, 能縮進(jìn)@media里面的6. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯(cuò)誤7. PHP類屬性聲明?8. javascript - 請(qǐng)教如何獲取百度貼吧新增的兩個(gè)加密參數(shù)9. html - 微信瀏覽器h5<video>標(biāo)簽問(wèn)題10. java - 安卓接入微信登錄,onCreate不會(huì)執(zhí)行
