kinit/kinit-api/main.py
2022-11-16 15:41:24 +08:00

98 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
# @version : 1.0
# @Creaet Time : 2021/10/19 15:47
# @File : main.py
# @IDE : PyCharm
# @desc : 主程序入口
"""
FastApi 更新文档https://github.com/tiangolo/fastapi/releases
FastApi Githubhttps://github.com/tiangolo/fastapi
"""
from fastapi import FastAPI
import uvicorn
from starlette.middleware.cors import CORSMiddleware
from application import settings
from application import urls
from starlette.staticfiles import StaticFiles # 依赖安装pip install aiofiles
import importlib
from core.logger import logger
from core.exception import register_exception
"""
其他配置:
docs_url配置交互文档的路由地址如果禁用则为None默认为 /docs
redoc_url 配置 Redoc 文档的路由地址如果禁用则为None默认为 /redoc
openapi_url配置接口文件json数据文件路由地址如果禁用则为None默认为/openapi.json
"""
app = FastAPI(
title="KInit",
description="本项目基于Fastapi与Vue3+Typescript+Vite3+element-plus的基础项目 前端基于vue-element-plus-admin框架开发",
version="1.0.0"
)
def import_module(modules: list, desc: str):
for module in modules:
if not module:
continue
try:
# 动态导入模块
module_pag = importlib.import_module(module[0:module.rindex(".")])
getattr(module_pag, module[module.rindex(".") + 1:])(app)
except ModuleNotFoundError:
logger.error(f"AttributeError导入{desc}失败,未找到该模块:{module}")
except AttributeError:
logger.error(f"ModuleNotFoundError导入{desc}失败,未找到该模块下的方法:{module}")
"""
添加中间件
"""
import_module(settings.MIDDLEWARES, "中间件")
"""
添加全局事件
"""
import_module(settings.EVENTS, "全局事件")
"""
全局异常捕捉处理
"""
register_exception(app)
"""
跨域解决
"""
if settings.CORS_ORIGIN_ENABLE:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.ALLOW_ORIGINS,
allow_credentials=settings.ALLOW_CREDENTIALS,
allow_methods=settings.ALLOW_METHODS,
allow_headers=settings.ALLOW_HEADERS)
"""
挂在静态目录
"""
if settings.STATIC_ENABLE:
app.mount(settings.STATIC_URL, app=StaticFiles(directory=settings.STATIC_ROOT))
if settings.TEMP_ENABLE:
app.mount(settings.TEMP_URL, app=StaticFiles(directory=settings.TEMP_DIR))
"""
引入应用中的路由
"""
for url in urls.urlpatterns:
app.include_router(url["ApiRouter"], prefix=url["prefix"], tags=url["tags"])
if __name__ == '__main__':
"""
# 启动项目
# reload自动重载项目
# debug调试
# workers启动几个进程
"""
uvicorn.run(app='main:app', host="0.0.0.0", port=9000)