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 视图函数
相关推荐
wxin_VXbishe3 小时前
springboot旅游小程序-计算机毕业设计源码76696
java·spring boot·python·spring·django·sqlite·flask
发条宇12 小时前
1267, “Illegal mix of collations (latin1_swedish_ci,IMPLICIT
django·flask
魔尔助理顾问1 天前
Flask如何读取配置信息
python·flask·bootstrap
子燕若水2 天前
Flask 调试的时候进入main函数两次
后端·python·flask
ZHOU_WUYI3 天前
Flask Docker Demo 项目指南
python·docker·flask
BuLingLings3 天前
vue3+flask+sqlite前后端项目实战
python·sqlite·flask
wxl7812274 天前
基于flask+pandas+csv的报表实现
python·flask·pandas
西红柿土豆丶4 天前
基于Flask、Bootstrap及深度学习的水库智能监测分析平台
人工智能·python·深度学习·flask·bootstrap
带娃的IT创业者5 天前
《AI大模型应知应会100篇》第58篇:Semantic Kernel:微软的大模型应用框架
人工智能·microsoft·flask
未名编程5 天前
【Flask开发踩坑实录】pip 安装报错:“No matching distribution found” 的根本原因及解决方案!
python·flask·pip