Flask-如何将查询字符串参数转换为路由参数 [英] Flask - how to get query string parameters into the route parameters

查看:59
本文介绍了Flask-如何将查询字符串参数转换为路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Flask非常陌生,其中一个基本要求是我需要SEO友好的网址.
我有一条路线,说

Im very much new to Flask, and one of the starting requirements is that i need SEO friendly urls.
I have a route, say

@app.route('/sales/')
@app.route(/sales/<address>)
def get_sales(addr):
  # do some magic here
  # render template of sales

和提交地址的简单GET表单.

and a simple GET form that submits an address.

<form action={{ url_for('get_sales') }}> 
 <input type='text' name='address'>
 <input type=submit>
</form>

在提交表单时,请求将转到/sales/?address = somevalue而不是标准路径.我需要将该表格提交到/sales/somevalue的哪些选择?我觉得我缺少一些非常基本的东西.

On form submission, the request goes to /sales/?address=somevalue and not to the standard route. What options do I have to have that form submit to /sales/somevalue ? I feel like I'm missing something very basic.

推荐答案

您将需要使用JavaScript来实现此目的,因此您的模板将变为:

You would need to use JavaScript to achieve this so your template would become:

<input type='text' id='address'>
 <button onclick="sendUrl();">submit</button>


<script>
    function sendUrl(){
        window.location.assign("/sales/"+document.getElementById("address").value);
    }
</script>

和您以前的路线类似:

@app.route('/sales/')
@app.route('/sales/<address>')
def get_sales(address="Nowhere"):
  # do some magic here
  # render template of sales
  return "The address is "+address

但是,这不是做这种事情的最佳方法.另一种方法是让flask提供数据并使用单页应用程序框架从用户界面的角度处理路由.

However, this is not the best way of doing this kind of thing. An alternative approach is to have flask serve data and use a single-page-application framework in javascript to deal with the routes from a user interface perspective.

这篇关于Flask-如何将查询字符串参数转换为路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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