【PythonWeb开发】Flask请求中传递参数到视图函数的方法总结。

在Flask中,传入参数主要有两种常见的方式,即通过GET请求和POST请求。

一、GET请求传递参数

(1)URL路径中获取

这种类型的参数通常称为路径参数或路由参数,它们是URL路径的一部分,通过尖括号**<parameter_name>**定义在路由规则中。

python 复制代码
@app.route('/user/<username>/post/<int:post_id>')
def show_post(username, post_id):
    # 这里可以直接通过函数参数获取路径中的变量
    return f"Username: {username}, Post ID: {post_id}"

如果你需要更复杂的路径参数处理,或者在处理请求之后动态获取路径参数,可以使用**request.view_args**,它是一个字典,包含了所有通过URL路径传递的参数。

python 复制代码
@app.route('/some/route/<path:custom_path>')
def handle_custom_path(custom_path):
    # 除了直接作为参数,你也可以通过view_args获取
    print(request.view_args)  # 输出: {'custom_path': 'the/path/from/url'}
    return f"The custom path is: {custom_path}"

(2)请求参数中获取

GET请求通常将参数附加在URL后面,通过问号**?** 分隔URL和参数,多个参数之间使用**&**连接。这种方式适用于请求不会改变服务器上的资源,且参数长度有限制(因为参数直接出现在URL中)。

http://example.com/api/data?key1=value1&key2=value2

使用**request.args**字典对象来获取GET参数。有三种使用方法:

  • get方法,如果该参数不存在,则可以提供一个默认值,避免抛出异常。
  • get_list方法,当一个参数可能在同一请求中有多个值时,返回一个包含所有值的列表。
  • 中括号,这种方式与普通字典访问类似,取不到会抛出异常。
python 复制代码
from flask import request

@app.route('/api/data')
def get_data():
    key1 = request.args.get('key1')  # 获取key1的值,如果不存在则返回None
    key2 = request.args['key2']      # 直接通过键访问,如果不存在会抛出KeyError
    key3 = request.args.get_list('key3')  # 取出存在同名key的所有值
    return f"Key1: {key1}, Key2: {key2}, Key3: {key3}"

二、POST请求传递参数

POST请求通常用于提交表单或发送可能改变服务器状态的数据。参数不在URL中显示,而是放在请求体中。POST请求可以承载更大的数据量,且对数据类型的支持更灵活。

POST请求有两种常见的编码格式:

  • application/x-www-form-urlencoded:表单数据,类似于GET请求的查询字符串格式。
  • multipart/form-data:用于文件上传,也可以包含普通字段。

(1)上传表单数据

对于表单使用**request.form**

  • 中括号方式
  • get方法

(2)上传JSON数据

对于JSON格式的数据(当Content-Type为**application/json** 时),使用**request.get_json()**

python 复制代码
from flask import request, jsonify

@app.route('/api/data', methods=['POST'])
def post_data():
    if request.is_json:  # is_json属性可以判断返回的是否是json数据
        data = request.get_json()          # 获取JSON格式的POST数据
        key1 = data.get('key1')           # 如果数据是JSON对象,则这样获取
    else:
        key1 = request.form.get('key1')    # 获取表单形式的POST数据
    return jsonify({"received_key1": key1})

(3)上传视频数据

使用**request.files**来取出上传的文件。

python 复制代码
@app.route('/upload_video', methods=['POST'])
def upload_video():
    video_file = request.files['video']  # 假设表单中文件字段名为'video'
    
    if video_file.filename == '':
        return "No video selected", 400
    
    # 可以在这里添加额外的验证,比如检查文件大小、视频格式等
    if video_file and allowed_file(video_file.filename, video_extensions):  # 假设allowed_file检查文件类型和大小
        filename = secure_filename(video_file.filename)
        video_file.save(os.path.join(app.config['VIDEO_UPLOAD_FOLDER'], filename))
        return "Video uploaded successfully"
    else:
        return "Invalid video file or other error", 400

(4)上传图片数据

使用**request.files**来取出上传的文件。上传图片数据的过程与上述视频上传相似,只是可能在验证阶段会特别检查图片的格式。

python 复制代码
def allowed_file(filename):
    """检查文件扩展名是否允许上传"""
    ALLOWED_EXTENSIONS = { 'jpg', 'jpeg', 'png', 'gif'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
python 复制代码
@app.route('/upload_image', methods=['POST'])
def upload_image():
    image_file = request.files['image']  # 假设表单中文件字段名为'image'
    
    if image_file.filename == '':
        return "No image selected", 400
    
    # 验证图片格式等
    if image_file and allowed_file(image_file.filename, image_extensions):  # 使用适合的图片扩展名集合
        filename = secure_filename(image_file.filename)
        image_file.save(os.path.join(app.config['IMAGE_UPLOAD_FOLDER'], filename))
        return "Image uploaded successfully"
    else:
        return "Invalid image file or other error", 400
相关推荐
一眼万里*e3 小时前
fish-speech语音大模型本地部署
python·flask·大模型
叫我DPT1 天前
Flask-3
python·flask
dotdotyy1 天前
调用智谱AI,面试小助手Flask简单示例
人工智能·面试·flask
去你的鸟命2 天前
YOLOv8 Flask整合问题
python·yolo·flask
叫我DPT2 天前
Flask-1
后端·python·flask
爱技术的小伙子2 天前
【30天玩转python】Web开发(Flask/Django)
前端·python·flask
投图匠2 天前
如何使用Flask框架创建一个类似OpenAI的REST API接口
后端·python·flask
Azure DevOps3 天前
Azure DevOps Server:不能指派新增的用户
运维·microsoft·flask·azure·devops
0wioiw03 天前
Flask+微信小程序实现Login+Profile
python·微信小程序·flask
zybsjn3 天前
使用 Nginx 和 Gunicorn 部署 Flask 项目详细教程
nginx·flask·gunicorn