main.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. from enum import Enum
  2. import time
  3. from datetime import datetime
  4. from typing import Optional
  5. from pydantic import BaseModel
  6. from fastapi import FastAPI, Query, UploadFile, File
  7. from fastapi import FastAPI
  8. from fastapi.middleware.cors import CORSMiddleware
  9. import json
  10. import urllib.request
  11. import dataset,json
  12. import pandas as pd
  13. from gspread_pandas import Spread, Client
  14. from oauth2client.service_account import ServiceAccountCredentials
  15. import gspread
  16. from first import first
  17. app = FastAPI()
  18. origins = [
  19. "http://172.105.205.52",
  20. "http://172.105.205.52:8001",
  21. ]
  22. app.add_middleware(
  23. CORSMiddleware,
  24. # allow_origins=origins,
  25. allow_origins=["*"],
  26. allow_credentials=True,
  27. allow_methods=["*"],
  28. allow_headers=["*"],
  29. )
  30. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/NFTBoard?charset=utf8mb4')
  31. class subreq(BaseModel):
  32. email:str
  33. class ContactUs(BaseModel):
  34. country_code: str
  35. username: str
  36. email: str
  37. phone: str
  38. coop_dif: Optional[bool] = 0
  39. coop_ad: Optional[bool] = 0
  40. coop_acting: Optional[bool] = 0
  41. coop_marketing: Optional[bool] = 0
  42. work_address: Optional[str] = ''
  43. @app.get("/showdata/{limit}")
  44. async def showdata(limit):
  45. # url = 'https://api.coinmarketcap.com/data-api/v3/nft/collections?start=0&limit=' + limit
  46. url = 'https://api.coinmarketcap.com/data-api/v3/nft/collections?start=0&limit=' + limit + '&period=2'
  47. r = urllib.request.urlopen(url)
  48. collections = json.loads(r.read())['data']['collections']
  49. reqs = []
  50. for req in collections:
  51. website = '#'
  52. if req.get('website') is not None:
  53. website = req['website']
  54. collection_net_worth = round(float(req['netWorth']), 2)
  55. volume_7d = round(float(req['volume7d']), 2)
  56. volume_all_time = round(float(req['volumeAT']), 2)
  57. reqs.append({'rank':req['rank'],'slug':req['slug'],'logo':req['logo'],'website':website,'name':req['name'],'assets':req['assets'],'collection_net_worth':collection_net_worth,'volume_7d':volume_7d,'sales_7d':req['sales7d'],'volume_all_time':volume_all_time,'sales_all_time':req['salesAT'],'owners':req['owners']})
  58. return reqs
  59. @app.post("/add_sub")
  60. async def add_subclient_info(req:subreq):
  61. code = 1
  62. sub_table = db['Subscribe']
  63. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  64. statement='SELECT COUNT(1) FROM Subscribe WHERE email = "'+req.email+'"'
  65. if first(db.query(statement))['COUNT(1)']==0:
  66. pk = sub_table.insert({'email':req.email,'timestamp':time_stamp})
  67. make_ci_df()
  68. code = 0
  69. return {'msg':code}#0 means succss added, 1 means email is duplicated
  70. @app.post('/add_contact_us')
  71. async def add_contact_us_client_info(req: ContactUs):
  72. """ 新增Contact Us資料,先存入DB,並從DB撈回全部資料,更新Google Sheet. """
  73. code = 1
  74. table = db['ContactUs']
  75. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  76. # 會根據email做判斷,此處先comment給測試使用。
  77. # statement = 'SELECT COUNT(1) FROM ContactUs WHERE email = "'+ req.email +'"'
  78. # if first(db.query(statement))['COUNT(1)'] == 0:
  79. # table.insert(
  80. # {
  81. # 'country_code':req.country_code,
  82. # 'username': req.username,
  83. # 'email': req.email,
  84. # 'phone': req.phone,
  85. # 'coop_dif': req.coop_dif,
  86. # 'coop_ad': req.coop_ad,
  87. # 'coop_acting': req.coop_acting,
  88. # 'coop_marketing': req.coop_marketing,
  89. # 'work_address': req.work_address,
  90. # 'timestamp': time_stamp
  91. # }
  92. # )
  93. # code = 0
  94. # # 更新sheet
  95. # make_contact_us_df()
  96. table.insert(
  97. {
  98. 'country_code':req.country_code,
  99. 'username': req.username,
  100. 'email': req.email,
  101. 'phone': req.phone,
  102. 'coop_dif': req.coop_dif,
  103. 'coop_ad': req.coop_ad,
  104. 'coop_acting': req.coop_acting,
  105. 'coop_marketing': req.coop_marketing,
  106. 'work_address': req.work_address,
  107. 'timestamp': time_stamp
  108. }
  109. )
  110. code = 0
  111. # 更新sheet
  112. make_contact_us_df()
  113. return {'msg':code}#0 means succss added, 1 means email is duplicated
  114. @app.get("/get_sub_list")
  115. async def add_subclient_info():
  116. statement = 'SELECT * FROM Subscribe'
  117. result = []
  118. for row in db.query(statement):
  119. result += [{'id':row['id'],'email':row['email'],'timeStamp':row['timestamp']}]
  120. return result
  121. def make_ci_df():
  122. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/NFTBoard?charset=utf8mb4')
  123. statement = 'SELECT * FROM Subscribe ORDER BY timestamp DESC'
  124. #2021-05-23 15:57:43
  125. df = pd.DataFrame()
  126. for row in db.query(statement):
  127. date_format = "%Y-%M-%d %H:%M:%S"
  128. fdate = row['timestamp'].strftime('%Y-%m-%d %H時 %M分')
  129. df = df.append({'serial id':row['id'],'e-mail':row['email'],'登記時間':fdate}, ignore_index=True)
  130. df = df[['serial id','e-mail','登記時間']]
  131. save_sheet(df,'subscribe_rec','Sheet1')
  132. def make_contact_us_df():
  133. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/NFTBoard?charset=utf8mb4')
  134. statement = 'SELECT * FROM ContactUs ORDER BY timestamp DESC'
  135. df = pd.DataFrame()
  136. for row in db.query(statement):
  137. df = df.append({'id': row['id'], '國家區域': row['country_code'], '姓名': row['username'], '聯絡Email': row['email'], '聯絡手機': row['phone'], '合作方式_異業合作': row['coop_dif'], '合作方式_廣告刊登': row['coop_ad'], '合作方式_代理發行': row['coop_acting'], '合作方式_知識產權行銷': row['coop_marketing'], '作品連結': row['work_address'], '申請時間': row['timestamp']}, ignore_index=True)
  138. df = df[['id', '國家區域', '姓名', '聯絡Email', '聯絡手機', '合作方式_異業合作', '合作方式_廣告刊登', '合作方式_代理發行', '合作方式_知識產權行銷', '作品連結', '申請時間']]
  139. # print(df)
  140. save_sheet(df, '聯絡NFTBoard (回應)', 'Sheet1', json_name='cred.json')
  141. def save_sheet(df,filename,tabname,startpos='A1', json_name='spread2.json'):
  142. scope = ['https://spreadsheets.google.com/feeds',
  143. 'https://www.googleapis.com/auth/drive']
  144. credentials = ServiceAccountCredentials.from_json_keyfile_name(json_name, scope)
  145. gc = gspread.authorize(credentials)
  146. spread = Spread(filename,creds=credentials)
  147. spread.df_to_sheet(df, sheet=tabname, start=startpos, replace=True, index=False)