Skip to content

Commit

Permalink
refactor python folder
Browse files Browse the repository at this point in the history
  • Loading branch information
dreamhunter2333 committed Apr 26, 2024
1 parent 181be93 commit 1febb00
Show file tree
Hide file tree
Showing 17 changed files with 87 additions and 82 deletions.
5 changes: 3 additions & 2 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging

from pydantic import BaseSettings, Field
from pydantic import Field
from pydantic_settings import BaseSettings

logging.basicConfig(
format="%(asctime)s: %(levelname)s: %(name)s: %(message)s",
Expand All @@ -26,4 +27,4 @@ class Config:


settings = Settings()
_logger.info(f"settings: {settings.json(indent=2)}")
_logger.info(f"settings: {settings.model_dump_json(indent=2)}")
60 changes: 1 addition & 59 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,6 @@
import os
import logging
import uvicorn

from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse, FileResponse
from fastapi.staticfiles import StaticFiles

from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware

from src.limiter import limiter, get_real_ipaddr
from src.chatgpt_router import router as chatgpt_router
from src.divination_router import router as divination_router
from src.user_router import router as user_router


_logger = logging.getLogger(__name__)

app = FastAPI(title="Chatgpt Divination API")
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5173",
"http://localhost",
"http://127.0.0.1"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

app.include_router(chatgpt_router)
app.include_router(divination_router)
app.include_router(user_router)

if os.path.exists("dist"):
@app.get("/")
@app.get("/login/{path}")
async def read_index(request: Request):
_logger.info(f"Request from {get_real_ipaddr(request)}")
return FileResponse(
"dist/index.html",
headers={"Cache-Control": "no-cache"}
)

app.mount("/", StaticFiles(directory="dist"), name="static")


@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception):
return PlainTextResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=f"Internal Server Error: {exc}",
)
from src.app import app

if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
15 changes: 8 additions & 7 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
fastapi==0.95.0
python-dotenv==1.0.0
uvicorn==0.21.1
openai==0.27.4
python-multipart==0.0.6
slowapi==0.1.8
pyjwt==2.7.0
fastapi==0.110.2
pydantic-settings==2.2.1
pydantic==2.7.1
uvicorn==0.29.0
openai==1.23.6
slowapi==0.1.9
pyjwt==2.8.0
requests==2.31.0
60 changes: 60 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os
import logging

from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse, FileResponse
from fastapi.staticfiles import StaticFiles

from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware

from src.limiter import limiter, get_real_ipaddr
from src.chatgpt_router import router as chatgpt_router
from src.divination_router import router as divination_router
from src.user_router import router as user_router


_logger = logging.getLogger(__name__)

app = FastAPI(title="Chatgpt Divination API")
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5173",
"http://localhost",
"http://127.0.0.1"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

app.include_router(chatgpt_router)
app.include_router(divination_router)
app.include_router(user_router)

if os.path.exists("dist"):
@app.get("/")
@app.get("/login/{path}")
async def read_index(request: Request):
_logger.info(f"Request from {get_real_ipaddr(request)}")
return FileResponse(
"dist/index.html",
headers={"Cache-Control": "no-cache"}
)

app.mount("/", StaticFiles(directory="dist"), name="static")


@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception):
return PlainTextResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=f"Internal Server Error: {exc}",
)
2 changes: 1 addition & 1 deletion src/chatgpt_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from config import settings
from fastapi import APIRouter

from models import DivinationBody, User
from src.models import DivinationBody, User
from src.user import get_user
from .limiter import get_real_ipaddr, limiter
from .divination import DivinationFactory
Expand Down
2 changes: 1 addition & 1 deletion src/divination/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

from models import DivinationBody
from src.models import DivinationBody
from typing import Optional


Expand Down
2 changes: 1 addition & 1 deletion src/divination/birthday.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import datetime
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

BIRTHDAY_PROMPT = "我请求你担任中国传统的生辰八字算命的角色。" \
Expand Down
2 changes: 1 addition & 1 deletion src/divination/dream.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import HTTPException
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

DREAM_PROMPT = "我请求你担任中国传统的周公解梦师的角色。" \
Expand Down
2 changes: 1 addition & 1 deletion src/divination/fate.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import HTTPException
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

SYS_PROMPT = "你是一个姻缘助手,我给你发两个人的名字,用逗号隔开,"\
Expand Down
2 changes: 1 addition & 1 deletion src/divination/name.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import HTTPException
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

NAME_PROMPT = "我请求你担任中国传统的姓名五格算命师的角色。" \
Expand Down
2 changes: 1 addition & 1 deletion src/divination/new_name.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
from fastapi import HTTPException
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

NEW_NAME_PROMPT = (
Expand Down
2 changes: 1 addition & 1 deletion src/divination/plum_flower.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import HTTPException
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

SYS_PROMPT = "我请求你担任中国传统的梅花易数占卜师的角色。" \
Expand Down
2 changes: 1 addition & 1 deletion src/divination/tarot.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import HTTPException
from models import DivinationBody
from src.models import DivinationBody
from .base import DivinationFactory

TAROT_PROMPT = "我请求你担任塔罗占卜师的角色。 " \
Expand Down
2 changes: 1 addition & 1 deletion src/divination_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from config import settings
from fastapi import APIRouter

from models import BirthdayBody, CommonResponse
from src.models import BirthdayBody, CommonResponse
from .limiter import get_real_ipaddr
from .divination.birthday import BirthdayFactory

Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion src/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from config import settings
from models import User
from src.models import User
from fastapi import HTTPException

_logger = logging.getLogger(__name__)
Expand Down
7 changes: 4 additions & 3 deletions src/user_router.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from typing import Optional
import jwt
import requests
import datetime
import logging

from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, status
import requests

from config import settings
from models import OauthBody, SettingsInfo, User
from src.models import OauthBody, SettingsInfo, User
from src.user import get_user

router = APIRouter()
Expand Down

0 comments on commit 1febb00

Please sign in to comment.