flask框架基础
Flask 允许在路由中包含参数,以便根据不同的参数值返回不同的内容。
<br>
<br>
```
<br>
@app.route('/user/<username>')
<br>
def show_user_profile(username):
<br>
return f'User {username}'
<br>
```
<br>
<br>
当访问http://localhost:5000/user/john时,username参数的值为john,show_user_profile()函数会返回User john。
<br>
<br>
还可以指定参数的类型,例如:
<br>
<br>
```
<br>
@app.route('/post/<int:post_id>')
<br>
def show_post(post_id):
<br>
return f'Post {post_id}'
<br>
```
<br>
<br>
这里的int表示post_id参数必须是整数类型,如果传入非整数类型的值,Flask 会返回 404 错误。
<br>
<br>
### 3.3 运行应用
<br>
<br>
定义好路由和视图函数后,可以通过以下代码运行 Flask 应用:
<br>
<br>
```
<br>
if __name__ == '__main__':
<br>
app.run(debug=True)
<br>
```
<br>
<br>
app.run()方法用于启动开发服务器,debug=True表示开启调试模式。在调试模式下,当代码发生变化时,服务器会自动重新加载,并且如果出现错误,会在浏览器中显示详细的错误信息,方便开发调试。
<br>
<br>
运行上述代码后,在浏览器中访问http://localhost:5000,就可以看到对应的响应内容了。
<br>
<br>
## 四、模板引擎
<br>