示例#1
0
def init_app(application: FastAPI):
    """Configure the application further."""
    msg_format = "[%(name)s] [%(levelname)s] %(message)s"
    if settings.DEBUG:
        asyncio.get_event_loop().set_debug(True)
        warnings.simplefilter("always", ResourceWarning)
        logging.basicConfig(level="DEBUG", format=msg_format)
        application.debug = True
    else:
        logging.basicConfig(level="INFO", format=msg_format)
def create_fastapi_app():
    app = FastAPI()
    app.debug = True
    app.testing = True
    app.secret_key = "testing"
    app.test_client = TestClient(app)
    app.config = {
        "OAUTH2_ERROR_URIS":
        [("invalid_client", "https://a.b/e#invalid_client")]
    }
    return app
示例#3
0
def create_app() -> FastAPI:
    app = FastAPI()
    app.mount('/static', StaticFiles(directory='./static'), name='static')
    app.debug = True

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    app.include_router(
        user_route,
        prefix='/api/v1/user',
        tags=['login'],
    )
    app.include_router(
        project_route,
        prefix='/api/v1/project',
        tags=['project'],
    )
    app.include_router(
        request_route,
        prefix='/api/v1/request',
        tags=['request'],
    )
    app.include_router(
        report_route,
        prefix='/api/v1/project/report',
        tags=['report'],
    )
    app.include_router(
        case_route,
        prefix='/api/v1/project/case',
        tags=['case'],
    )
    app.include_router(
        workstation_route,
        prefix='/api/v1/workstation',
        tags=['workstation'],
    )
    app.include_router(
        overview_route,
        prefix='/api/v1/project/overview',
        tags=['overview'],
    )
    app.include_router(
        editor_route,
        prefix='/api/v1/project/editor',
        tags=['editor'],
    )
    return app
示例#4
0
def get_app():
    app = FastAPI()
    app.debug = True
    app.mount("/static",
              StaticFiles(directory=os.path.join(base_dir, 'static')),
              name="static")

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    return app
示例#5
0
def create_app() -> FastAPI:
    app = FastAPI()
    app.debug = True

    register_tortoise(app, config=TORTOISE_ORM, generate_schemas=True)

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    init_routers(app)

    return app
示例#6
0
def generate_application() -> FastAPI:
    application = FastAPI(title=settings.PROJECT_NAME)
    application.debug = True

    application.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    application.add_event_handler("startup", create_connection)
    application.add_event_handler("shutdown", disconnect)

    application.include_router(api_router, prefix=settings.API_V1_STR)

    return application
示例#7
0
def create_app() -> FastAPI:
    application = FastAPI(__name__)
    application.debug = True

    application.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    application.add_event_handler("startup", create_connection)
    application.add_event_handler("shutdown", disconnect)

    application.include_router(users_router, prefix="/users")
    application.include_router(tag_router, prefix="/tags")
    application.include_router(articles_router, prefix="/articles")
    application.include_router(category_router, prefix="/categorys")

    return application
示例#8
0
def create_app():
    """
    앱 함수 실행cssssssss
    :return:
    """

    c = conf()
    app = FastAPI()
    app.debug = True

    conf_dict = asdict(c)
    init_db()

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

    # 레디스 이니셜라이즈

    # 미들웨어 정의

    # 라우터 정의
    print(get_contents())
    return app
示例#9
0
def generate_application() -> FastAPI:
    application = FastAPI()
    application.debug = True

    application.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    application.add_event_handler("startup", create_connection)
    application.add_event_handler("shutdown", disconnect)

    application.include_router(iehou_router, prefix="/iehou", tags=["iehou"])

    application.include_router(ulink_router, prefix="/ulink", tags=["ulink"])

    application.include_router(user_router, prefix="/user", tags=["users"])

    return application
示例#10
0
from api.v1.router import api_router
from log import setup_logging, logger
from pony.orm import db_session
from api.middleware import AuthenticationBackend
from starlette.middleware.authentication import AuthenticationMiddleware

