Flask 动态路由、请求数据接收、视图函数返回值详解

一、动态路由

在前面的博客中,我们学习了如何创建基本的 Flask 应用,并定义了一些简单的路由。但有时候,我们需要更加灵活的路由,能够根据用户请求的不同来动态生成响应。Flask 提供了动态路由的功能,使我们能够轻松处理这种需求。

使用动态路由参数

动态路由是指路由中的某些部分可以是变量,这样在处理请求时可以获取这些变量的值。例如:

from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    return f'User {
     username}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post {
     post_id}'

在上面的例子中,<username><int:post_id> 都是动态路由参数。当用户访问 /user/john 时,username 参数将被设置为 'john';当用户访问 /post/1 时,post_id 参数将被设置为 1。在Flask中,除了int之外,还有一些其他的数据类型可以用于动态路由。以下是一些常见的数据类型和它们的描述:

数据类型 描述
int 接受整数
float 接受浮点数
path 类似字符串,但可以包含斜杠(/)
string 默认类型,接受没有斜杠的字符串
uuid 接受UUID字符串

二、获取请求中的数据

1. 在 GET 请求中获取参数

在 Flask 中,可以使用 request.args 对象来获取 GET 请求中传递的参数。这些参数通常是通过查询字符串(Query String)传递的。

from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search():
    query = request.args.get('q')
    return f'Search query: {
     query}'

用户可以通过访问 /search?q=Flask 来传递搜索参数。

2. 在 POST 请求中获取表单参数(Content-Type=multipart/form-data Content-Type=application/x-www-form-urlencoded)
from flask import Flask, request

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    return f'Username: {
     username}, Password: {
     password}'
3. 在 POST 请求中获取raw数据(Content-Type=application/json Content-Type=text/plain)
from flask import Flask, request

app = Flask(__name__)

@app.route('/raw', methods=['POST'])
def get_raw_data():
    data = request.data
    return f'Raw data received: {
     data.decode()}'
4. 在 POST 请求中获取文件数据(Content-Type=multipart/form-data)
from flask import Flask, request

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return 'No file part'

    file = request.files['file']

    if file.filename == '':
        return 'No selected file'

    return f'File {
     file.filename} uploaded successfully'
5. 获取请求中的header和cookie
from flask import Flask, request

app = Flask(__name__)

@app.route('/get_data')
def get_data():
    cookie_data = request.cookies.get('my_cookie')
    header_data = request.headers.get('User-Agent')
    return f'Cookie data: {
     cookie_data}, User-Agent: {
     header_data}'

三、视图函数返回值

视图函数的返回值会自动转换为一个响应对象。如果返回值是一个字符串,那 么会被转换为一个包含作为响应体的字符串、一个 200 OK 出错代码 和一 个 text/html 类型的响应对象。如果返回值是一个字典或者列表, 那么会调用 jsonify() 来产生一个响应。以下是转换的规则:

  • 如果视图返回的是一个响应对象,那么就直接返回它。

  • 如果返回的是一个字符串,那么根据这个字符串和缺省参数生成一个用于 返回的响应对象。

  • 如果返回的是一个迭代器或者生成器,那么返回字符串或者字节,作为流 响应对待。

  • 如果返回的是一个字典或者列表,那么使用 jsonify() 创建一个响应对象。

  • 如果返回的是一个元组,那么元组中的项目可以提供额外的信息。元组中 必须至少包含一个项目,且项目应当由 (response, status) 、 (response, headers) 或者 (response, status, headers) 组 成。 status 的值会重载状态代码, headers 是一个由额外头部 值组成的列表或字典。

  • 如果以上都不是,那么 Flask 会假定返回值是一个有效的 WSGI 应用并把 它转换为一个响应对象。

  • 如果想要在视图内部掌控响应对象的结果,那么可以使用 make_response() 函数。

from flask import Flask, jsonify

app = Flask(__name__)

# 返回字符串
@app.route('/string')
def return_string():
    return 'Hello, Flask!'

# 返回元组 (response, status, headers)
@app.route('/tuple')
def return_tuple():
    return 'Hello, Flask!', 200, {
   'Content-Type': 'text/plain'}

# 返回 Response 对象
@app.route('/response')
def return_response():
    return jsonify({
   'message': 'Hello, Flask!'})

重定向

在 Flask 中,可以使用 redirect 函数来进行重定向。

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/redirect_example')
def redirect_example():
    # 重定向到 /new_location 路由
    return redirect('/new_location')

@app.route('/new_location')
def new_location():
    return 'New location!'

总结

在本篇博客中,我们学习了如何使用 Flask 处理动态路由,以及在请求中获取参数的方法。无论是通过动态路由参数,还是通过请求对象的不同属性,Flask 提供了丰富的工具来处理各种请求和路由需求。

相关推荐

  1. 第2天:Flask视图函数

    2023-12-05 16:16:08       5 阅读
  2. flask (route)

    2023-12-05 16:16:08       15 阅读
  3. Vue-router的动态:获取传递的

    2023-12-05 16:16:08       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-05 16:16:08       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-05 16:16:08       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-05 16:16:08       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-05 16:16:08       18 阅读

热门阅读

  1. uniapp搭建内网映射测试https域名

    2023-12-05 16:16:08       46 阅读
  2. flask五小时快速入门资料记录

    2023-12-05 16:16:08       47 阅读
  3. Leetcode 2949. Count Beautiful Substrings II

    2023-12-05 16:16:08       40 阅读
  4. tortoisegit 报错:server refused to start a shell/command

    2023-12-05 16:16:08       40 阅读
  5. mybatis中<association> 和 <collection>

    2023-12-05 16:16:08       33 阅读
  6. 嵌入式硬件基础知识——1

    2023-12-05 16:16:08       35 阅读
  7. mySQL踩坑记录

    2023-12-05 16:16:08       43 阅读
  8. SpringDocConfiguration

    2023-12-05 16:16:08       30 阅读
  9. Linux CenTOS命令备忘

    2023-12-05 16:16:08       36 阅读