Flask学习笔记 - 视图函数

前言

继续自习...

Flask 视图函数

视图函数是Flask应用中的核心部分,它负责处理请求并生成响应

  1. 定义视图函数:视图函数是处理请求并返回响应的核心功能。
  2. 接收请求数据:使用 request 对象获取 URL 参数、表单数据、查询参数等。
  3. 返回响应:可以返回字符串、HTML、JSON 或自定义响应对象。
  4. 处理请求和响应:使用 request 对象和 make_response 来处理请求和生成自定义响应。
  5. 处理错误:视图函数内处理异常或使用 Flask 的错误处理机制。
  6. 视图函数的装饰器:使用 @app.before_request、@app.after_request 等装饰器处理请求前后逻辑。
  7. 视图函数返回的状态码:可以指定 HTTP 状态码来表示请求的处理结果。

定义视图函数/接收请求数据/返回响应/处理请求和响应

python 复制代码
from flask import request

# 接收 - URL参数
@app.route('/greet/<name>')  
def greet(name):
    return f'Hello, {name}!'

# 接收 - 表单数据
@app.route('/submit', methods=['POST'])  
def submit():
    username = request.form.get('username')  
    return f'Form submitted by {username}!'

# 接收 - GET请求中query
@app.route('/search')
def search():
    query = request.args.get('query')
    return f'Search results for: {query}'
    
# 返回 - 字符串
@app.route('/message')
def message():
    return 'This is a simple message.'

# 返回 - HTML模板
@app.route('/hello/<name>')
def html_hello(name):
    return render_template('hello.html', name=name)

# 返回 - JSON
@app.route('/api/data')
def api_data():
    data = {'key': 'value'}
    return jsonify(data)

# 返回 - 自定义响应对象
@app.route('/custom')
def custom_response():
    response = Response('Custom response with headers', status=200)
    response.headers['X-Custom-Header'] = 'Value'
    return response

# 处理请求和响应
@app.route('/info')
def info():
    user_agent = request.headers.get('User-Agent')
    return f'Your user agent is {user_agent}'

处理错误

可以在视图函数中处理异常或错误,或者通过 Flask 提供的错误处理机制来处理应用中的错误

python 复制代码
# try-except
# /divide/3/0
@app.route('/divide/<int:x>/<int:y>')
def divide(x, y):
    try:
        result = x / y
        return f'Result: {result}'
    except ZeroDivisionError:
        return 'Error: Division by zero', 400

# 全局错误
@app.errorhandler(404)
def not_found(error):
    return '消失了', 404

抛异常

正常

全局错误码

装饰器

  • @app.before_request:在每个请求处理之前运行的函数。
  • @app.after_request:在每个请求处理之后运行的函数。
  • @app.teardown_request:在请求结束后运行的函数,用于清理工作。
python 复制代码
@app.before_request
def before_request():
    print('请求前')

@app.after_request
def after_request(response):
    print('请求后')
    return response

@app.teardown_request
def teardown_request(exception):
    print('请求结束,清理')

看到终端有输出对应的日志

视图函数返回的状态码

视图函数不仅可以返回内容,还可以指定 HTTP 状态码。

python 复制代码
# 返回
@app.route('/status')
def status():
    return 'Everything is OK', 200

@app.route('/error')
def error():
    return Response('An error occurred', status=500)

工具栏 - 帮助 - 切换开发人员工具,可以打开开发工具,检查网络,确认确实返回了500的错误码

Demo

Flask

参考

  1. Flask 视图函数
相关推荐
心运软件1 天前
Fashion-MNIST 图像分类实战:TensorFlow 五模型对比与 Flask 可视化
分类·flask·tensorflow
编码者卢布1 天前
【Azure Storage Account】Azure Queue指标中的Transactions 高,真实业务处理的消息就多吗?
microsoft·flask·azure
winfredzhang4 天前
从零实现“照片按地理位置显示在矢量地图上”:Flask + SQLite + Leaflet 全栈实战
python·sqlite·flask
龙腾AI白云6 天前
数字孪生、具身智能、世界模型三者交叉
数据库·人工智能·机器学习·flask·pygame
hhb_6187 天前
Flask+SQLite实现用户管理接口
python·sqlite·flask
QQ14220784498 天前
基于 Flask 的「自动任务控制台」设计与踩坑实录
后端·python·flask
深圳市尚想信息技术有限公司9 天前
TM52F1376海速芯HITENX Flash-8位MCU单片机,多通道ADC + 段码显示一体化主控芯片
单片机·嵌入式硬件·mcu·flask·芯片·控制器
高级程序源10 天前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计
高级程序源10 天前
SSM仓储管理系统31582-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·flask·课程设计
高级程序源10 天前
springboot本地生活服务平台33399-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·小程序·flask·课程设计