main.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. app = FastAPI()
  12. app.add_middleware(
  13. CORSMiddleware,
  14. allow_origins=['*'],
  15. allow_credentials=True,
  16. allow_methods=["*"],
  17. allow_headers=["*"],
  18. )
  19. def get_db():
  20. db = dataset.connect('mysql://choozmo:pAssw0rd@139.162.121.30:33306/hhh?charset=utf8mb4')
  21. step_questions_table = db['step_questions']
  22. return step_questions_table
  23. @app.post("/step_questions/submit")
  24. async def submit(request: Request):
  25. form_data = await request.form()
  26. result = {
  27. 'sex': form_data.get('q1'),
  28. 'phone': form_data.get('q2'),
  29. 'email': form_data.get('q3'),
  30. 'building_case_name': form_data.get('q4'),
  31. 'building_case_type': form_data.get('q5'),
  32. 'decoration_style': ','.join(form_data.getlist('q6')),
  33. 'decoration_budget': ','.join(form_data.getlist('q7')),
  34. 'decoration_size': ','.join(form_data.getlist('q8')),
  35. }
  36. get_db().insert(result)
  37. response = RedirectResponse(url='/a1/index_complete.html')
  38. return response
  39. # return result
  40. app.mount("/a1", StaticFiles(directory="static"), name="static")
  41. @app.get("/a1")
  42. async def redirect():
  43. # url = app.url_path_for("/a1/index.html")
  44. response = RedirectResponse(url='/a1/index.html')
  45. return response
  46. #@app.get("/a1", response_class=HTMLResponse)
  47. #@app.get("/a1", response_class=HTMLResponse)
  48. #async def read_items():
  49. # return """
  50. # <html>
  51. # <head>
  52. # <title>Some HTML in here</title>
  53. # </head>
  54. # <body>
  55. # <h1>Look ma! HTML!</h1>
  56. # </body>
  57. # </html>
  58. # """
  59. @app.get("/step_questions")
  60. async def get_step_question(request: Request):
  61. db_data = list(get_db().find())
  62. df = pd.DataFrame(db_data, columns=db_data[0].keys())
  63. stream = io.StringIO()
  64. df.to_csv(stream, index = False)
  65. # response = StreamingResponse(data_frame.to_csv(index=False), media_type="text/csv")
  66. response = StreamingResponse(iter([stream.getvalue()]), media_type="text/csv")
  67. response.headers["Content-Disposition"] = "attachment; filename=export.csv"
  68. return response