main.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. from fastapi import FastAPI, Form, Request
  2. from fastapi.encoders import jsonable_encoder
  3. from fastapi.middleware.cors import CORSMiddleware
  4. import dataset
  5. import pandas as pd
  6. from starlette.responses import FileResponse, StreamingResponse
  7. from fastapi.responses import HTMLResponse
  8. from fastapi.staticfiles import StaticFiles
  9. import io
  10. from starlette.responses import RedirectResponse
  11. import codecs
  12. import random
  13. from starlette.status import HTTP_302_FOUND,HTTP_303_SEE_OTHER
  14. import smtplib
  15. import traceback
  16. import requests
  17. import threading
  18. import os
  19. from email.mime.text import MIMEText
  20. from email.mime.image import MIMEImage
  21. from email.mime.multipart import MIMEMultipart
  22. import boto3
  23. from botocore.exceptions import ClientError
  24. from email.mime.base import MIMEBase
  25. from email.mime.application import MIMEApplication
  26. import random
  27. app = FastAPI()
  28. app.add_middleware(
  29. CORSMiddleware,
  30. allow_origins=['*'],
  31. allow_credentials=True,
  32. allow_methods=["*"],
  33. allow_headers=["*"],
  34. )
  35. coffee='0'
  36. def hhh_send_mail(email,coffee=False):
  37. SENDER = "Gorgeous Space <noreply@hhh.com.tw>"
  38. RECIPIENT = "jeweiliang@gmail.com"
  39. AWS_REGION = "us-east-1"
  40. CHARSET = "UTF-8"
  41. client = boto3.client('ses',region_name=AWS_REGION)
  42. # Try to send the email.
  43. try:
  44. #Provide the contents of the email.
  45. msg = MIMEMultipart()
  46. msg["Subject"] = "[幸福空間] 您的五萬元裝修折價券 "
  47. msg["From"] = "noreply@hhh.com.tw"
  48. msg["To"] = email
  49. # Set message body
  50. if coffee:
  51. body = MIMEText("感謝填寫幸福空間問卷,開啟下方完整券樣(密碼9888)至櫃台掃碼兌換。https://txp.rs/v/EvX69b4Xq9 \n\n 附件是您的五萬元裝修折價券\n", "plain")
  52. else:
  53. body = MIMEText("感謝填寫幸福空間問卷,這是您的五萬元裝修折價券\n", "plain")
  54. msg.attach(body)
  55. filename = "coupon.png" # In same directory as script
  56. with open(filename, "rb") as attachment:
  57. part = MIMEApplication(attachment.read())
  58. part.add_header("Content-Disposition",
  59. "attachment",
  60. filename=filename)
  61. msg.attach(part)
  62. response = client.send_raw_email(
  63. Source=msg["From"],
  64. Destinations=[msg["To"]],
  65. RawMessage={"Data": msg.as_string()}
  66. )
  67. print(response)
  68. # Display an error if something goes wrong.
  69. except ClientError as e:
  70. print(e.response['Error']['Message'])
  71. else:
  72. print("Email sent! Message ID:"),
  73. print(response['MessageId'])
  74. os.system('python3 /root/hhh_step_question/step_question/tests/dftest.py &')
  75. def thread_mail(umail):
  76. print('thread_mail called')
  77. # r = requests.get('http://3.220.159.187:8081/mailto/'+umail)
  78. # print(r.text)
  79. # os.chdir('/root/hhh_step_question/step_question/tests')
  80. # os.system('python3 /root/hhh_step_question/step_question/tests/dftest.py &')
  81. def get_db():
  82. # db = dataset.connect('mysql://choozmo:pAssw0rd@139.162.121.30:33306/hhh?charset=utf8mb4')
  83. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  84. step_questions_table = db['step_questions']
  85. return step_questions_table
  86. def mail_to_user(umail):
  87. r = requests.get('http://3.220.159.187:8081/mailto/'+umail)
  88. print(r.text)
  89. # os.chdir('/root/hhh_step_question/step_question/tests')
  90. os.system('python3 /root/hhh_step_question/step_question/tests/dftest.py &')
  91. # umail
  92. @app.post("/step_questions/submit", response_class=RedirectResponse)
  93. async def submit(request: Request):
  94. form_data = await request.form()
  95. # form_data = request.form()
  96. email=form_data.get('q3')
  97. result = {
  98. 'sex': form_data.get('q1'),
  99. 'phone': form_data.get('q2'),
  100. 'email': email,
  101. 'building_case_name': form_data.get('q4'),
  102. 'building_case_type': form_data.get('q5'),
  103. 'decoration_style': ','.join(form_data.getlist('q6')),
  104. 'decoration_budget': ','.join(form_data.getlist('q7')),
  105. 'decoration_size': ','.join(form_data.getlist('q8')),
  106. 'src':'SMS'
  107. }
  108. print(result)
  109. get_db().insert(result)
  110. # mail_to_user(email)
  111. x = threading.Thread(target=hhh_send_mail, args=(email,))
  112. x.start()
  113. return RedirectResponse(url="/a1/index_complete_msg.html", status_code=HTTP_302_FOUND)
  114. # return result
  115. @app.post("/step_questions/line-submit", response_class=RedirectResponse)
  116. async def line_submit(request: Request):
  117. form_data = await request.form()
  118. print(form_data)
  119. # form_data = request.form()
  120. email=form_data.get('q3')
  121. result = {
  122. 'sex': form_data.get('q1'),
  123. 'phone': form_data.get('q2'),
  124. 'email': email,
  125. 'building_case_name': form_data.get('q4'),
  126. 'building_case_type': form_data.get('q5'),
  127. 'decoration_style': ','.join(form_data.getlist('q6')),
  128. 'decoration_budget': ','.join(form_data.getlist('q7')),
  129. 'decoration_size': ','.join(form_data.getlist('q8')),
  130. 'src':'LINE',
  131. 'userid': form_data.get('userid'),
  132. # 'id': form_data.get('id'),
  133. 'area': form_data.get('area'),
  134. }
  135. if result['userid']==None:
  136. result['userid']="None"
  137. print(result)
  138. get_db().insert(result)
  139. # mail_to_user(email)
  140. x = threading.Thread(target=hhh_send_mail, args=(email,True))
  141. x.start()
  142. return RedirectResponse(url="/a1/index_complete_line_after.html", status_code=HTTP_302_FOUND)
  143. # return result
  144. app.mount("/a1", StaticFiles(directory="static"), name="static")
  145. @app.get("/coffee/set/{item_id}")
  146. async def coffee_set(item_id: int):
  147. global coffee
  148. if item_id==0:
  149. coffee='0'
  150. else:
  151. coffee='1'
  152. return {"code":"ok" }
  153. @app.get("/coffee")
  154. async def coffee_get():
  155. global coffee
  156. # val=random.randint(5,100)
  157. # coffee='0'
  158. # if val%2==0:
  159. # coffee='1'
  160. return {'coffee':coffee}
  161. @app.get("/220")
  162. async def redirect220():
  163. response = RedirectResponse(url='/a1/index-line.html')
  164. response.set_cookie(key="area", value="220", domain="q.ptt.cx")
  165. return response
  166. @app.get("/242")
  167. async def redirect242():
  168. response = RedirectResponse(url='/a1/index-line.html')
  169. response.set_cookie(key="area", value="242", domain="q.ptt.cx")
  170. return response
  171. @app.get("/241")
  172. async def redirect241():
  173. response = RedirectResponse(url='/a1/index-line.html')
  174. response.set_cookie(key="area", value="241", domain="q.ptt.cx")
  175. return response
  176. @app.get("/112")
  177. async def redirect112():
  178. response = RedirectResponse(url='/a1/index-line.html')
  179. response.set_cookie(key="area", value="112", domain="q.ptt.cx")
  180. return response
  181. @app.get("/111")
  182. async def redirect111():
  183. response = RedirectResponse(url='/a1/index-line.html')
  184. response.set_cookie(key="area", value="111", domain="q.ptt.cx")
  185. return response
  186. @app.get("/a1")
  187. async def redirect():
  188. # url = app.url_path_for("/a1/index.html")
  189. response = RedirectResponse(url='/a1/index.html')
  190. return response
  191. #@app.get("/a1", response_class=HTMLResponse)
  192. #@app.get("/a1", response_class=HTMLResponse)
  193. #async def read_items():
  194. # return """
  195. # <html>
  196. # <head>
  197. # <title>Some HTML in here</title>
  198. # </head>
  199. # <body>
  200. # <h1>Look ma! HTML!</h1>
  201. # </body>
  202. # </html>
  203. # """
  204. @app.get("/step_questions")
  205. async def get_step_question(request: Request):
  206. db_data = list(get_db().find())
  207. df = pd.DataFrame(db_data, columns=db_data[0].keys())
  208. stream = io.StringIO()
  209. df.to_csv(stream, index = False)
  210. # response = StreamingResponse(data_frame.to_csv(index=False), media_type="text/csv")
  211. response = StreamingResponse(iter([stream.getvalue()]), media_type="text/csv")
  212. response.headers["Content-Disposition"] = "attachment; filename=export.csv"
  213. return response