main.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. data = response.json()["data"]
  42. print(data)
  43. return {"message": "Access token stored successfully"}
  44. @app.get("/verify_callback")
  45. async def verify_callback(request: Request):
  46. # 打印请求方法
  47. print(f"Method: {request.method}")
  48. # 打印请求头
  49. print(f"Headers:")
  50. for key, value in request.headers.items():
  51. print(f"{key}: {value}")
  52. # 打印查询参数
  53. print(f"Query Parameters:")
  54. for key, value in request.query_params.items():
  55. print(f"{key}: {value}")
  56. return HTMLResponse("<h1>Callback Received! Verification Successful.</h1>")
  57. def main():
  58. uvicorn.run(app, host=HOST, port=PORT, log_level="info")
  59. if __name__ == "__main__":
  60. main()