main.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import socket
  2. from fastapi import FastAPI, Request
  3. from fastapi.responses import HTMLResponse
  4. from fastapi.staticfiles import StaticFiles
  5. from fastapi.templating import Jinja2Templates
  6. import requests
  7. import uvicorn
  8. from fastapi.responses import FileResponse
  9. from fastapi import FastAPI, Depends, HTTPException, Form
  10. import httpx
  11. import os
  12. # from db.user import UserOAuthToken
  13. from config import HOST, PORT
  14. app = FastAPI()
  15. @app.get("/")
  16. async def read_root(request: Request):
  17. return FileResponse(os.path.join("static", "index.html"))
  18. # 授权码获取 access_token 的路由
  19. @app.post("/get_access_token")
  20. async def get_access_token(request: Request):
  21. client_key = os.environ.get("CLIENT_KEY") # 从环境变量中获取 client_key
  22. client_secret = os.environ.get("CLIENT_SECRET") # 从环境变量中获取 client_secret
  23. try:
  24. code = request.query_params["code"] # 从查询参数中获取 code
  25. except KeyError:
  26. raise HTTPException(status_code=400, detail="Missing 'code' parameter")
  27. # 发送请求获取 access_token
  28. async with httpx.AsyncClient() as client:
  29. response = await client.post(
  30. "https://open.douyin.com/oauth/access_token/",
  31. headers={"Content-Type": "application/json"},
  32. json={
  33. "grant_type": "authorization_code",
  34. "client_key": client_key,
  35. "client_secret": client_secret,
  36. "code": code,
  37. },
  38. )
  39. if response.status_code != 200:
  40. raise HTTPException(status_code=response.status_code, detail=response.text)
  41. '''
  42. {
  43. "data": {
  44. "access_token": "act.f7094fbffab2ecbfc45e9af9c32bc241oYdckvBKe82BPx8T******",
  45. "captcha": "",
  46. "desc_url": "",
  47. "description": "",
  48. "error_code": 0,
  49. "expires_in": 1296000,
  50. "log_id": "20230525105733ED3ED7AC56A******",
  51. "open_id": "b9b71865-7fea-44cc-******",
  52. "refresh_expires_in": 2592000,
  53. "refresh_token": "rft.713900b74edde9f30ec4e246b706da30t******",
  54. "scope": "user_info"
  55. },
  56. "message": "success"
  57. }
  58. '''
  59. data = response.json()["data"]
  60. print(data)
  61. # magong_user = UserOAuthToken(access_token=data['access_token'], open_id=data['open_id'])
  62. return {"message": "Access token stored successfully"}
  63. @app.get("/verify_callback")
  64. async def verify_callback(request: Request):
  65. # 打印请求方法
  66. print(f"Method: {request.method}")
  67. # open-douyin.magong.site/verify_callback?code=676a1101ea02bc5dTaUVtKg8c5enYaGqB4dT&state=&scopes=user_info,trial.whitelist
  68. print(request.url)
  69. # 打印请求头
  70. print(f"Headers:")
  71. for key, value in request.headers.items():
  72. print(f"{key}: {value}")
  73. # 打印查询参数
  74. print(f"Query Parameters:")
  75. for key, value in request.query_params.items():
  76. print(f"{key}: {value}")
  77. return HTMLResponse("<h1>Callback Received! Verification Successful.</h1>")
  78. def main():
  79. print(f"https://open-douyin-cf.magong.site 公网代理地址,cloudflare dns proxy ,由 caddy 转发到 8600 端口")
  80. print(f"https://open-douyin-wk.magong.site 公网代理地址,cloudflare workers 转发到 8600 端口")
  81. print(f"http://sv-v2.magong.site:{PORT} ⭐ 推荐,仅支持 ipv6 ,直连、满速、无延迟。缺点是不支持 https 协议,因为不经过 Caddy 代理,直达 Fastapi 没有配置 https")
  82. print(f"https://open-douyin.magong.site 内网穿透隧道,cloudflare tunnel ,经常访问不了")
  83. uvicorn.run(app, host=None, port=PORT, log_level="info")
  84. if __name__ == "__main__":
  85. main()