main.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from enum import Enum
  2. import time
  3. from datetime import datetime
  4. from typing import Optional
  5. from pydantic import BaseModel
  6. from fastapi import FastAPI, Query, UploadFile, File
  7. import dataset,json
  8. from fastapi import FastAPI
  9. from fastapi.middleware.cors import CORSMiddleware
  10. import pandas as pd
  11. from gspread_pandas import Spread, Client
  12. from oauth2client.service_account import ServiceAccountCredentials
  13. import gspread
  14. import asyncio
  15. app = FastAPI()
  16. import nest_asyncio
  17. import threading
  18. origins = [
  19. "https://hhh.com.tw"
  20. "http://172.105.205.52",
  21. "http://172.105.205.52:8002",
  22. "http://172.104.93.163",
  23. ]
  24. app.add_middleware(
  25. CORSMiddleware,
  26. # allow_origins=origins,
  27. allow_origins=["*"],
  28. allow_credentials=True,
  29. allow_methods=["*"],
  30. allow_headers=["*"],
  31. )
  32. class deco_request(BaseModel):
  33. id: int
  34. name: str
  35. email: str
  36. phone: str
  37. class deco_request_detail(BaseModel):
  38. id: int
  39. name: str
  40. email: str
  41. phone: str
  42. #detail
  43. loc: str
  44. h_class: str
  45. # type: str
  46. # budget: str
  47. size: str
  48. # bed_num: int
  49. # liv_num: int
  50. # bath_num: int
  51. # style: str
  52. # prefer_date: str
  53. time_stamp: str
  54. # gender: str
  55. version: str
  56. class client_info(BaseModel):
  57. name:str
  58. organization:str
  59. position:str
  60. phone:str
  61. email:str
  62. cert_last5:str
  63. where_learn:str
  64. why_sign:str
  65. @app.get("/deco_request")
  66. async def get_req():
  67. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  68. request_table = db['deco_request']
  69. statement = 'SELECT * FROM deco_request'
  70. reqs = []
  71. for req in db.query(statement):
  72. '''
  73. reqs.append({'name':req['name'],'email':req['email'],'phone':req['phone'],'loc':req['loc']
  74. ,'h_class':req['h_class'],'type':req['type'],'budget':req['budget'],'size':req['size'],'bed_num':req['bed_num']
  75. ,'liv_num':req['liv_num'],'bath_num':req['bath_num'],'style':req['style'],'prefer_date':req['prefer_date'],'gender':req.gender})
  76. '''
  77. reqs.append({'name':req['name'],'email':req['email'],'phone':req['phone'],'loc':req['loc']
  78. ,'h_class':req['h_class'], 'size':req['size']})
  79. return reqs
  80. @app.post("/deco_request")
  81. async def create_req(req:deco_request):
  82. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  83. request_table = db['deco_request']
  84. time_stamp = datetime.fromtimestamp(time.time())
  85. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  86. pk = request_table.insert({'name':req.name,'email':req.email,'phone':req.phone,'time_stamp':time_stamp})
  87. req.id = pk
  88. return req
  89. @app.post("/add_client_info")
  90. async def add_client_info(ci:client_info):
  91. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  92. request_table = db['client_info']
  93. time_stamp = datetime.fromtimestamp(time.time())
  94. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  95. pk = request_table.insert({'name':ci.name,'organization':ci.organization,'position':ci.position,'phone':ci.phone,'email':ci.email
  96. ,'cert_last5':ci.cert_last5,'where_learn':ci.where_learn,'why_sign':ci.why_sign,'time_stamp':time_stamp})
  97. return pk
  98. @app.post("/deco_request_detail")
  99. async def create_req_detail(req:deco_request_detail):
  100. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  101. statement = 'SELECT * FROM deco_request WHERE email="'+req.email+'"'
  102. email_cnt = 0
  103. for row in db.query(statement):
  104. email_cnt = email_cnt + 1
  105. statement = 'SELECT * FROM deco_request WHERE phone="'+req.phone+'"'
  106. phone_cnt = 0
  107. for row in db.query(statement):
  108. phone_cnt = phone_cnt + 1
  109. return_code = 0
  110. #return code 0=good, 1=email duplication, 2=phone duplication, 3= both duplicate
  111. '''
  112. if email_cnt>0 and phone_cnt==0:
  113. return_code = 1
  114. if email_cnt==0 and phone_cnt>0:
  115. return_code = 2
  116. if email_cnt>0 and phone_cnt>0:
  117. return_code = 3
  118. '''
  119. if return_code ==0 :
  120. request_table = db['deco_request']
  121. time_stamp = datetime.fromtimestamp(time.time())
  122. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  123. req.time_stamp = time_stamp
  124. '''
  125. pk = request_table.insert({'name':req.name,'email':req.email,'phone':req.phone,'loc':req.loc
  126. ,'h_class':req.h_class,'type':req.type,'budget':req.budget,'size':req.size,'bed_num':req.bed_num
  127. ,'liv_num':req.liv_num,'bath_num':req.bath_num,'style':req.style,'prefer_date':req.prefer_date,'time_stamp':req.time_stamp,'gender':req.gender,'version':req.version})
  128. '''
  129. pk = request_table.insert({'name':req.name,'email':req.email,'phone':req.phone,'loc':req.loc
  130. , 'h_class':req.h_class, 'size':req.size,'time_stamp':req.time_stamp,'version':req.version})
  131. req.id = pk
  132. x = threading.Thread(target=make_req_df)
  133. x.start()
  134. #asyncio.run(make_req_df())23
  135. return return_code
  136. else :
  137. return return_code
  138. async def make_req_df():
  139. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  140. statement = 'SELECT * FROM deco_request ORDER BY time_stamp DESC'
  141. #2021-05-23 15:57:43
  142. df = pd.DataFrame()
  143. for row in db.query(statement):
  144. date_format = "%Y-%M-%d %H:%M:%S"
  145. #fdate = datetime.strptime(row['ts_date'],date_format)
  146. fdate = row['time_stamp'].strftime('%Y-%m-%d')
  147. df = df.append({'serial id':row['id'],'姓名':['name'],'email':row['email'],'電話':row['phone']
  148. ,'地區':row['loc'],'房屋類型':row['h_class'],"房屋型態":row['type'],'預算':row['budget']
  149. ,'坪數':row['size'],'房數':row['bed_num'],'廳數':row['liv_num'],'衛浴數':row['bath_num']
  150. ,'風格類型':row['style'],'預選裝修日期':row['prefer_date']}, ignore_index=True)
  151. save_sheet(df,'deco_request','sheet1')
  152. def save_sheet(df,filename,tabname,startpos='A1'):
  153. scope = ['https://spreadsheets.google.com/feeds',
  154. 'https://www.googleapis.com/auth/drive']
  155. # credentials = ServiceAccountCredentials.from_json_keyfile_name('c:\\keys\\spread2.json', scope)
  156. credentials = ServiceAccountCredentials.from_json_keyfile_name('spread2.json', scope)
  157. gc = gspread.authorize(credentials)
  158. spread = Spread(filename,creds=credentials)
  159. spread.df_to_sheet(df, index=False, sheet=tabname, start=startpos, replace=False)