main.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import pandas as pd
  2. from fastapi import FastAPI, File, UploadFile
  3. from fastapi.middleware.cors import CORSMiddleware
  4. import dataset
  5. from functools import reduce
  6. app = FastAPI()
  7. app.add_middleware(
  8. CORSMiddleware,
  9. allow_origins=['*'],
  10. allow_credentials=True,
  11. allow_methods=["*"],
  12. allow_headers=["*"],
  13. )
  14. @app.post("/write/")
  15. async def writecsv(file: UploadFile = File(...)):
  16. # read csv
  17. repls = (' Stats ', '_'), (' at ', '_'), ('-', '_'), \
  18. (' ', ''), ('.csv', '')
  19. filename = file.filename
  20. filename = reduce(lambda a, kv: a.replace(*kv), repls, filename)
  21. data = file.file
  22. df = pd.read_csv(data, sep=",",
  23. skiprows=0, na_values='NULL')
  24. # db connect
  25. db = dataset.connect(
  26. 'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/keywordweb?charset=utf8mb4'
  27. )
  28. sql = "CREATE TABLE IF NOT EXISTS " \
  29. + filename + \
  30. "(ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " \
  31. "keyword VARCHAR(100), " \
  32. "currency VARCHAR(100), avg_monthly_searches VARCHAR(100), " \
  33. "three_month_change VARCHAR(100), " \
  34. "yearly_change VARCHAR(100), competition VARCHAR(100), " \
  35. "competition_indexed VARCHAR(100), " \
  36. "top_page_bid_low_range VARCHAR(100), " \
  37. "top_page_bid_hi_range VARCHAR(100)" \
  38. ");"
  39. db.query(sql)
  40. # write to db
  41. table = db[filename]
  42. lines = df.shape
  43. i = 0
  44. rows = lines[0]
  45. for i in range(rows):
  46. row1 = df.iloc[i]
  47. k = row1[0]
  48. c = row1[1]
  49. a = row1[2]
  50. t = row1[3]
  51. y = row1[4]
  52. c1 = row1[5]
  53. c2 = row1[6]
  54. t1 = row1[7]
  55. t2 = row1[8]
  56. dbdata = dict(keyword=k, currency=c, avg_monthly_searches=a,
  57. three_month_change=t, yearly_change=y, competition=c1,
  58. competition_indexed=c2, top_page_bid_low_range=t1,
  59. top_page_bid_hi_range=t2)
  60. table.insert(dbdata)
  61. db.close()