main.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. import pandas as pd
  16. from gspread_pandas import Spread, Client
  17. from oauth2client.service_account import ServiceAccountCredentials
  18. import gspread
  19. from first import first
  20. app = FastAPI()
  21. origins = [
  22. "http://172.105.205.52",
  23. "http://172.105.205.52:8000",
  24. ]
  25. app.add_middleware(
  26. CORSMiddleware,
  27. allow_origins=['*'],
  28. allow_credentials=True,
  29. allow_methods=["*"],
  30. allow_headers=["*"],
  31. )
  32. serverADDR = 'welife.asia:8002/'
  33. cover_img_dir = 'static/cover_img/'
  34. app.mount("/static/cover_img", StaticFiles(directory="static/cover_img"), name="static/cover_img")
  35. ##########TAG CRUD################TAG CRUD##################TAG CRUD###########TAG CRUD##################
  36. class Tag(BaseModel):
  37. id: int
  38. name: str
  39. @app.get("/tags")
  40. async def get_tags():
  41. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  42. statement = 'SELECT id,name FROM tag'
  43. tags = []
  44. for row in db.query(statement):
  45. tags.append({'id':row['id'],'name':row['name']})
  46. return tags
  47. @app.post("/create_tag")
  48. async def create_tags(tag:Tag):
  49. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  50. tag_table = db['tag']
  51. pk = tag_table.insert({'name':tag.name})
  52. tag.id = pk
  53. return tag
  54. @app.get("/del_tag/{tag_id}")
  55. async def delete_tags(tag_id:int):
  56. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  57. sqls = 'DELETE FROM tag WHERE id = '+str(tag_id)
  58. db.query(sqls)
  59. sqls = 'DELETE FROM course_tag WHERE tag_id = '+str(tag_id)
  60. db.query(sqls)
  61. return 'success'
  62. @app.post("/update_tag/")
  63. async def update_tags(tag_id,tag:Tag):
  64. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  65. sqls = 'UPDATE tag\
  66. SET name="'+tag.name+'"\
  67. WHERE id='+tag_id+';'
  68. db.query(sqls)
  69. tag.id=tag_id
  70. return tag
  71. @app.get("/tags/{tag_id}")
  72. async def get_tags(tag_id):
  73. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  74. statement = 'SELECT id,name FROM tag where id = '+tag_id
  75. for row in db.query(statement):
  76. result = {'id':row['id'],'name':row['name']}
  77. return result
  78. ###########COURSE CRUD###########COURSE CRUD###########COURSE CRUD###########COURSE CRUD###########
  79. class Course(BaseModel):
  80. id: int
  81. title: str
  82. profile: str
  83. url: str #course website location url
  84. cover_img: str #img url form
  85. teacher_name: str
  86. teacher_img: str #teacher user image url form
  87. price: int
  88. price_discount: int
  89. hours: float
  90. units: int
  91. class Email_tag(BaseModel):
  92. email:str
  93. tags:str
  94. @app.post("/get_courses_by_cid")
  95. async def get_courses(cids:List[int]):
  96. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  97. cid_str = '('
  98. for t in cids:
  99. cid_str = cid_str + str(t) +','
  100. cid_str = cid_str[:-1]+')'
  101. courses = []
  102. statement = 'SELECT * FROM course WHERE id IN'+cid_str
  103. for row in db.query(statement):
  104. courses.append({'id':row['id'],'title':row['title'],'url':row['url']
  105. ,'teacher_name':['teacher_name'],'price':row['price'],'price_discount':row['price_discount'],'profile':row['profile']
  106. ,'cover_img':'https://'+serverADDR + row['cover_img'],'hours':row['hours'],'units':row['units'],'clicks':row['clicks']})
  107. return courses
  108. @app.post("/get_courses")
  109. async def get_courses(tags:List[int]):
  110. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  111. tag_str = '('
  112. for t in tags:
  113. tag_str = tag_str + str(t) +','
  114. tag_str = tag_str[:-1]+')'
  115. courses = []
  116. statement = 'SELECT * FROM course_tag '\
  117. 'INNER JOIN course on course_tag.course_id=course.id '\
  118. 'INNER JOIN tag on course_tag.tag_id = tag.id '\
  119. 'WHERE tag.id IN'+tag_str+' ORDER BY clicks DESC'
  120. for row in db.query(statement):
  121. courses.append({'id':row['course_id'],'title':row['title'],'url':row['url']
  122. ,'teacher_name':['teacher_name'],'price':row['price'],'price_discount':row['price_discount'],'profile':row['profile']
  123. ,'cover_img':'https://'+serverADDR + row['cover_img'],'hours':row['hours'],'units':row['units'],'clicks':row['clicks']})
  124. return courses
  125. @app.post("/create_courses")
  126. async def create_courses(tags: list,course:Course):
  127. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  128. #add to course table
  129. course_table = db['course']
  130. pk = course_table.insert({'title':course.title,'profile':course.profile,'url':course.url,'cover_img':course.cover_img,'teacher_name':course.teacher_name,
  131. 'price':course.price,'price_discount':course.price_discount,'hours':course.hours,'units':course.units})
  132. course.id = pk
  133. course_tag_table = db['course_tag']
  134. for tag in tags:
  135. course_tag_table.insert({'course_id':course.id,'tag_id':tag})
  136. return {'msg':'新增成功'}
  137. @app.get("/del_course/{course_id}")
  138. async def delete_course(course_id:int):
  139. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  140. sqls = 'DELETE FROM course WHERE id = '+str(course_id)
  141. db.query(sqls)
  142. sqls = 'DELETE FROM course_tag WHERE course_id = '+str(course_id)
  143. db.query(sqls)
  144. return {'msg':'新增成功'}
  145. @app.post("/update_course")
  146. async def update_course(cid:int,tags:List[int]):
  147. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  148. sqls = 'DELETE FROM course_tag WHERE course_id = '+str(cid)
  149. db.query(sqls)
  150. course_tag_table = db['course_tag']
  151. for tag in tags:
  152. course_tag_table.insert({'course_id':cid,'tag_id':tag})
  153. return {'msg':'ok'}
  154. @app.get("/course_click/{course_id}")
  155. async def delete_course(course_id:int):
  156. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  157. sqls = 'UPDATE course\
  158. SET clicks=clicks+1\
  159. WHERE id='+str(course_id)+';'
  160. db.query(sqls)
  161. return {'msg':'ok'}
  162. @app.post("/upload_cover_img/")
  163. async def create_upload_file(file: UploadFile = File(...)):
  164. img_name = str(time.time()).replace('.','')
  165. contents = await file.read()
  166. image = Image.open(io.BytesIO(contents))
  167. image= image.convert("RGB")
  168. image.save(cover_img_dir+img_name+'.jpg')
  169. return {"msg": serverADDR+cover_img_dir+img_name+'.jpg'}
  170. @app.post("/email_interest")
  171. async def email_interest(email_tag:Email_tag):
  172. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  173. email_table = db['interest_email']
  174. for tag in email_tag.tags.split(','):
  175. email_table.insert({'email':email_tag.email,'interest_tag':tag})
  176. x = threading.Thread(target=to_sheet)
  177. x.start()
  178. return {'msg':'ok'}
  179. def to_sheet():
  180. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/openTalk?charset=utf8mb4')
  181. statement = 'SELECT DISTINCT email FROM interest_email '
  182. df = pd.DataFrame()
  183. for row in db.query(statement):
  184. tag_names = ''
  185. for row_tag in db.query('SELECT interest_tag FROM interest_email WHERE email="'+row['email']+'"'):
  186. tag_names += first(db.query('SELECT * FROM tag where id ='+str(row_tag['interest_tag'])))['name']
  187. tag_names += ', '
  188. df = df.append({'email':row['email'],'種類':tag_names}, ignore_index=True)
  189. save_sheet(df,'interest_email','index')
  190. def save_sheet(df,filename,tabname,startpos='A1'):
  191. scope = ['https://spreadsheets.google.com/feeds',
  192. 'https://www.googleapis.com/auth/drive']
  193. credentials = ServiceAccountCredentials.from_json_keyfile_name('spread2.json', scope)
  194. gc = gspread.authorize(credentials)
  195. spread = Spread(filename,creds=credentials)
  196. spread.df_to_sheet(df, index=False, sheet=tabname, start=startpos, replace=False)