要回答我的問題(雖然有可能是我只是不知道一個簡單的和更好的方法,但這裏是我落得這樣做,現在)...
我創建了一個自定義路由轉換器(用於執行此操作的方法描述爲here),並將其註冊到我的應用中,以便我可以在我的view_results()
路由中使用它。我說這個我utils.py
,我在同一個目錄中我的應用程序的初始化:
from werkzeug.routing import BaseConverter
class DictionaryConverter(BaseConverter):
"""Convert python dictionary to URL query string and back."""
def to_python(self, value):
d = {}
for item in value.split('&'):
k, v = item.split('=')
if k != 'csrf_token':
d[k] = v
return d
def to_url(self, values):
pairs = []
for k in values:
#don't expose the csrf token in the query string
if k != 'csrf_token':
pairs.append('{}={}'.format(k, values[k]))
return '&'.join(BaseConverter.to_url(self, value=pair) for pair in pairs)
然後在我的應用程序__init__.py
我確信初始化程序後註冊自定義轉換器,但是加載使用的藍圖前它(我main
藍圖):
app = Flask(__name__)
# ...
from .utils import DictionaryConverter
app.url_map.converters['dict'] = DictionaryConverter
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
我的搜索視圖從request.form
發送數據(這是該數據去上崗)一起的結果視圖。我使用code=303
來消除歧義,並且使用make certain the request is sent as a GET,但這可能不是什麼大問題。
@main.route('/search/', methods=['GET', 'POST'])
def search():
form = SearchForm()
if form.validate_on_submit():
return redirect(url_for('.view_results', data=request.form), code=303)
return render_template('search.html', form=form)
最後,我的結果視圖使用新的轉換器,然後我可以按通常(正如你所看到的,我還沒有真正做任何事的又訪問數據,但現在我應該是能夠啓動):
@main.route('/search/results?<dict:data>')
def view_results(data):
for i in data:
print(i, data[i])
return "placeholder"
這似乎是工作,但我還是覺得我只是缺少從瓶的東西很明顯,不會要求創建一個自定義轉換器...
千萬不要錯過' 'form.data''到視圖,通過''form.field.data''。用你的字段名替換該字段 –
@AliFaki哦,我明白了......一次只傳一個並在路由中自己構建查詢字符串?例如'@ main.route('/ search/results?field1 =&field2 = &field3 = ')' –
KaleidoEscape