-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
90 lines (71 loc) · 1.94 KB
/
main.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
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from redis_om import get_redis_connection, HashModel
import requests
from fastapi.background import BackgroundTasks
import time
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:3000'],
allow_methods=['*'],
allow_headers=['*']
)
redis = get_redis_connection(
host='redis-18285.c300.eu-central-1-1.ec2.cloud.redislabs.com',
port=18285,
password='IsQ2cnDaAdVoPXmfKbbj6vt31xlWvYFB',
decode_responses=True
)
class ProductOrder(HashModel):
product_id: str
quantity: int
class Meta:
database = redis
class Order(HashModel):
product_id: str
price: float
fee: float
total: float
quantity: int
status: str
class Meta:
database = redis
@app.post('/orders')
def create(productOrder: ProductOrder, background_tasks: BackgroundTasks):
req = requests.get(f'http://localhost:8000/product/{productOrder.product_id}')
product = req.json()
fee = product['price'] * 0.2
order = Order(
product_id = productOrder.product_id,
price = product['price'],
fee = fee,
total = product['price'] + fee,
quantity = productOrder.quantity,
status = 'pending'
)
order.save()
background_tasks.add_task(order_complete, order)
return order
@app.get('/orders/{pk}')
def get(pk: str):
return format(pk)
def format(pk: str):
order = Order.get(pk)
return {
'id': order.pk,
'product_id': order.product_id,
'fee': order.fee,
'total': order.total,
'quantity': order.quantity,
'status': order.status
}
@app.get('/orders')
def all():
orders = Order.all_pks()
return [format(pk) for pk in orders]
def order_complete(order: Order):
time.sleep(5)
order.status = 'completed'
order.save()
redis.xadd(name='order-completed', fields=order.dict())