-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
81 lines (61 loc) · 2.51 KB
/
api.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
# -*- coding:utf-8 -*-
from flask import Flask
from flask_cors import CORS
from flask_restful import Resource, Api, reqparse
from model.product import Product
from model.order import Order
from model.orderhasproduct import OrderHasProduct
from model.db_init import db_init, db
from config import config
app = Flask(__name__, static_url_path='/static')
CORS(app)
app.config.from_object(config['default'])
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
db_init(app)
api = Api(app)
class ProductEndpoint(Resource):
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('pid', type=int, help='product id')
args = parser.parse_args()
pid = args['pid']
if not pid:
products = Product.query.all()
else:
products = Product.query.filter_by(id=pid)
products = [p.data for p in products]
print(products)
return products
class OrderEndpoint(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, help='name')
parser.add_argument('phone', type=str, help='phone')
parser.add_argument('address', type=str, help='address')
parser.add_argument('email', type=str, help='email')
parser.add_argument('bankAccount', type=str, help='bank account')
parser.add_argument('itemList', type=list, help='item list', location="json")
args = parser.parse_args()
print(args)
with app.app_context():
order = Order(args['name'], args['address'], args['phone'], args['email'], args['bankAccount'])
order.save_to_db()
for pid in args['itemList']:
ohp = OrderHasProduct(order.data['id'], pid, 1)
ohp.save_to_db()
return order.id
with app.app_context():
#db.drop_all()
db.create_all()
products = Product.query.all()
if len(products) == 0:
img_url = 'https://cf-assets2.tenlong.com.tw/products/images/000/130/414/original/9789864776283.jpg?1551941737'
p1 = Product(u'萌貓投資偵探所', 100, 264, u'商周出版', u'繁體中文', img_url, '9789864776283')
p2 = Product(u'萌貓投資偵探所2', 100, 264, u'商周出版', u'繁體中文', img_url, '9789864776283')
p1.save_to_db()
p2.save_to_db()
#print(Product.query.all())
api.add_resource(ProductEndpoint,'/api/v1/product')
api.add_resource(OrderEndpoint,'/api/v1/order')
if __name__ == '__main__':
app.run(debug = True)