DEBUG = os.environ.get('ENV', '') == 'dev'
logger.info(f'DEBUG: {DEBUG}')

app_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, app_path)
version = os.environ.get('VERSION', '0.0.1')
logger.info(f'version: {version}')
app = FastAPI(version=version)
app.debug = DEBUG
origins = [
    "*",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(AuthenticationMiddleware, backend=AuthenticationBackend())

app.include_router(api_router, prefix='/api/v1')
from fastapi import FastAPI, WebSocket
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import cv2 as cv
import uvicorn
import time

from tracklib.Tracker import Tracker

app = FastAPI()
# after connecting with websocket set camera to VideoCapture object
app.camera = None
# and set tracker object to manage algorithms
app.tracker = None
app.debug = False

# mount css file
app.mount("/resources", StaticFiles(directory="resources"), name="resources")
# and read html file
html = ""
with open('html/index.html', 'r') as f:
    html = f.read()


@app.get("/")
async def get():
    return HTMLResponse(html)


# websocket endpoint with camera operations
Created on Tue Dec  1 09:25:17 2020

@author: krish
"""

from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
from starlette.middleware.cors import CORSMiddleware
import uvicorn

app = FastAPI()
app.add_middleware(CORSMiddleware,
                   allow_origins=["*"],
                   allow_headers=["*"],
                   allow_methods=["*"])
app.debug = True

html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off"/>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
示例#13
0
# if settings.DEBUG_REQUESTS:
#     # import requests.packages.urllib3.connectionpool as http_client
#     # http_client.HTTPConnection.debuglevel = 1
#     REQUESTS_LOGGER = logging.getLogger("requests")
#     REQUESTS_LOGGER.setLevel(logging.DEBUG)
#     REQUESTS_LOGGER.propagate = True
#     URLLIB3_LOGGER = logging.getLogger("urllib3")
#     URLLIB3_LOGGER.setLevel(logging.DEBUG)

# SOURCE: https://github.com/nwcell/guid_tracker/blob/aef948336ba268aa06df7cc9e7e6768b08d0f363/src/guid/main.py
app = FastAPI(title="Ultron-8 Web Server")

LOGGER.info(f" [DEBUG] {settings.DEBUG}")

app.debug = settings.DEBUG
app.mount(
    "/static",
    StaticFiles(directory=str(Path(__file__).parent / "static")),
    name="static",
)

# CORS
origins = []

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_methods=[settings.BACKEND_CORS_ORIGINS],
    allow_headers=[settings.BACKEND_CORS_ORIGINS],
    allow_credentials=True,
示例#14
0
import os
from fastapi import FastAPI
from fastapi import Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import controller

# FastAPI - это ASGI-фрэймворк. Apache2 не поддерживает ASGI.
# Вэб-серверы (и др.) с поддержвой ASGI указаны по ссылке ниже:
# https://github.com/florimondmanca/awesome-asgi

famd_app = FastAPI()
root_dir = os.path.abspath(__file__).split('main.py')[0]
static_dir = root_dir + 'static'
famd_app.mount("/static", StaticFiles(directory=static_dir), name="static")
famd_app.router.redirect_slashes = False
famd_app.include_router(controller.router, prefix='/phrases')
famd_app.debug = True
templates = Jinja2Templates(directory=f'{root_dir}templates')


# Used template engine Jinja2.
# https://jinja.palletsprojects.com/en/2.11.x/templates/
@famd_app.get('/', response_class=HTMLResponse)
async def root(request: Request):
    service = controller.get_service()
    data = service.get_index_data()
    data['request'] = request
    return templates.TemplateResponse('index.html', data)
示例#15
0
import config

from logging.config import dictConfig

from fastapi import FastAPI
from fastapi.responses import FileResponse

from routers.telegram_bot import router as telegram_api_router
from routers.websockets import router as websocket_router

dictConfig(config.LOGGING_CONFIG)
logger = logging.getLogger(__name__)

app = FastAPI()
app.debug = config.settings.debug

app.include_router(
    telegram_api_router.router,
    tags=['bot'],
    prefix='/bot',
)
app.include_router(
    websocket_router.router,
    tags=['webSocket'],
    prefix='/webSocket',
)


@app.get("/")
async def get():
示例#16
0
def create_app(settings: ApiSettings) -> FastAPI:
    """Create a FastAPI app"""
    paging_client = PaginationTokenClient()
    core_client = CoreCrudClient(pagination_client=paging_client)

    app = FastAPI()
    inject_settings(settings)

    app.debug = settings.debug
    app.include_router(
        create_core_router(core_client, settings), tags=["Core Endpoints"],
        dependencies=[Depends(oauth2_scheme)]
    )
    add_exception_handlers(app, DEFAULT_STATUS_CODES)

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_headers=["*"],
    )

    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request,
                                           exc: RequestValidationError):
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content=jsonable_encoder(
                {
                    "detail": exc.errors(),
                    "query_params": request.query_params,
                    "path_params": request.path_params,
                }
            ),
        )

    if settings.api_extension_is_enabled(ApiExtensions.transaction):
        transaction_client = TransactionsClient()
        app.include_router(
            create_transactions_router(transaction_client, settings),
            tags=["Transaction Extension"], dependencies=[Depends(oauth2_scheme)]
        )

    if settings.add_on_is_enabled(AddOns.tiles):
        tiles_client = TilesClient()
        app.add_api_route(
            name="Get OGC Tiles Resource",
            path="/collections/{collectionId}/items/{itemId}/tiles",
            response_model=TileSetResource,
            response_model_exclude_none=True,
            response_model_exclude_unset=True,
            methods=["GET"],
            endpoint=create_endpoint_with_depends(tiles_client.get_item_tiles, ItemUri),
            tags=["OGC Tiles"],
            dependencies=[Depends(oauth2_scheme)]
        )
        app.include_router(create_tiles_router(), prefix="/titiler", tags=["Titiler"], dependencies=[Depends(oauth2_scheme)])

    config_openapi(app, settings)

    @app.on_event("startup")
    async def on_startup():
        """Create database engines and sessions on startup"""
        app.state.ENGINE_READER = create_engine(
            settings.reader_connection_string, echo=settings.debug
        )
        app.state.ENGINE_WRITER = create_engine(
            settings.writer_connection_string, echo=settings.debug
        )
        app.state.DB_READER = sessionmaker(
            autocommit=False, autoflush=False, bind=app.state.ENGINE_READER
        )
        app.state.DB_WRITER = sessionmaker(
            autocommit=False, autoflush=False, bind=app.state.ENGINE_WRITER
        )

    @app.on_event("shutdown")
    async def on_shutdown():
        """Dispose of database engines and sessions on app shutdown"""
        app.state.ENGINE_READER.dispose()
        app.state.ENGINE_WRITER.dispose()

    @app.middleware("http")
    async def create_db_connection(request: Request, call_next):
        """Create a new database connection for each request"""
        if "titiler" in str(request.url):
            return await call_next(request)
        reader = request.app.state.DB_READER()
        writer = request.app.state.DB_WRITER()
        READER.set(reader)
        WRITER.set(writer)
        resp = await call_next(request)
        reader.close()
        writer.close()
        return resp

    @app.post("/login")
    async def login(body: Login):
        try:
            tokens = await get_tokens(body.username, body.password)

            return tokens
        except Exception as exception:
            raise HTTPException(status_code=400, detail=f"{exception}")

    @app.post("/token")
    async def get_token(form_data: OAuth2PasswordRequestForm = Depends()):
        try:
            username = form_data.username
            password = form_data.password
            tokens = await get_tokens(username, password)
            access_token = tokens["access_token"]

            return {"access_token": access_token, "token_type": "bearer"}
        except Exception as exception:
            raise HTTPException(status_code=400, detail=f"{exception}")

    mgmt_router = APIRouter()

    @mgmt_router.get("/_mgmt/ping")
    async def ping():
        """Liveliness/readiness probe"""
        return {"message": "PONG"}

    app.include_router(mgmt_router, tags=["Liveliness/Readiness"])

    return app