我试图根据这个项目建模一些代码。 https://auth0.com/blog/developing-restful-apis-with-python-and-flask/#bootstrapping-flask
这是我在python中的第一个REST API。这是代码。
from marshmallow import Schema, fields
class Product():
def __init__(self, ident, name, description, category):
self.ident = ident
self.name = name
self.description = description
self.category = category
def __repr__(self):
return '<Expense(name={self.description!r})>'.format(self=self)
class ProductSchema(Schema):
ident = fields.Str()
name = fields.Str()
category = fields.Str()
description = fields.Str()
index.py
from flask import Flask, jsonify, request
from server.model.product import Product, ProductSchema
app = Flask(__name__)
products=[Product('a','b','c','d')]
@app.route("/")
def hello_world():
return "Hello, World!"
@app.route("/products", methods=['POST'])
def add_product():
product = ProductSchema().load(request.get_json())
products.append(product.data)
return "", 204
@app.route("/products")
def get_products():
schema = ProductSchema(many=True)
return jsonify(products)
if __name__ == "__main__":
app.run()
但是,当我尝试对/ products执行http GET请求时,我在说明中得到了错误。
答案 0 :(得分:1)
你有两个问题:
products
类型为list,jsonify不是结果列表,因为它不是安全性。Product()
对象是类,你需要返回dict。使用以下代码更改代码:
import json
@app.route("/products")
def get_products():
schema = ProductSchema(many=True)
return json.dumps([p.__dict__ for p in prodacts])
或
from flask import Response
import json
@app.route("/products")
def get_products():
schema = ProductSchema(many=True)
return Response(json.dumps([p.__dict__ for p in prodacts]), mimetype='application/json')