-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
93 lines (68 loc) · 2.36 KB
/
app.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from flask import Flask, request
import flask.scaffold
flask.helpers._endpoint_from_view_func = flask.scaffold._endpoint_from_view_func
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cart.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)
api = Api(app)
class cart(db.Model):
id = db.Column(db.Integer, primary_key=True)
img = db.Column(db.String())
name = db.Column(db.String())
price = db.Column(db.Integer())
count = db.Column(db.Integer())
def __init__(self, img,name,price,count):
self.img = img
self.name = name
self.price = price
self.count = count
def __repr__(self):
return f"{self.name}:{self.price}"
class cartSchema(ma.Schema):
class Meta:
fields = ("id", "img", "name", "price", "count")
cart_schema = cartSchema()
carts_schema = cartSchema(many=True)
class cartListResource(Resource):
def get(self):
carts = cart.query.all()
return carts_schema.dump(carts)
def post(self):
new_cart = cart(
img=request.json['img'],
name=request.json['name'],
price=request.json['price'],
count=request.json['count'],
)
db.session.add(new_cart)
db.session.commit()
return cart_schema.dump(new_cart)
class cartResource(Resource):
def get(self, cart_id):
carts = cart.query.get_or_404(cart_id)
return cart_schema.dump(carts)
def patch(self, cart_id):
carts = cart.query.get_or_404(cart_id)
if 'img' in request.json:
carts.img = request.json['img']
if 'name' in request.json:
carts.name = request.json['name']
if 'price' in request.json:
carts.price = request.json['price']
if 'count' in request.json:
carts.count = request.json['count']
db.session.commit()
return cart_schema.dump(carts)
def delete(self, cart_id):
carts = cart.query.get_or_404(cart_id)
db.session.delete(carts)
db.session.commit()
return 'Data deleted Successfully', 204
api.add_resource(cartListResource, '/carts')
api.add_resource(cartResource, '/carts/<int:cart_id>')
if __name__ == '__main__':
app.run(debug=True)