【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 开发变得更加简单和高效。希望本文对您有所帮助!

相关推荐
一朵小花14 分钟前
Python中with的用法
python
m0_7482323937 分钟前
基于OpenCV和Python的人脸识别系统_django
python·opencv·django
dme.1 小时前
Python爬虫selenium验证-中文识别点选+图片验证码案例
爬虫·python
东方-教育技术博主1 小时前
wps中zotero插件消失,解决每次都需要重新开问题
python
后端码匠1 小时前
Spring Boot3+Vue2极速整合:10分钟搭建DeepSeek AI对话系统
人工智能·spring boot·后端
可乐张1 小时前
AutoGen 技术博客系列 (九):从 v0.2 到 v0.4 的迁移指南
后端·llm
可乐张1 小时前
AutoGen 技术博客系列 (八):深入剖析 Swarm—— 智能体协作的新范式
后端·llm
计算机-秋大田1 小时前
基于Spring Boot的农产品智慧物流系统设计与实现(LW+源码+讲解)
java·开发语言·spring boot·后端·spring·课程设计
计算机毕设指导62 小时前
基于SpringBoot的城乡商城协作系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
镰圈量化2 小时前
当电脑上有几个python版本Vscode选择特定版本python
开发语言·vscode·python