72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding:utf-8 -*-
|
|
# @Filename: base.py
|
|
# @Author: lychang
|
|
# @Time: 2022/5/9 13:33
|
|
import functools
|
|
import json
|
|
import time
|
|
import os
|
|
|
|
from fastapi import FastAPI, Response
|
|
from starlette.middleware.cors import CORSMiddleware
|
|
from api import logger
|
|
|
|
logger.set_log_root_name("private_assistant")
|
|
log_level = os.getenv("LOG_LEVEL", "info")
|
|
if log_level == "debug":
|
|
logger.set_log_level("debug")
|
|
|
|
|
|
def set_logger_config(api_path=None, business_type="api", source=""):
|
|
def decorator(func, p=api_path):
|
|
@functools.wraps(func)
|
|
def wrapper(api=p, *args, **kwargs):
|
|
deal_stage = func.__name__
|
|
if api is None:
|
|
api = deal_stage
|
|
if "{" in api:
|
|
for i in kwargs:
|
|
if i in api:
|
|
api = api.replace("{" + i + "}", str(kwargs[i]))
|
|
x_trace_id = kwargs.get("x_trace_id", None)
|
|
if x_trace_id is None:
|
|
x_trace_id = ""
|
|
_s = time.time()
|
|
logger.set_extra(deal_stage, business_type, api, x_trace_id, source)
|
|
data, status_code, headers = func(*args, **kwargs)
|
|
x_server_time = str(time.time() - _s)
|
|
headers["x-server-time"] = x_server_time
|
|
ret = Response(content=data, status_code=status_code, headers=headers)
|
|
logger.info(f"[{api}] spend time: {x_server_time}.")
|
|
return ret
|
|
|
|
return wrapper
|
|
|
|
return decorator
|
|
|
|
|
|
def response(data: bytes = b'', status_code: int = 200, headers=None) -> (bytes, int, dict):
|
|
code_mapping = {400: "Bad Request",
|
|
404: "The requested resource is not available",
|
|
409: "Original content exists, creation failed",
|
|
206: "Updated success",
|
|
201: "Created success",
|
|
500: "Internal Server Error"
|
|
}
|
|
if headers is None:
|
|
headers = {'Content-Type': 'application/json'}
|
|
error_msg = code_mapping.get(status_code)
|
|
if error_msg:
|
|
data_dict = {"error_code": status_code, "error_msg": error_msg}
|
|
data = json.dumps(data_dict).encode('utf-8')
|
|
|
|
return data, status_code, headers
|
|
|
|
|
|
app = FastAPI()
|
|
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'],
|
|
allow_headers=['*'])
|
|
|
|
|