import logging, random # , uvicorn from enum import Enum #from datetime import datetime, time, timedelta from fastapi import Body, Cookie, Depends, FastAPI, File, Form, Header, HTTPException, Path, Query, Request, status, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse from fastapi.staticfiles import StaticFiles from functools import lru_cache from pydantic import BaseModel, EmailStr, Field from typing import Dict, List, Optional, Set, Union from sqlalchemy import create_engine, text from sqlalchemy.exc import IntegrityError, OperationalError from . import config from .lib_general import * from .log import * # Import the routers here first: from .routers import api_crud, address, websockets # , items, journals, users from .db_sql import db print('### **** *** ** * The Aether FastAPI API app is starting... * ** *** **** ###') #log = logging.getLogger('root') #log.setLevel(logging.ERROR) # DEBUG > INFO > WARNING > ERROR > CRITICAL #logging.basicConfig( #format='[%(asctime)s] %(levelname)s @ %(module)s.%(funcName)s()#%(lineno)d: %(message)s' #) app = FastAPI() @lru_cache() def get_settings(): return config.Settings() app.mount('/static', StaticFiles(directory='static'), name='static') # Set up each route once the router has been imported app.include_router( api_crud.router, prefix='/crud', tags=['CRUD'], #dependencies=[Depends(get_token_header)], #dependencies=[Depends(get_account_header)], #responses={404: {'description': 'Not found'}}, ) app.include_router( address.router, prefix='/address', tags=['Address'], #dependencies=[Depends(get_token_header)], #dependencies=[Depends(get_account_header)], #responses={404: {'description': 'Not found'}}, ) app.include_router( websockets.router, #prefix='/websocket', tags=['Websockets'], #dependencies=[Depends(get_token_header)], #dependencies=[Depends(get_account_header)], #responses={404: {'description': 'Not found'}}, ) # BEGIN: CORS origins = [ 'http://fastapi.localhost', 'http://localhost', 'http://localhost:5000', 'http://fastapi.localhost:5000', 'https://oneskyit.com', ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_origin_regex='https://.*\.oneskyit\.com', allow_credentials=True, allow_methods=['*'], allow_headers=['*'], #expose_headers=[], #max_age=600, ) # END: CORS @app.on_event('startup') async def startup(): log.setLevel(logging.INFO) # DEBUG, INFO, WARN, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) log.info('FastAPI app is starting up...') #await database.connect() @app.on_event('shutdown') async def shutdown(): log.setLevel(logging.INFO) # DEBUG, INFO, WARN, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) log.info('FastAPI app is shutting down...') #await database.disconnect() #Add the processing time to the response header. @app.middleware('http') async def add_process_time_header(request: Request, call_next): import time start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers['X-Process-Time'] = str(process_time) return response @app.get('/', tags=['Default']) async def get_root(): log.setLevel(logging.INFO) # DEBUG, INFO, WARN, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) log.info(config.settings.APP_NAME) log.setLevel(logging.DEBUG) print('***') log.debug('This is debug') # 10 DEBUG log.info('This is info') # 20 INFO log.warn('This is warn') # 30 WARNING log.warning('This is a warning') # 30 WARNING log.error('This is an error') # 40 ERROR log.exception('This is an exception') # 40 ERROR log.critical('This is critical') # 50 CRITICAL #print('----') #logging.debug('This is debug') # 10 DEBUG #logging.info('This is info') # 20 INFO #logging.warn('This is warn') # 30 WARNING #logging.warning('This is a warning') # 30 WARNING #logging.error('This is an error') # 40 ERROR #logging.exception('This is an exception') # 40 ERROR #logging.critical('This is critical') # 50 CRITICAL print('^^^') return {'hello': 'This is the Aether API using FastAPI.'} # ### TEST TEST TEST ### # @app.get('/quick_test', tags=['Default']) async def quick_test(): log.setLevel(logging.DEBUG) # DEBUG, INFO, WARN, WARNING, ERROR, EXCEPTION, CRITICAL log.debug(locals()) log.info('Getting all accounts...') sql = text( """ SELECT * FROM `account` """ ) try: result = db.execute(sql) except Exception as e: log.error('*** An exception happened. ***') log.error(repr(e)) log.error('***') log.error(str(e)) log.error('^^^ exception ^^^') else: if result.rowcount: records = result.fetchall() log.debug(records) else: log.warning('Something went wrong.') log.info('Got the account list') response = {} response['hello'] = 'This is the Aether API using FastAPI.' response['data'] = records return response # ### TEST TEST TEST ### #