Exemplo n.º 1
0
def create_app():
    c = conf()
    app = FastAPI()
    conf_dict = asdict(c)
    mongo.init_app(app, **conf_dict)
    app.include_router(index.router)
    app.include_router(provider.router)
    # app.include_router(user.router)
    app.include_router(inventory.router)
    return app
Exemplo n.º 2
0
def create_app():
    """
    앱 함수 실행
    :return:
    """
    c = conf()
    app = FastAPI()
    conf_dict = asdict(c)
    db.init_app(app, **conf_dict)
    # 데이터 베이스 이니셜라이즈

    # 레디스 이니셜라이즈

    # 미들웨어 정의
    app.add_middleware(middleware_class=BaseHTTPMiddleware,
                       dispatch=access_control)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=conf().ALLOW_SITE,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    app.add_middleware(TrustedHostMiddleware,
                       allowed_hosts=conf().TRUSTED_HOSTS,
                       except_path=["/health"])

    # 라우터 정의
    app.include_router(index.router)
    app.include_router(auth.router, tags=["Authentication"], prefix="/api")
    if conf().DEBUG:
        app.include_router(services.router,
                           tags=["Services"],
                           prefix="/api",
                           dependencies=[Depends(API_KEY_HEADER)])
    else:
        app.include_router(services.router, tags=["Services"], prefix="/api")
    app.include_router(users.router,
                       tags=["Users"],
                       prefix="/api",
                       dependencies=[Depends(API_KEY_HEADER)])
    return app
Exemplo n.º 3
0
def create_app():
    """
    앱 함수 실행
    :return:
    """
    c = conf()
    app = FastAPI()

    # 데이터 베이스 초기화
    class Item(BaseModel):
        id: int
        name: str
        price: float = 50000
        is_offer: Optional[bool] = None

    my_item: Item = Item(id=1, name='test', price=1000, is_offer=False)

    # print(f'name={my_item.name} price={my_item.price} is_offer={my_item.is_offer}')

    class ModelName(str, Enum):
        alexnet = 'alexnet'
        resnet = 'resnet'
        lenet = 'lenet'


    # 레디스 초기화

    # 미들웨어 정의

    # 라우터 정의

    @app.get('/')
    def read_root():
        return {'Hello': 'World'}

    @app.get('/items/{item_id}')
    def read_item(item_id: int, q: Optional[str] = None):
        return {'item_id': item_id, 'q': q}

    @app.post('/items/{item_id}')
    def update_item(item_id: int, item: Item):
        return {'item_id': item_id, 'item_name': item.name}

    @app.get('/models/{model_name}')
    def get_model(model_name: ModelName):
        if model_name == ModelName.alexnet:
            return {'model_name': model_name, 'message': 'deep learning FTW!'}

        if model_name.value == "lenet":
            return {"model_name": model_name, "message": "LeCNN all the images"}

        return {"model_name": model_name, "message": "Have some residuals"}

    return app
