网址结构和形式与Flask的帖子 [英] url structure and form posts with Flask

查看:179
本文介绍了网址结构和形式与Flask的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  @ app.route('/ search /< 

在Flask中, ;位置> /')
def search():
return render_template('search.html')

然而,在HTML中,表单将以这种方式发布到网址中

  www.myapp.com/搜索?位置=巴黎

后者似乎从应用程序返回了一个404

  www.myapp.com/search/london 

会按预期的方式返回。



我确信有一个简单的难题,我没有得到,但肯定是路由引擎会考虑符合规则要求的查询字符串参数。

如果不是这种情况下的最佳解决方案,我相信90%的开发者必须到达这一点...



在此先感谢。

解决方案

查询参数不包含在路由匹配中,他们注入到函数的参数。只有匹配的URL部分被注入。你要找的是 request.args (GET查询参数), request.form (POST)或 request.values (合并)。

如果你想要支持这两者,你可以这样做:

  @ app.route('/ search /< location>')
def search(location = None):
location = location or request.args.get('location')
#执行搜索



<尽管如此,假设你可能想搜索其他参数,可能最好的办法是更接近:

  def _search(location = None,other_param = None):
#执行搜索

@ app.route('/ search')
def search_custom():
location = request.args.get('location')
#...获取其他参数...
返回_search(location = location,other params ...)

@ app.route('/ search /< location>)
def search_location(location):
return _s earch(location = location)

等等。

In Flask you write the route above the method declaration like so:

@app.route('/search/<location>/')
def search():
  return render_template('search.html')

However in HTML as form will post to the url in this fashion

www.myapp.com/search?location=paris

the latter seems to return a 404 from the application where

www.myapp.com/search/london

will return as expected.

I'm sure that there is a simple piece of the puzzle that i'm not getting, but surely the routing engine will consider the query string parameters for meeting the rules requirements.

If not what is the optimal solution for this scenario as i'm sure 90% of developers must arrive at this point...

thanks in advance.

解决方案

The query parameters are not included as part of the route matching, nor are they injected into function arguments. Only the matched URL portions are injected. What you're looking for is request.args (GET query parameters), request.form (POST) or request.values (combined).

You could do something like this if you wanted to support both:

@app.route('/search/<location>')
def search(location=None):
    location = location or request.args.get('location')
    # perform search

Though, assuming you may want to search on other parameters, probably the best way to do it would be closer to:

def _search(location=None,other_param=None):
    # perform search

@app.route('/search')
def search_custom():
    location = request.args.get('location')
    # ... get other params too ...
    return _search(location=location, other params ... )

@app.route('/search/<location>')
def search_location(location):
    return _search(location=location)

And so forth.

这篇关于网址结构和形式与Flask的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