1 Star 0 Fork 13

lyh/fastapistuday

forked from 雷子/fastapistuday 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.py 1.75 KB
一键复制 编辑 原始数据 按行查看 历史
雷子 提交于 2022-01-12 21:44 . 实战项目合并到主干
from fastapi import FastAPI,Request
from aioredis import create_redis_pool, Redis
from routers.user import usersRouter
from routers.course import courseRouter
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from config import *
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
#
# # 前端页面url
# origins = [
# "http://localhost.tiangolo.com",
# "http://localhost:8080",
# "http://192.168.31.35",
# ]
#
# # 后台api允许跨域
# app.add_middleware(
# CORSMiddleware,
# allow_origins=origins,
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
async def get_redis_pool() -> Redis:
if EVENT=="test":
redis = await create_redis_pool(f"redis://:@" + testredishost + ":" + testredisport + "/" + testredisdb + "?encoding=utf-8")
else:
redis = await create_redis_pool(f"redis://:@" + redishost + ":" + redisport + "/" + redisdb + "?encoding=utf-8")
return redis
@app.on_event("startup")
async def startup_event():
app.state.redis = await get_redis_pool()
@app.on_event("shutdown")
async def shutdown_event():
app.state.redis.close()
await app.state.redis.wait_closed()
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
content=jsonable_encoder({"message": exc.errors(), "code": 421}),
)
app.include_router(usersRouter, prefix="/user", tags=['users'])
app.include_router(courseRouter, prefix='/course', tags=['course'])
if __name__ == '__main__':
import uvicorn
uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/linyaofai/fastapistuday.git
git@gitee.com:linyaofai/fastapistuday.git
linyaofai
fastapistuday
fastapistuday
master

搜索帮助