154.md 3.0 KB
Newer Older
W
wizardforcel 已提交
1
# Flask 教程:路由
W
init  
wizardforcel 已提交
2 3 4 5 6

> 原文: [https://pythonbasics.org/Flask-Tutorial-Routes/](https://pythonbasics.org/Flask-Tutorial-Routes/)

现代的 Web 应用程序使用一种称为路由的技术。 这可以帮助用户记住 URL。 例如,他们看到的不是/booking.php,而是/ booking /。 他们会看到/ account / 1234 /,而不是/account.asp?id=1234/。

W
wizardforcel 已提交
7

W
init  
wizardforcel 已提交
8

W
wizardforcel 已提交
9
## 路由
W
init  
wizardforcel 已提交
10

W
wizardforcel 已提交
11
### Flask 路由示例
W
init  
wizardforcel 已提交
12

W
wizardforcel 已提交
13
Flask 中的路由映射到 Python 函数。 您已经创建了一条路由,即“ /”路由:
W
init  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
```py
W
init  
wizardforcel 已提交
16 17 18 19 20 21 22 23 24
@app.route('/')
    def index():

```

route()**装饰器** `@app.route()`将 URL 绑定到函数。

如果需要路由/ hello,可以将其绑定到 hello_world()函数,如下所示:

W
wizardforcel 已提交
25
```py
W
init  
wizardforcel 已提交
26 27 28 29 30 31 32 33
@app.route('/hello')
def hello_world():
   return "hello world"

```

函数 hello_world()的输出显示在浏览器中。

W
wizardforcel 已提交
34
### Flask 路径参数
W
init  
wizardforcel 已提交
35 36 37

创建路由时可以使用参数。 参数可以是这样的字符串(文本):`/product/cookie`

W
wizardforcel 已提交
38
这将具有以下路由和功能:
W
init  
wizardforcel 已提交
39

W
wizardforcel 已提交
40
```py
W
init  
wizardforcel 已提交
41 42 43 44 45 46
@app.route('/product/<name>')
def get_product(name):
  return "The product is " + str(name)

```

W
wizardforcel 已提交
47
因此,您可以将参数传递给 Flask 路由,可以传递数字吗?
W
init  
wizardforcel 已提交
48 49 50

此处的示例创建路由`/sale/&lt;transaction_id&gt;`,其中 transaction_id 是数字。

W
wizardforcel 已提交
51
```py
W
init  
wizardforcel 已提交
52 53 54 55 56 57
@app.route('/sale/<transaction_id>')
def get_sale(transaction_id=0):
  return "The transaction is "+str(transaction_id)

```

W
wizardforcel 已提交
58
### Flask 多参数路由
W
init  
wizardforcel 已提交
59

W
wizardforcel 已提交
60
如果您希望烧瓶路由具有多个参数,则可以这样做。 对于路由`/create/<first_name>/<last_name>`,您可以执行以下操作:
W
init  
wizardforcel 已提交
61

W
wizardforcel 已提交
62
```py
W
init  
wizardforcel 已提交
63 64 65 66 67 68
@app.route('/create/<first_name>/<last_name>')
def create(first_name=None, last_name=None):
  return 'Hello ' + first_name + ',' + last_name

```

W
wizardforcel 已提交
69
### Flask  POST 路由
W
init  
wizardforcel 已提交
70 71 72 73 74

Flask 支持 HTTP POST 请求。 如果您对此不熟悉,我建议您学习此课程:[使用 Flask](https://gum.co/IMzBy) 创建应用。

创建一个名为 login.html 的模板

W
wizardforcel 已提交
75
```py
W
init  
wizardforcel 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89
<html>
   <body>
      <form action = "http://localhost:5000/login" method = "post">
         <p>Username:</p>
         <p><input type = "text" name = "name" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

```

下面的代码支持两种类型的 HTTP 请求。

W
wizardforcel 已提交
90
```py
W
init  
wizardforcel 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
from flask import Flask
from flask import render_template
from flask import request

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/dashboard/<name>')
def dashboard(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['name']
      return redirect(url_for('dashboard',name = user))
   else:
      user = request.args.get('name')
      return render_template('login.html')

if __name__ == '__main__':
   app.run(debug = True)

```

如果收到这样的错误,则路由错误:

W
wizardforcel 已提交
118
```py
W
init  
wizardforcel 已提交
119 120 121 122 123
werkzeug.routing.BuildError
werkzeug.routing.BuildError: Could not build url for endpoint 'dashboard'. Did you forget to specify values ['name']? 
```

**[下载示例](https://gum.co/IMzBy)**