Skip to content

Instantly share code, notes, and snippets.

@ciscoinfo
Last active September 4, 2021 15:04
Show Gist options
  • Select an option

  • Save ciscoinfo/98320d643b28a14c307943ebf0ccab59 to your computer and use it in GitHub Desktop.

Select an option

Save ciscoinfo/98320d643b28a14c307943ebf0ccab59 to your computer and use it in GitHub Desktop.
files for my article "API REST avec Flask"
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
# Load the configuration from the instance folder
app.config.from_pyfile('config.py', silent=True)
# Define the database object which is imported
db = SQLAlchemy(app)
# Initialize Marshmallow
ma = Marshmallow(app)
import my_app.models
import my_app.views
from . import db, ma
from dataclasses import dataclass
@dataclass
class Product(db.Model):
__tablename__ = "product"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
description = db.Column(db.String(100))
price = db.Column(db.Float)
quantity = db.Column(db.Integer)
def __repr__(self):
return f'<Product {self.name}>'
def to_dict(self):
return {column.name: getattr(self, column.name) for column in self.__table__.columns}
# class ProductSchema(ma.Schema):
# class Meta:
# fields = ('name', 'description', 'price', 'quantity')
class ProductSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Product
load_instance = True
sqla_session = db.session
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
from my_app import app
if __name__ == "__main__":
app.run()
import requests
from pprint import pprint
BASE_URL = "http://127.0.0.1:5000/"
def get_one_marshmallow():
print("\n------- get_one_marshmallow -------\n")
response = requests.get(BASE_URL + "/get/1")
pprint(response.json())
def get_many_marshmallow():
print("\n------- get_many_marshmallow -------\n")
response = requests.get(BASE_URL + "/getall/1")
pprint(response.json())
def get_one_todict():
print("\n------- get_one_todict -------\n")
response = requests.get(BASE_URL + "/get/2")
pprint(response.json())
def get_many_todict():
print("\n------- get_many_todict -------\n")
response = requests.get(BASE_URL + "/getall/2")
pprint(response.json())
def get_one_flaskrest():
print("\n------- get_one_flaskrest -------\n")
response = requests.get(BASE_URL + "/get/3")
pprint(response.json())
def get_many_flaskrest():
print("\n------- get_many_flaskrest -------\n")
response = requests.get(BASE_URL + "/getall/3")
pprint(response.json())
if __name__ == "__main__":
get_one_marshmallow()
input()
get_many_marshmallow()
input()
get_one_todict()
input()
get_many_todict()
input()
get_one_flaskrest()
input()
get_many_flaskrest()
from my_app import app
from flask import jsonify
from my_app.models import *
# only to test flask_restful
from flask_restful import fields, marshal_with, Resource, Api
api = Api(app)
product_1 = Product(
name="baguette",
description="La baguette de tradition",
price=1.15,
quantity=5
)
product_2 = Product(
name="jambon",
description="de Parme evidemment et sans nitrites",
price=150.5,
quantity=10
)
products = [product_1, product_2]
product_fields = {
'name': fields.String,
'description': fields.String,
'price': fields.String,
}
# to test the server/routing
@app.route("/", methods=["GET"])
def get():
return jsonify({"hello": "world"})
# ------------------ Marshmallow
# one
@app.route("/get/1", methods=["GET"])
def get_1():
return product_schema.jsonify(product_1)
# many
@app.route("/getall/1", methods=["GET"])
def getall_1():
return products_schema.jsonify(products)
# ------------------ to_dict
# one
@app.route("/get/2", methods=["GET"])
def get_2():
return jsonify(product_1.to_dict())
# many
@app.route("/getall/2", methods=["GET"])
def getall_2():
all_product_dict = [product.to_dict() for product in products]
return jsonify(all_product_dict)
# ------------------ flask_restful
# one
class ProductsGetOne(Resource):
@marshal_with(product_fields)
def get(self):
return product_1
# many
class ProductsGetMany(Resource):
@marshal_with(product_fields)
def get(self):
return products
api.add_resource(ProductsGetOne, "/get/3")
api.add_resource(ProductsGetMany, "/getall/3")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment