main.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. app = FastAPI()
  27. app.add_middleware(
  28. CORSMiddleware,
  29. allow_origins=['*'],
  30. allow_credentials=True,
  31. allow_methods=["*"],
  32. allow_headers=["*"],
  33. )
  34. def hhh_send_mail(email):
  35. SENDER = "Gorgeous Space <noreply@hhh.com.tw>"
  36. RECIPIENT = "jeweiliang@gmail.com"
  37. AWS_REGION = "us-east-1"
  38. CHARSET = "UTF-8"
  39. client = boto3.client('ses',region_name=AWS_REGION)
  40. # Try to send the email.
  41. try:
  42. #Provide the contents of the email.
  43. msg = MIMEMultipart()
  44. msg["Subject"] = "[幸福空間] 您的五萬元裝修折價券 "
  45. msg["From"] = "noreply@hhh.com.tw"
  46. msg["To"] = email
  47. # Set message body
  48. body = MIMEText("感謝填寫幸福空間問卷,這是您的五萬元裝修折價券\n", "plain")
  49. msg.attach(body)
  50. filename = "coupon.png" # In same directory as script
  51. with open(filename, "rb") as attachment:
  52. part = MIMEApplication(attachment.read())
  53. part.add_header("Content-Disposition",
  54. "attachment",
  55. filename=filename)
  56. msg.attach(part)
  57. response = client.send_raw_email(
  58. Source=msg["From"],
  59. Destinations=[msg["To"]],
  60. RawMessage={"Data": msg.as_string()}
  61. )
  62. print(response)
  63. # Display an error if something goes wrong.
  64. except ClientError as e:
  65. print(e.response['Error']['Message'])
  66. else:
  67. print("Email sent! Message ID:"),
  68. print(response['MessageId'])
  69. def thread_mail(umail):
  70. print('thread_mail called')
  71. # r = requests.get('http://3.220.159.187:8081/mailto/'+umail)
  72. # print(r.text)
  73. # os.chdir('/root/hhh_step_question/step_question/tests')
  74. # os.system('python3 /root/hhh_step_question/step_question/tests/dftest.py &')
  75. def get_db():
  76. # db = dataset.connect('mysql://choozmo:pAssw0rd@139.162.121.30:33306/hhh?charset=utf8mb4')
  77. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  78. step_questions_table = db['step_questions']
  79. return step_questions_table
  80. def mail_to_user(umail):
  81. r = requests.get('http://3.220.159.187:8081/mailto/'+umail)
  82. print(r.text)
  83. # os.chdir('/root/hhh_step_question/step_question/tests')
  84. os.system('python3 /root/hhh_step_question/step_question/tests/dftest.py &')
  85. # umail
  86. @app.post("/step_questions/submit", response_class=RedirectResponse)
  87. async def submit(request: Request):
  88. form_data = await request.form()
  89. # form_data = request.form()
  90. email=form_data.get('q3')
  91. result = {
  92. 'sex': form_data.get('q1'),
  93. 'phone': form_data.get('q2'),
  94. 'email': email,
  95. 'building_case_name': form_data.get('q4'),
  96. 'building_case_type': form_data.get('q5'),
  97. 'decoration_style': ','.join(form_data.getlist('q6')),
  98. 'decoration_budget': ','.join(form_data.getlist('q7')),
  99. 'decoration_size': ','.join(form_data.getlist('q8')),
  100. 'src':'SMS'
  101. }
  102. print(result)
  103. get_db().insert(result)
  104. # mail_to_user(email)
  105. x = threading.Thread(target=hhh_send_mail, args=(email,))
  106. x.start()
  107. return RedirectResponse(url="/a1/index_complete_msg.html", status_code=HTTP_302_FOUND)
  108. # return result
  109. @app.post("/step_questions/line-submit", response_class=RedirectResponse)
  110. async def line_submit(request: Request):
  111. form_data = await request.form()
  112. # form_data = request.form()
  113. email=form_data.get('q3')
  114. result = {
  115. 'sex': form_data.get('q1'),
  116. 'phone': form_data.get('q2'),
  117. 'email': email,
  118. 'building_case_name': form_data.get('q4'),
  119. 'building_case_type': form_data.get('q5'),
  120. 'decoration_style': ','.join(form_data.getlist('q6')),
  121. 'decoration_budget': ','.join(form_data.getlist('q7')),
  122. 'decoration_size': ','.join(form_data.getlist('q8')),
  123. 'src':'LINE'
  124. }
  125. print(result)
  126. get_db().insert(result)
  127. # mail_to_user(email)
  128. x = threading.Thread(target=hhh_send_mail, args=(email,))
  129. x.start()
  130. return RedirectResponse(url="/a1/index_complete_line_after.html", status_code=HTTP_302_FOUND)
  131. # return result
  132. app.mount("/a1", StaticFiles(directory="static"), name="static")
  133. @app.get("/a1")
  134. async def redirect():
  135. # url = app.url_path_for("/a1/index.html")
  136. response = RedirectResponse(url='/a1/index.html')
  137. return response
  138. #@app.get("/a1", response_class=HTMLResponse)
  139. #@app.get("/a1", response_class=HTMLResponse)
  140. #async def read_items():
  141. # return """
  142. # <html>
  143. # <head>
  144. # <title>Some HTML in here</title>
  145. # </head>
  146. # <body>
  147. # <h1>Look ma! HTML!</h1>
  148. # </body>
  149. # </html>
  150. # """
  151. @app.get("/step_questions")
  152. async def get_step_question(request: Request):
  153. db_data = list(get_db().find())
  154. df = pd.DataFrame(db_data, columns=db_data[0].keys())
  155. stream = io.StringIO()
  156. df.to_csv(stream, index = False)
  157. # response = StreamingResponse(data_frame.to_csv(index=False), media_type="text/csv")
  158. response = StreamingResponse(iter([stream.getvalue()]), media_type="text/csv")
  159. response.headers["Content-Disposition"] = "attachment; filename=export.csv"
  160. return response