【Flask 系统教程 3】请求与响应

Flask 是一个灵活而强大的 Web 框架,而请求与响应则是构建 Web 应用的核心组成部分。在本文中,我们将探讨 Flask 中请求与响应的各种用法,包括不同的请求方法、重定向、响应对象、获取查询参数以及文件上传等。

请求

在 Flask 中,请求是客户端(浏览器)向服务器发送的消息,用于获取某种资源或执行某种操作。我们可以通过不同的方法来处理这些请求。

请求方式

通过使用不同的装饰器直接设置请求方法

python 复制代码
from flask import Flask

app = Flask(__name__)

@app.get('/get_example')
def get_example():
    return 'This is a GET request.'

@app.post('/post_example')
def post_example():
    return 'This is a POST request.'

@app.delete('/delete_example')
def delete_example():
    return 'This is a DELETE request.'

@app.put('/put_example')
def put_example():
    return 'This is a PUT request.'

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

对于不同的请求方式使用不同的装饰器即可进行设置。


通过装饰器 methods 参数设置请求方法

python 复制代码
from flask import Flask, request

app = Flask(__name__)


# GET 请求方法
@app.route('/get_example', methods=['GET'])
def get_example():
    return 'This is a GET request.'


# POST 请求方法
@app.route('/post_example', methods=['POST'])
def post_example():
    return 'This is a POST request.'


# PUT 请求方法
@app.route('/put_example', methods=['PUT'])
def put_example():
    return 'This is a PUT request.'


# DELETE 请求方法
@app.route('/delete_example', methods=['DELETE'])
def delete_example():
    return 'This is a DELETE request.'


# 支持 GET 和 POST 请求方法 
@app.route('/get_post_example', methods=['GET', 'POST'])  # 支持传入列表,实现多个方法
def get_post_example():
    if request.method == 'GET':
        return 'This is a GET request.'
    elif request.method == 'POST':
        return 'This is a POST request.'


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

重定向

在 Web 开发中,重定向是一种常见的技术,用于将用户从一个 URL 地址重定向到另一个 URL 地址。Flask 提供了多种重定向的方式,通过不同的状态码来实现不同的重定向效果。

python 复制代码
from flask import Flask, url_for, redirect

app = Flask(__name__)


@app.route('/redirect_example/')
def redirect_example():
    # 重定向到指定的 URL,并返回 301 状态码
    return redirect(url_for('target_route'), code=301)


@app.route('/target_route/')
def target_route():
    return "you get it here"


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

在以上示例中,使用函数 redirect即可实现对路由的重定向,并且可以设置状态码

  • 重定向状态码以及含义
状态码 名称 含义
301 永久重定向 请求的资源已被永久分配了新的 URL。
302 发现 请求的资源已被临时分配了新的 URL。
303 查看其他位置 对请求的响应可以在不同的 URL 下找到,并且应该使用 GET 方法检索请求的资源。
307 临时重定向 请求的资源已被临时移动到另一个位置。
308 永久重定向 请求的资源已被永久移动到另一个位置。

响应

响应是服务器返回给客户端的消息,它可以包含文本、JSON 数据、文件等内容。

响应对象

Flask 提供了 make_response() 函数用于创建响应对象,我们可以通过这个对象来设置响应的内容和状态码,同时 Flask也支持直接响应对应的数据

python 复制代码
from flask import make_response


# 响应模板
@app.route('/')
def index():
    return render_template('index.html')
# template_folder 指定模板文件夹 默认是同级目录的 templates

# 响应字符串
@app.route('/string')
def return_string():
    return "Hello, World!"


# 响应 JSON 数据
@app.route('/json')
def return_json():
    data = {'message': 'Hello, World!'}
    return data
    # return jsonify(data) 的效果一样,老版本不支持直接返回,必须要用jsonify


# 响应元组
@app.route('/tuple')
def return_tuple():
    response = ("Hello, World!", 200, {'Content-Type': 'text/plain'})
    response2 = ("Hello, World!", 200, [('Content-Type', 'text/plain')])
    response3 = ("Hello, World!", {'Content-Type': 'text/plain'})
    # 这都是合法的写法
    return response


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

可以返回一个元组,元组中必须至少包含一个项目,且项目应当由 (response, status) 、 (response, headers)或者 (response, status, headers)组成。 status的值会重载状态代码, headers是一个由额外头部值组成的列表 或字典, status值会覆盖状态代码, headers可以是一个列表或字典,作为额外的消息标头值。

除了返回文本外,我们还可以返回 JSON 数据、元组(包含响应内容、状态码和头信息)、模板等。

自定义响应对象

如果 Flask 提供的响应对象不能满足需求,我们还可以自定义响应对象。

python 复制代码
from flask import Flask, make_response, Response

app = Flask(__name__)


# 使用 response 返回自定义响应对象
@app.route('/response')
def custom_response():
    content = "Custom Response with response"
    code = 200
    headers = {'Content-Type': 'text/plain'}
    custom_resp = Response(content, code, headers)
    return custom_resp


# 使用 make_response 返回自定义响应对象
@app.route('/make_response')
def make_custom_response():
    content = "Custom Response with make_response"
    code = 200
    headers = {'Content-Type': 'text/plain'}
    custom_resp = make_response(content, code)
    custom_resp.headers.extend(headers)
    return custom_resp


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

获取查询参数

在处理 GET 请求时,我们经常需要获取 URL 中的查询参数。Flask 提供了 request.args 来获取查询参数。

python 复制代码
from flask import request

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

而在处理 POST 请求时,则可以使用 request.form来获取对应的参数

python 复制代码
@app.route('/example_post', methods=['POST'])
def example_post():
    # 获取表单中的参数
    name = request.form.get('name')
    return 'Hello, {}'.format(name)

但是无论对于GET请求或者POST请求,都可以使用 request.values来获取参数,用法与上一致。


文件上传

处理文件上传也是 Web 开发中的常见需求。Flask 提供了 request.files 来获取上传的文件。

python 复制代码
from flask import Flask, request, render_template

app = Flask(__name__)


@app.route('/upload', methods=['POST'])
def upload_image():
    if 'pic' not in request.files:
        return "未上传文件"
    file = request.files['pic']  # pic是上传参数的key
    file.save("test.png")

    return "文件上传成功"


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

结语

通过本文的介绍,我们深入了解了 Flask 中请求与响应的多种用法。无论是处理不同的请求方法、实现重定向、创建不同类型的响应对象,还是处理查询参数和文件上传,Flask 都提供了丰富的功能和灵活的方法,使得 Web 开发变得更加简单和高效。希望本文对您有所帮助!

相关推荐
一线大码19 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
秃了也弱了。19 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
Dfreedom.19 小时前
从 model(x) 到__call__:解密深度学习框架的设计基石
人工智能·pytorch·python·深度学习·call
weixin_4250230019 小时前
Spring Boot 配置文件优先级详解
spring boot·后端·python
weixin_4250230019 小时前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码19 小时前
Java 8-25 各个版本新特性总结
java·后端
VX:Fegn089520 小时前
计算机毕业设计|基于springboot + vue校园社团管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·课程设计
To Be Clean Coder20 小时前
【Spring源码】通过 Bean 工厂获取 Bean 的过程
java·后端·spring
小徐Chao努力20 小时前
【Langchain4j-Java AI开发】06-工具与函数调用
java·人工智能·python
无心水20 小时前
【神经风格迁移:全链路压测】33、全链路监控与性能优化最佳实践:Java+Python+AI系统稳定性保障的终极武器
java·python·性能优化