Exemplo n.º 4
0
def create_app():
    """
    앱 함수 실행
    :return:
    """
    c = conf()
    app = FastAPI()
    # 데이터 베이스 이니셜라이즈
    conf_dict = asdict(c)
    db.init_app(app, **conf_dict)
    # 미들웨어 정의
    app.add_middleware(
        CORSMiddleware,
        allow_origins=conf().ALLOW_SITE,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    # 라우터 정의
    app.include_router(data.router)
    app.include_router(recommand.router)
    return app
Exemplo n.º 5
0
def create_app():
    """
    앱 함수 실행
    :return:
    """
    c = conf()
    app = FastAPI()
    conf_dict = asdict(c)
    db.init_app(app, **confg_dict)

    # 데이터베이스 이니셜라이즈

    # 레디스 이니셜라이즈

    # 미들웨어 정의

    # 라우터 정의

    return app
Exemplo n.º 6
0
def create_app():
    """
    앱 함수 실행
    :return:
    """
    c = conf()
    app = FastAPI()
    #클래스를 딕셔너리로 만들어줌
    conf_dict = asdict(c)
    #print(conf_dict)
    db.init_app(app, **conf_dict)
    # 데이터 베이스 이니셜라이즈

    # 레디스 이니셜라이즈

    # 미들웨어 정의

    # 라우터 정의
    app.include_router(index.router)
    return app
Exemplo n.º 7
0
def create_app():
    """
    Run function app
    :return:
    """
    c = conf()
    app = FastAPI()
    conf_dict = asdict(c)
    db.init_app(app, **conf_dict)

    # 데이터베이스 initialize

    # 레디스 initialize

    # 미들웨어 define

    # define router
    app.include_router(index.router)
    app.include_router(auth.router, tags=["Authentication"], prefix="/auth")
    return app
Exemplo n.º 8
0
async def access_control(request: Request, call_next):
    request.state.req_time = D.datetime()
    request.state.start = time.time()
    request.state.inspect = None
    request.state.user = None
    request.state.service = None

    ip = request.headers[
        "x-forwarded-for"] if "x-forwarded-for" in request.headers.keys(
        ) else request.client.host
    request.state.ip = ip.split(",")[0] if "," in ip else ip
    headers = request.headers
    cookies = request.cookies

    url = request.url.path
    if await url_pattern_check(url,
                               EXCEPT_PATH_REGEX) or url in EXCEPT_PATH_LIST:
        response = await call_next(request)
        if url != "/":
            await api_logger(request=request, response=response)
        return response

    try:
        if url.startswith("/api"):
            # api 인경우 헤더로 토큰 검사
            if url.startswith("/api/services"):
                qs = str(request.query_params)
                qs_list = qs.split("&")
                session = next(db.session())
                if not config.conf().DEBUG:
                    try:
                        qs_dict = {
                            qs_split.split("=")[0]: qs_split.split("=")[1]
                            for qs_split in qs_list
                        }
                    except Exception:
                        raise ex.APIQueryStringEx()

                    qs_keys = qs_dict.keys()

                    if "key" not in qs_keys or "timestamp" not in qs_keys:
                        raise ex.APIQueryStringEx()

                    if "secret" not in headers.keys():
                        raise ex.APIHeaderInvalidEx()

                    api_key = ApiKeys.get(session=session,
                                          access_key=qs_dict["key"])

                    if not api_key:
                        raise ex.NotFoundAccessKeyEx(api_key=qs_dict["key"])
                    mac = hmac.new(bytes(api_key.secret_key, encoding='utf8'),
                                   bytes(qs, encoding='utf-8'),
                                   digestmod='sha256')
                    d = mac.digest()
                    validating_secret = str(
                        base64.b64encode(d).decode('utf-8'))

                    if headers["secret"] != validating_secret:
                        raise ex.APIHeaderInvalidEx()

                    now_timestamp = int(D.datetime(diff=9).timestamp())
                    if now_timestamp - 10 > int(
                            qs_dict["timestamp"]) or now_timestamp < int(
                                qs_dict["timestamp"]):
                        raise ex.APITimestampEx()

                    user_info = to_dict(api_key.users)
                    request.state.user = UserToken(**user_info)

                else:
                    # Request User 가 필요함
                    if "authorization" in headers.keys():
                        key = headers.get("Authorization")
                        api_key_obj = ApiKeys.get(session=session,
                                                  access_key=key)
                        user_info = to_dict(
                            Users.get(session=session, id=api_key_obj.user_id))
                        request.state.user = UserToken(**user_info)
                        # 토큰 없음
                    else:
                        if "Authorization" not in headers.keys():
                            raise ex.NotAuthorized()
                session.close()
                response = await call_next(request)
                return response
            else:
                if "authorization" in headers.keys():
                    token_info = await token_decode(
                        access_token=headers.get("Authorization"))
                    request.state.user = UserToken(**token_info)
                    # 토큰 없음
                else:
                    if "Authorization" not in headers.keys():
                        raise ex.NotAuthorized()
        else:
            # 템플릿 렌더링인 경우 쿠키에서 토큰 검사
            cookies[
                "Authorization"] = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTQsImVtYWlsIjoia29hbGFAZGluZ3JyLmNvbSIsIm5hbWUiOm51bGwsInBob25lX251bWJlciI6bnVsbCwicHJvZmlsZV9pbWciOm51bGwsInNuc190eXBlIjpudWxsfQ.4vgrFvxgH8odoXMvV70BBqyqXOFa2NDQtzYkGywhV48"

            if "Authorization" not in cookies.keys():
                raise ex.NotAuthorized()

            token_info = await token_decode(
                access_token=cookies.get("Authorization"))
            request.state.user = UserToken(**token_info)
        response = await call_next(request)
        await api_logger(request=request, response=response)
    except Exception as e:

        error = await exception_handler(e)
        error_dict = dict(status=error.status_code,
                          msg=error.msg,
                          detail=error.detail,
                          code=error.code)
        response = JSONResponse(status_code=error.status_code,
                                content=error_dict)
        await api_logger(request=request, error=error)

    return response
Exemplo n.º 9
0
from dataclasses import asdict

import uvicorn
from fastapi import FastAPI

from app.database.conn import mongo
from app.common.config import conf
from app.routes import index, provider, inventory


def create_app():
    c = conf()
    app = FastAPI()
    conf_dict = asdict(c)
    mongo.init_app(app, **conf_dict)
    app.include_router(index.router)
    app.include_router(provider.router)
    # app.include_router(user.router)
    app.include_router(inventory.router)
    return app


app = create_app()

if __name__ == "__main__":
    uvicorn.run("main:app",
                host="127.0.0.1",
                port=8000,
                reload=conf().PROJ_RELOAD)