Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python restful

作者:此岸蝶恋花   发布日期:2026-07-31   浏览:115

from flask import Flask, request, jsonify

app = Flask(__name__)

# 定义一个简单的 RESTful API 资源
class Product:
    def __init__(self, id, name, price):
        self.id = id
        self.name = name
        self.price = price

# 模拟数据库
products = [
    Product(1, "Laptop", 999),
    Product(2, "Mouse", 10),
    Product(3, "Keyboard", 50)
]

# 获取所有产品
@app.route('/products', methods=['GET'])
def get_products():
    product_list = [{'id': p.id, 'name': p.name, 'price': p.price} for p in products]
    return jsonify(product_list)

# 获取单个产品
@app.route('/products/<int:product_id>', methods=['GET'])
def get_product(product_id):
    product = next((p for p in products if p.id == product_id), None)
    if product:
        return jsonify({'id': product.id, 'name': product.name, 'price': product.price})
    else:
        return jsonify({'message': 'Product not found'}), 404

# 添加新产品
@app.route('/products', methods=['POST'])
def add_product():
    data = request.get_json()
    new_product = Product(id=data['id'], name=data['name'], price=data['price'])
    products.append(new_product)
    return jsonify({'message': 'Product added successfully'}), 201

# 更新产品信息
@app.route('/products/<int:product_id>', methods=['PUT'])
def update_product(product_id):
    data = request.get_json()
    product = next((p for p in products if p.id == product_id), None)
    if product:
        product.name = data.get('name', product.name)
        product.price = data.get('price', product.price)
        return jsonify({'message': 'Product updated successfully'})
    else:
        return jsonify({'message': 'Product not found'}), 404

# 删除产品
@app.route('/products/<int:product_id>', methods=['DELETE'])
def delete_product(product_id):
    global products
    products = [p for p in products if p.id != product_id]
    return jsonify({'message': 'Product deleted successfully'})

if __name__ == '__main__':
    app.run(debug=True)

解释说明:

  1. 导入必要的模块

    • Flask:用于创建 Web 应用程序。
    • requestjsonify:用于处理 HTTP 请求和返回 JSON 响应。
  2. 定义产品类

    • Product 类用于表示产品,包含 idnameprice 属性。
  3. 模拟数据库

    • 使用一个列表 products 来存储多个 Product 对象,模拟数据库中的数据。
  4. 定义路由和方法

    • /products (GET):获取所有产品的列表。
    • /products/<int:product_id> (GET):根据 ID 获取单个产品。
    • /products (POST):添加新产品。
    • /products/<int:product_id> (PUT):更新指定 ID 的产品信息。
    • /products/<int:product_id> (DELETE):删除指定 ID 的产品。
  5. 运行应用

    • 使用 app.run(debug=True) 启动 Flask 应用,并开启调试模式。

上一篇:request python

下一篇:python filenotfounderror

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python windows下文件路径写法

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站