main.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import io
  8. app = FastAPI()
  9. app.add_middleware(
  10. CORSMiddleware,
  11. allow_origins=['*'],
  12. allow_credentials=True,
  13. allow_methods=["*"],
  14. allow_headers=["*"],
  15. )
  16. def get_db():
  17. db = dataset.connect('mysql://choozmo:pAssw0rd@139.162.121.30:33306/hhh?charset=utf8mb4')
  18. step_questions_table = db['step_questions']
  19. return step_questions_table
  20. @app.post("/step_questions/submit")
  21. async def submit(request: Request):
  22. form_data = await request.form()
  23. result = {
  24. 'sex': form_data.get('q1'),
  25. 'phone': form_data.get('q2'),
  26. 'email': form_data.get('q3'),
  27. 'building_case_name': form_data.get('q4'),
  28. 'building_case_type': form_data.get('q5'),
  29. 'decoration_style': ','.join(form_data.getlist('q6')),
  30. 'decoration_budget': ','.join(form_data.getlist('q7')),
  31. 'decoration_size': ','.join(form_data.getlist('q8')),
  32. }
  33. get_db().insert(result)
  34. return result
  35. @app.get("/step_questions")
  36. async def get_step_question(request: Request):
  37. db_data = list(get_db().find())
  38. df = pd.DataFrame(db_data, columns=db_data[0].keys())
  39. stream = io.StringIO()
  40. df.to_csv(stream, index = False)
  41. # response = StreamingResponse(data_frame.to_csv(index=False), media_type="text/csv")
  42. response = StreamingResponse(iter([stream.getvalue()]), media_type="text/csv")
  43. response.headers["Content-Disposition"] = "attachment; filename=export.csv"
  44. return response