main.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. from enum import Enum
  2. from typing import Optional
  3. from pydantic import BaseModel
  4. from fastapi import FastAPI, Query, UploadFile, File
  5. import dataset,json
  6. from fastapi import FastAPI
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from fastapi.staticfiles import StaticFiles
  9. import time
  10. from datetime import datetime
  11. from PIL import Image
  12. import io
  13. from typing import List
  14. import threading
  15. app = FastAPI()
  16. origins = [
  17. "http://172.105.205.52",
  18. "http://172.105.205.52:8000",
  19. ]
  20. app.add_middleware(
  21. CORSMiddleware,
  22. allow_origins=['*'],
  23. allow_credentials=True,
  24. allow_methods=["*"],
  25. allow_headers=["*"],
  26. )
  27. serverADDR = 'welife.asia:8002/'
  28. cover_img_dir = 'static/cover_img/'
  29. app.mount("/static/cover_img", StaticFiles(directory="static/cover_img"), name="static/cover_img")
  30. ##########TAG CRUD################TAG CRUD##################TAG CRUD###########TAG CRUD##################
  31. class Tag(BaseModel):
  32. id: int
  33. name: str
  34. @app.get("/tags")
  35. async def get_tags():
  36. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  37. statement = 'SELECT id,name FROM tag'
  38. tags = []
  39. for row in db.query(statement):
  40. tags.append({'id':row['id'],'name':row['name']})
  41. return tags
  42. @app.post("/create_tag")
  43. async def create_tags(tag:Tag):
  44. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  45. tag_table = db['tag']
  46. pk = tag_table.insert({'name':tag.name})
  47. tag.id = pk
  48. return tag
  49. @app.get("/del_tag/{tag_id}")
  50. async def delete_tags(tag_id:int):
  51. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  52. sqls = 'DELETE FROM tag WHERE id = '+str(tag_id)
  53. db.query(sqls)
  54. sqls = 'DELETE FROM course_tag WHERE tag_id = '+str(tag_id)
  55. db.query(sqls)
  56. return 'success'
  57. @app.post("/update_tag/")
  58. async def update_tags(tag_id,tag:Tag):
  59. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  60. sqls = 'UPDATE tag\
  61. SET name="'+tag.name+'"\
  62. WHERE id='+tag_id+';'
  63. db.query(sqls)
  64. tag.id=tag_id
  65. return tag
  66. @app.get("/tags/{tag_id}")
  67. async def get_tags(tag_id):
  68. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  69. statement = 'SELECT id,name FROM tag where id = '+tag_id
  70. for row in db.query(statement):
  71. result = {'id':row['id'],'name':row['name']}
  72. return result
  73. ###########COURSE CRUD###########COURSE CRUD###########COURSE CRUD###########COURSE CRUD###########
  74. class Course(BaseModel):
  75. id: int
  76. title: str
  77. profile: str
  78. url: str #course website location url
  79. cover_img: str #img url form
  80. teacher_name: str
  81. teacher_img: str #teacher user image url form
  82. price: int
  83. price_discount: int
  84. hours: float
  85. units: int
  86. @app.post("/get_courses_by_cid")
  87. async def get_courses(cids:List[int]):
  88. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  89. cid_str = '('
  90. for t in cids:
  91. cid_str = cid_str + str(t) +','
  92. cid_str = cid_str[:-1]+')'
  93. courses = []
  94. statement = 'SELECT * FROM course WHERE id IN'+cid_str
  95. for row in db.query(statement):
  96. courses.append({'id':row['id'],'title':row['title'],'url':row['url']
  97. ,'teacher_name':['teacher_name'],'price':row['price'],'price_discount':row['price_discount'],'profile':row['profile']
  98. ,'cover_img':'https://'+serverADDR + row['cover_img'],'hours':row['hours'],'units':row['units']})
  99. return courses
  100. @app.post("/get_courses")
  101. async def get_courses(tags:List[int]):
  102. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  103. tag_str = '('
  104. for t in tags:
  105. tag_str = tag_str + str(t) +','
  106. tag_str = tag_str[:-1]+')'
  107. courses = []
  108. statement = 'SELECT * FROM course_tag '\
  109. 'INNER JOIN course on course_tag.course_id=course.id '\
  110. 'INNER JOIN tag on course_tag.tag_id = tag.id '\
  111. 'WHERE tag.id IN'+tag_str+' ORDER BY clicks DESC'
  112. for row in db.query(statement):
  113. courses.append({'id':row['course_id'],'title':row['title'],'url':row['url']
  114. ,'teacher_name':['teacher_name'],'price':row['price'],'price_discount':row['price_discount'],'profile':row['profile']
  115. ,'cover_img':'https://'+serverADDR + row['cover_img'],'hours':row['hours'],'units':row['units']})
  116. return courses
  117. @app.post("/create_courses")
  118. async def create_courses(tags: list,course:Course):
  119. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  120. #add to course table
  121. course_table = db['course']
  122. pk = course_table.insert({'title':course.title,'profile':course.profile,'url':course.url,'cover_img':course.cover_img,'teacher_name':course.teacher_name,
  123. 'price':course.price,'price_discount':course.price_discount,'hours':course.hours,'units':course.units})
  124. course.id = pk
  125. course_tag_table = db['course_tag']
  126. for tag in tags:
  127. course_tag_table.insert({'course_id':course.id,'tag_id':tag})
  128. x = threading.Thread(target=to_sheet)
  129. x.start()
  130. return {'msg':'新增成功'}
  131. @app.get("/del_course/{course_id}")
  132. async def delete_course(course_id:int):
  133. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  134. sqls = 'DELETE FROM course WHERE id = '+str(course_id)
  135. db.query(sqls)
  136. sqls = 'DELETE FROM course_tag WHERE course_id = '+str(course_id)
  137. db.query(sqls)
  138. return {'msg':'新增成功'}
  139. @app.post("/upload_cover_img/")
  140. async def create_upload_file(file: UploadFile = File(...)):
  141. img_name = str(time.time()).replace('.','')
  142. contents = await file.read()
  143. image = Image.open(io.BytesIO(contents))
  144. image= image.convert("RGB")
  145. image.save(cover_img_dir+img_name+'.jpg')
  146. return {"msg": serverADDR+cover_img_dir+img_name+'.jpg'}
  147. async def to_sheet():
  148. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  149. statement = 'SELECT * FROM course ORDER BY clicks DESC'
  150. df = pd.DataFrame()
  151. for row in db.query(statement):
  152. date_format = "%Y-%M-%d %H:%M:%S"
  153. df = df.append({'serial id':row['id'],'標題':['Title'],'介紹':row['profile'],'url':row['url']
  154. ,'圖片':row['cover_img'],'價錢':row['price'],"折扣後價錢":row['price_discount'],'時數':row['hours']
  155. ,'單元數':row['units']}, ignore_index=True)
  156. save_sheet(df,'deco_request','sheet1')
  157. def save_sheet(df,filename,tabname,startpos='A1'):
  158. scope = ['https://spreadsheets.google.com/feeds',
  159. 'https://www.googleapis.com/auth/drive']
  160. credentials = ServiceAccountCredentials.from_json_keyfile_name('spread2.json', scope)
  161. gc = gspread.authorize(credentials)
  162. spread = Spread(filename,creds=credentials)
  163. spread.df_to_sheet(df, index=False, sheet=tabname, start=startpos, replace=False)