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>
相关推荐
大江东去浪淘尽千古风流人物11 分钟前
【Python】第三方库的功能简介
开发语言·python
坐忘3GQ16 分钟前
65.Python-web框架-Django-免费模板django-datta-able的admin_datta
后端·python·django·templates·datta able·admin_datta
HZ3557217 分钟前
智谱AI: ChatGLM API的使用
python·自然语言处理
PhoenixAI826 分钟前
AI绘画-Stable Diffusion 原理介绍及使用
人工智能·python·机器学习·ai作画·stable diffusion
2301_7969821429 分钟前
pycharm中新建的临时python文件存放在哪里?
ide·python·pycharm
U盘失踪了30 分钟前
Django 多对多关系
python·django
LightOfNight34 分钟前
【后端面试题】【中间件】【NoSQL】ElasticSearch的优化方案1(分页查询、刷新间隔、批量提交)
数据库·redis·后端·elasticsearch·缓存·中间件·nosql
eclipsercp39 分钟前
《每天5分钟用Flask搭建一个管理系统》 第7章:用户认证
后端·python·flask
小尤笔记1 小时前
Python知识点背诵手册,超详细知识梳理
开发语言·python·学习·python入门·学习手册
经海路大白狗1 小时前
开启IT世界的第一步:高考新生的暑期学习指南
前端·后端·python·学习·高考