Flask请求、响应和请求扩展

Flask请求、响应和请求扩展

一、请求对象

1. Flask中的request对象特点:

  • 全局性 :在Flask应用中,request对象是全局可访问的,不需要在每个视图函数中单独传递。

  • 请求特定 :虽然request是全局的,但它对于每个请求是唯一的,即每个请求都会有一个新的request实例。

  • 属性丰富request对象提供了许多属性和方法,用于获取请求的各个方面,如请求方法、请求参数、请求头等。

2. 常用request属性:

  • request.method:返回请求的HTTP方法(如GET、POST等)。

  • request.args:返回一个字典,包含GET请求中的查询字符串参数。

  • request.form:返回一个字典,包含POST请求中的表单数据。

  • request.values:返回一个字典,包含GET和POST请求中的所有数据。

  • request.cookies:返回一个字典,包含客户端发送的cookie。

  • request.headers:返回一个字典,包含请求的HTTP头信息。

  • request.path:返回请求的路径部分(不包括查询字符串)。

  • request.full_path:返回请求的完整路径(包括查询字符串)。

  • request.script_root:返回请求的脚本根路径。

  • request.url:返回请求的完整URL(包括查询字符串)。

  • request.base_url:返回请求的基础URL(不包括查询字符串)。

  • request.url_root:返回请求的根URL。

  • request.host_url:返回请求的主机URL。

  • request.host:返回请求的主机名和端口。

  • request.files:返回一个字典,包含上传的文件。

  • 文件上传

    • 使用request.files可以访问上传的文件。可以通过文件名获取文件对象,并使用文件对象的save方法保存文件。

二、响应对象

1. 响应四件套

  1. 直接返回字符串:直接在视图函数中返回一个字符串,Flask会自动创建一个响应对象,并将该字符串作为响应体。

    python 复制代码
    return 'Hello, World!'
  2. 返回模板 :使用render_template函数渲染模板并返回响应。

    python 复制代码
    return render_template('index.html')
  3. 返回重定向 :使用redirect函数创建一个重定向响应。

    python 复制代码
    return redirect('http://example.com')
  4. 返回JSON格式 :使用jsonify函数将Python字典转换为JSON响应。

    python 复制代码
    return jsonify({'key': 'value'})

2. 在响应中写Cookie

  • 使用make_response函数创建一个响应对象,然后使用set_cookie方法

  • 设置cookie。

    python 复制代码
    res = make_response('home')
    res.set_cookie('yyy', 'yyy', path='/home')
  • 删除Cookie:

    python 复制代码
    res.delete_cookie('key')

3. 在响应头中写内容

  • 使用make_response创建响应对象后,可以直接操作响应头的字典。

    python 复制代码
    res = make_response('home')
    res.headers['xxx'] = 'xxx'

三、常用的请求扩展

1. 请求前处理:

  • before_request:在请求到达视图函数之前调用,可以用来执行一些预处理操作,如权限检查或数据初始化。

python 复制代码
@app.before_request
def before_request_func():
    print('before_request_func')

2. 请求后处理:

  • after_request:在请求结束后调用,可以对响应对象进行处理,如添加额外的响应头或进行日志记录。

python 复制代码
@app.after_request
def after_request_func(response):  # 有参数response
    print('after_request_func')
    # 一定要返回response
    return response
  • teardown_request:在每个请求结束后调用,无论是否有异常发生,常用于资源清理或请求后的日志记录。

python 复制代码
@app.teardown_request
def teardown_request_func(error=None):
    print('teardown_request_func')

3. 错误处理:

  • errorhandler:用于注册错误处理函数,当特定类型的错误发生时(如404,500等),将调用这些函数来处理错误。

python 复制代码
@app.errorhandler(404)
def page_not_found(error):
    return '404 Not Found', 404


@app.errorhandler(500)
def internal_server_error(error):
    return '500 Internal Server Error', 500

4. 模板全局函数和过滤器:

  • template_global:注册可以在模板中直接使用全局函数。

python 复制代码
@app.template_global()
def reverse(s):
    print('reverse')
    return s[::-1]

# 模板中使用
{{reverse(s)}}
  • template_filter:注册自定义的模板过滤器,以便在模板中轻松处理数据。

python 复制代码
@app.template_filter('reverse')
def reverse_filter(s):
    print('reverse_filter')
    return s[::-1]


# 模板中使用
{{ my_string|reverse_string }}

四、请求扩展示例

python 复制代码
from datetime import datetime

from flask import Flask, render_template
app = Flask(__name__)

@app.before_request
def before_request_func():
 print("Before Request")

@app.after_request
def after_request_func(response):
 print("After Request")
 return response

@app.teardown_request
def teardown_request_func(exception):
 print("Teardown Request")

@app.errorhandler(500)
def server_error(error):
 return 'Internal Server Error', 500

@app.template_global()
def format_time(dt):
 return dt.strftime('%Y-%m-%d %H:%M:%S')

@app.template_filter()
def reverse_string(s):
 return s[::-1]

@app.route('/')
def index():
 return render_template('index.html', current_time=datetime.now(), reversed_string='Hello World')

if __name__ == '__main__':
 app.run()
html 复制代码
# index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Welcome to my website</h1>
{{ format_time(current_time) }}
{{ reversed_string|reverse_string }}
</body>
</html>
相关推荐
玄武后端技术栈22 分钟前
什么是死信队列?死信队列是如何导致的?
后端·rabbitmq·死信队列
小文数模1 小时前
2025数维杯数学建模C题完整分析参考论文(共36页)(含模型、可运行代码、数据)
python·数学建模·matlab
是梦终空1 小时前
Python毕业设计219—基于python+Django+vue的房屋租赁系统(源代码+数据库+万字论文)
python·django·vue·毕业设计·毕业论文·源代码·房屋租赁系统
Q_Q19632884751 小时前
python小区物业管理系统-小区物业报修系统
开发语言·spring boot·python·django·flask·node.js·php
小小毛桃1 小时前
使用PyTorch训练马里奥强化学习代理的完整指南
人工智能·pytorch·python
yuanpan2 小时前
平面坐标系中判断点P是否在线段上AB上的常用方法总结
开发语言·python·平面·点线关系
海拥✘2 小时前
用Python监控金价并实现自动提醒!附完整源码
开发语言·python
王大傻09282 小时前
python实现点餐系统
python
知识中的海王2 小时前
猿人学web端爬虫攻防大赛赛题第7题——动态字体,随风漂移
爬虫·python
手机忘记时间2 小时前
在R语言中如何将列的名字改成别的
java·前端·python