-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
59 lines (45 loc) · 1.36 KB
/
app.py
File metadata and controls
59 lines (45 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
#Init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init Database
# global db
db = SQLAlchemy(app)
# Init marshmallow
ma = Marshmallow(app)
# Asset class
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), unique=True)
def __init__(self, name):
self.name = name
# Product Schema
class ProductSchema(ma.Schema):
class Meta:
fields = ('id', 'name')
# init schema
product_schema = ProductSchema(strict=True)
products_schema = ProductSchema(many=True, strict=True)
# Create product
@app.route('/product', methods=['POST'])
def add_product():
name = request.json['name']
new_product = Product(name)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
# Get all products
@app.route('/product', methods=['GET'])
def get_products():
all_products = Product.query.all()
result = products_schema.dump(all_products)
return jsonify(result.data)
#Run server
if __name__ == "__main__":
app.run(debug=True)