main.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import time
  2. from datetime import datetime
  3. from colorama import Back
  4. from fastapi import FastAPI, Form, Request, BackgroundTasks
  5. from fastapi.templating import Jinja2Templates
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from pydantic import BaseModel
  8. from oauth2client.service_account import ServiceAccountCredentials
  9. import os, dataset, json, gspread
  10. from gspread_pandas import Spread, Client
  11. import pandas as pd
  12. from fastapi_utils.tasks import repeat_every
  13. app = FastAPI()
  14. directory=os.path.dirname(os.getcwd())
  15. templates = Jinja2Templates(directory)
  16. origins = [
  17. "*"
  18. ]
  19. app.add_middleware(
  20. CORSMiddleware,
  21. allow_origins=origins,
  22. allow_credentials=True,
  23. allow_methods=["*"],
  24. allow_headers=["*"],
  25. )
  26. @app.get("/")
  27. async def read_root(request: Request):
  28. return templates.TemplateResponse("index.html",{"request": request})
  29. @app.post("/submitform")
  30. async def formentry(bgtask: BackgroundTasks, name: str = Form(...), phone: str = Form(...), loc: str = Form(...), course_name: str = Form(...), bookdate: str = Form(...), booktime: str = Form(...)):
  31. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/violetbeauty?charset=utf8mb4')
  32. request_table = db['booking_info']
  33. time_stamp = datetime.fromtimestamp(time.time())
  34. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  35. print(time_stamp)
  36. request_table.insert({"name": name, "phone": phone, "location": loc, "course_name":course_name, "book_date": bookdate, "book_time": booktime, "time_stamp": time_stamp})
  37. bgtask.add_task(getdata, db)
  38. return 0
  39. def getdata(db):
  40. statement = 'SELECT * FROM booking_info ORDER BY time_stamp DESC'
  41. df = pd.DataFrame()
  42. rowcount = 0
  43. for row in db.query(statement):
  44. date_format = "%Y-%M-%d %H:%M:%S"
  45. fdate = row['time_stamp'].strftime('%Y-%m-%d')
  46. df = df.append({'填單時間':row['time_stamp'],'姓名':row['name'],'電話':str('\'' + row['phone']),'預約體驗店家':row['location'],'選擇課程':row['course_name'],'預約日期':row['book_date'],'預約時間':row['book_time']}, ignore_index=True)
  47. rowcount +=1
  48. if rowcount!=0:
  49. save_sheet(df,'紫晴預約資料','預約資料')
  50. else:
  51. print('沒有資料')
  52. return 0
  53. def save_sheet(df,filename,tabname,startpos='A1'):
  54. scope = ['https://spreadsheets.google.com/feeds',
  55. 'https://www.googleapis.com/auth/drive']
  56. credentials = ServiceAccountCredentials.from_json_keyfile_name('violet-beauty-booking-data-8ef5f0d9a747.json', scope)
  57. gc = gspread.authorize(credentials)
  58. spread = Spread(filename,creds=credentials)
  59. spread.df_to_sheet(df, index=False, sheet=tabname, start=startpos, replace=False)
  60. time_stamp = datetime.fromtimestamp(time.time())
  61. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  62. spread.sheet.update('I1', '最後更新:' + time_stamp)
  63. @app.get("/getbooking_data")
  64. async def getbookingdata(bgtask: BackgroundTasks):
  65. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/violetbeauty?charset=utf8mb4')
  66. bgtask.add_task(getdata, db)
  67. return '資料取出中...'
  68. @app.on_event("startup")
  69. @repeat_every(seconds=60)
  70. def update_booking():
  71. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/violetbeauty?charset=utf8mb4')
  72. getdata(db)