main.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from enum import Enum
  2. from typing import Optional
  3. from fastapi import FastAPI, Query
  4. import dataset,json
  5. app = FastAPI()
  6. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/cmm_test?charset=utf8mb4')
  7. @app.get("/tags")
  8. async def get_tags():
  9. tag_dict = {}
  10. table = db.load_table('tag_table')
  11. statement = 'SELECT id,name FROM tag_table'
  12. for row in db.query(statement):
  13. tag_dict[row['id']]=row['name']
  14. json_dump = json.dumps(tag_dict, ensure_ascii=False)
  15. return json_dump
  16. @app.get("/courses")
  17. async def get_courses(tag_string):
  18. course_dict = {}
  19. statement = 'SELECT course_id from course_tag where tag_id IN'+tag_string
  20. course_id_string = '('
  21. for row in db.query(statement):
  22. course_id_string = course_id_string + str(row['course_id'])+","
  23. course_id_string=course_id_string[:-1]
  24. course_id_string = course_id_string+')'
  25. statement = 'SELECT id,name from course_table where id IN'+course_id_string
  26. for row in db.query(statement):
  27. course_dict[row['id']]=row['name']
  28. json_dump = json.dumps(course_dict, ensure_ascii=False)
  29. return json_dump