-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtea.py
executable file
·94 lines (79 loc) · 2.74 KB
/
tea.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
94
from monk import Monk
from model import Tea
from monk_sqlalchemy import conn
import asyncio
import random
from urllib.parse import unquote
import uvloop
app = Monk()
sql_config = dict(host='127.0.0.1',
port=3306,
user='root',
password='root',
db='take_tea',
charset='utf8',
autocommit=True,
maxsize=10,
minsize=1,
)
loop = asyncio.get_event_loop()
loop.run_until_complete(conn.connection(loop=loop, **sql_config))
@app.route('/', methods=['GET'])
async def index(request):
resp = await app.file(file="index.html")
return resp
@app.route("/tea", methods=['GET', 'POST'])
async def get_tea(request):
if request.method == 'GET':
tea_id = request.args.get('id')
if tea_id is None:
teas = await Tea.all()
return Monk.jsonfy(result=[t.to_json() for t in teas])
tea = await Tea.find_by(id=tea_id)
if tea is None:
return Monk.jsonfy(result=[])
else:
return Monk.jsonfy(result=[tea[0].to_json()])
if request.method == 'POST':
form = request.form
try:
d = dict(
name=form.get('name'),
taste=form.get('taste'),
function=form.get('function'),
age_up=int(form.get('age_up')),
age_down=int(form.get('age_down')),
taste_q=form.get('taste_q'),
function_q=form.get('function_q'),
image_url=form.get('image_url')
)
t = Tea(**d)
await t.save()
except Exception:
return app.jsonfy(status="fail")
return app.jsonfy(status="success")
@app.route('/tea_answer', methods=['GET'])
async def get_answer(request):
args = request.args
age = int(args.get('age'))
taste_q = args.get('taste')
function_q = args.get('function')
teas = await Tea.all()
ans = [t for t in teas if t.age_down < age < t.age_up]
if not ans:
return app.jsonfy(result=[], reason="Not match age")
if taste_q is not None:
ans = [t for t in ans if t.taste_q == taste_q]
if not ans:
return app.jsonfy(result=[], reason="Not match taste")
if function_q is not None:
ans = [t for t in ans if t.function_q == function_q]
if not ans:
return app.jsonfy(result=[], reason="Not match taste")
return app.jsonfy(result=[t.to_json() for t in ans], reason='')
@app.route("/get_daily_tea")
async def get_random_tea(request):
teas = await Tea.all()
tea = random.choice(teas)
return app.jsonfy(result=[tea.to_json()], reason='')
app.run(host='0.0.0.0', port=10086)