def main(): description = "Small Web App for ToDo\n\nDash app at \\ \nREST API docs at \\docs\\ " formatter = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(prog="todo", description=description, formatter_class=formatter) parser.add_argument( "--db_path", default=config.DB_PATH, type=str, help= f"path and file name of QSLite database [default: {config.DB_PATH}]", ) parser.add_argument( "--port", default=config.BACKEND_PORT, type=int, help=f"bind socket to this port [default: {config.BACKEND_PORT}]", ) args = parser.parse_args() config.DB_PATH = Path(args.db_path) config.BACKEND_URL_WITH_PORT = f"{config.BACKEND_URL}:{args.port}" app_dash = dash.Dash(__name__, assets_folder="frontend/assets") app_dash.config.suppress_callback_exceptions = True app_dash.layout = view.TaskManager() controller.activate_all(app_dash) app = FastAPI() app.include_router(router) app.mount("/", WSGIMiddleware(app_dash.server)) uvicorn.run(app, host="0.0.0.0", port=args.port, log_level="info")
async def run_backtest(stock_id: int = Form(...), run_id: int = Form(...)): conn = sqlite3.connect(config.DB_FILE) conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute( """ SELECT * FROM backtest_config WHERE run_id = ? """, (run_id, )) bt_config = cursor.fetchone() backtest(stock_id=bt_config['stock_id'], strategy=bt_config['strategy'], conn=conn, start_date=bt_config['bt_start'], end_date=bt_config['bt_end'], open_range=bt_config['open_range'], run_id=bt_config['run_id'], liquidate_time=bt_config['liquidate_time'], set_cash=bt_config['set_cash']) dapp = init_app() app.mount("/", WSGIMiddleware(dapp)) return RedirectResponse( url=f"/backtesting/final_report_{stock_id}_{run_id}", status_code=303)
def initialize_fast_app(gx_wsgi_webapp, gx_app): app = FastAPI( title="Galaxy API", docs_url="/api/docs", openapi_tags=api_tags_metadata, ) add_exception_handler(app) add_galaxy_middleware(app, gx_app) add_request_id_middleware(app) include_all_package_routers(app, 'galaxy.webapps.galaxy.api') wsgi_handler = WSGIMiddleware(gx_wsgi_webapp) app.mount('/', wsgi_handler) return app
def get_application() -> FastAPI: app = FastAPI(title=settings.PROJECT_NAME, debug=settings.DEBUG) app.add_middleware( CORSMiddleware, allow_origins=settings.ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(api_router, prefix="/api") app.mount("/django", WSGIMiddleware(get_wsgi_application())) return app
def initialize_fast_app(gx_webapp): app = FastAPI( title="Galaxy Tool Shed API", description=( "This API allows you to manage the Tool Shed repositories."), docs_url="/api/docs", ) add_exception_handler(app) add_request_id_middleware(app) include_all_package_routers(app, 'tool_shed.webapp.api') wsgi_handler = WSGIMiddleware(gx_webapp) app.mount('/', wsgi_handler) return app
def initialize_fast_app(gx_webapp): app = FastAPI( title="Galaxy Reports API", description= ("This API will give you insights into the Galaxy instance's usage and load. " "It aims to provide data about users, jobs, workflows, disk space, and much more." ), docs_url="/api/docs", ) add_exception_handler(app) add_request_id_middleware(app) include_all_package_routers(app, 'galaxy.webapps.reports.api') wsgi_handler = WSGIMiddleware(gx_webapp) app.mount('/', wsgi_handler) return app
def initialize_fast_app(gx_app): app = FastAPI(openapi_tags=api_tags_metadata) add_exception_handler(app) wsgi_handler = WSGIMiddleware(gx_app) from galaxy.webapps.galaxy.api import ( job_lock, jobs, licenses, roles, tours, ) app.include_router(jobs.router) app.include_router(job_lock.router) app.include_router(licenses.router) app.include_router(roles.router) app.include_router(tours.router) app.mount('/', wsgi_handler) return app
def get_application(): app = FastAPI(title=settings.PROJECT_NAME, debug=settings.DEBUG) app.add_middleware( CORSMiddleware, allow_origins=settings.ALLOWED_HOSTS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(router, prefix="/api") app.include_router( router2, prefix='/v2') #Example Where Multiple Routers can be mapped. app.mount("/Application", WSGIMiddleware(get_wsgi_application())) #FastAPI doesn't have a ASGIMiddleWare --> Version:0.65.1 app.mount("/static", StaticFiles(directory="static"), name="static") #This will include all the static files in the statics folder return app
fig_silhoutte.decode()) plt = graphics.distance_yellowbrick(X=df, y=df[result_col_name], features=features) plt.savefig("fig_distance.png") fig_distance = base64.b64encode( open("fig_distance.png", 'rb').read()) fig_distance = 'data:image/png;base64,{}'.format( fig_distance.decode()) list_png = [ "fig_elbow.png", "fig_balance.png", "fig_silhoutte.png", "fig_distance.png" ] for file in os.listdir('.'): if file.endswith(tuple(list_png)): os.remove(file) msg = "the results metrics have been calculated" else: msg = "a dataset has not been loaded" return msg, fig_elbow, fig_balance, fig_silhoutte, fig_distance app = FastAPI() app.mount(path, WSGIMiddleware(dash_app.server), name="dashboard")
import os from django.core.wsgi import get_wsgi_application from fastapi import FastAPI from fastapi.middleware.wsgi import WSGIMiddleware os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stock_fleets.settings.development") application = get_wsgi_application() from stock_fleets.urls import router as main_router from fastapi.staticfiles import StaticFiles app = FastAPI() app.include_router(main_router, prefix="/api") # use django with uvicorn(asgi) app.mount("/django", WSGIMiddleware(application)) # https://fastapi.tiangolo.com/tutorial/static-files/ app.mount("/static", StaticFiles(directory="static"), name="static")
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from fastapi.middleware.wsgi import WSGIMiddleware from dash_app import app_dash # Now create your regular FASTAPI application app = FastAPI() app.mount("/static", StaticFiles(directory="./app_name/static"), name="static") templates = Jinja2Templates(directory="./app_name/templates") app.mount("/dash", WSGIMiddleware(app_dash.server)) from app_name.views import main, tasks, dash
m.legacy_image_resource, True) return resource_class(_meta=meta, **fields) def create_media_resource(m: MediaModel, verbose=False) -> MediaResourceVerbose: meta = { 'resource_type': 'BlogMedia', 'resource_id': m.resource_id, 'is_verbose': True } # This assumes the Domain model is idential to the Verbose Resource return MediaResourceVerbose(_meta=meta, **m.dict()) def create_category_resource(m: CategoryModel, verbose=False) -> CategoryResourceVerbose: meta = { 'resource_type': 'BlogCategory', 'resource_id': m.resource_id, 'is_verbose': True } # This assumes the Domain model is idential to the Verbose Resource return CategoryResourceVerbose(_meta=meta, **m.dict()) app.mount("/api/rest/v2.0", WSGIMiddleware(flask_app))
app = Flask(__name__) app.register_blueprint(main_blueprint) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI_TEMPLATE.format(**DB_CONFIG) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = 'Fnioz1Cnl2grWSA2MLEbCrBuJjJK0ELB' app.config['UPLOADED_IMAGES_DEST'] = 'static/media' admin.init_app(app) db.init_app(app) Migrate(app, db) Bootstrap(app) login_manager.init_app(app) configure_uploads(app, images) fast_app = FastAPI() fast_app.include_router(routeapi) fast_app.mount("/", WSGIMiddleware(app)) _CREATE_SUPERUSER_HELP = ('Create superuser account.') @app.cli.command('createsuperuser', help=_CREATE_SUPERUSER_HELP) @click.option('--username', prompt=True) @click.option('--email', prompt=True, type=EMAIL) @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True) def create_superuser_command(username, email, password): create_superuser(username, email, password)
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 挂载django所需的全局变量 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) static_dir = os.path.join(base_dir, "djadmin/static/") app.mount("/static", StaticFiles(directory=static_dir), name="static") # 挂载django wsgi app.mount('/django', WSGIMiddleware(djadmin_app)) app.include_router(login_router, prefix="/auth", tags=["auth"]) app.include_router(api.router, prefix="/api", tags=["api"]) @app.get("/ping") async def server_heart_beat(): """ 服务器心跳机制,请求/ping,会返回pong :param :return: "pong" """ return "pong" if __name__ == "__main__":
@app.get("/h5") async def h5_index(): with open(join(PROJECT_PATH, "app", "h5", "index.html"), mode="rb") as f: html_content = f.read() return HTMLResponse(content=html_content, status_code=200) # ex http://host:port/static/xxxx xxx对应的为static文件夹下的路径 app.mount("/static", StaticFiles(directory=PROJECT_STATIC_PATH), name="static") # ex http://host:port/h5/static/xxxx xxx对应的为app/h5/static文件夹下的路径,h5文件夹为前端页面文件 app.mount("/h5/static", StaticFiles(directory=join(PROJECT_PATH, "app", "h5", "static")), name="/h5/static") # 引入flask路由 # 为微信公众号预留的 app.mount("/wx", WSGIMiddleware(flask_app)) # 引入API路由 app.include_router(api_router, prefix="/api", tags=["api"]) # 短链接302跳转 # 匹配不到默认跳转前端H5页面 @app.get("/{id}") async def shortUrl(id: str): originalUrl = GetOriginalUrl(id) if originalUrl: return RedirectResponse(originalUrl, status_code=302) return RedirectResponse(DOMAIN + '/h5#/', status_code=302)
def read_root(response: Response): response.status_code = 302 response.headers["Location"] = "static/index.html" return response @mainApp.post("/v1/login") def read_login(loginData: LoginModel): authResponse = requests.post('http://127.0.0.1:8001/login', json={ "loginId": loginData.loginId, "password": loginData.password }).json() return authResponse mainApp.mount("/static", StaticFiles(directory="static"), name="static") @mainApp.get("/items/{item_id}") def read_item(item_id: int, q: Optional[str] = None): return {"item_id": item_id, "q": q} @mainApp.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} mainApp.mount("/v1", WSGIMiddleware(app))
import requests from typing import List, Tuple, Optional # from dataset import LAN_ENCODING from .models import predictor from .dataapp import data_app, MOUNT_PATH from ml.models import files # files.init_model_files() # app.secret_key = str(uuid.uuid4()) # wsgiapp = app.wsgi_app app = FastAPI() # app.debug = True app.mount(MOUNT_PATH, WSGIMiddleware(data_app.server)) TAG_PRED = predictor.get_tag_predictor( init=False, # test_model=True ) LAN_PRED = predictor.get_lan_predictor( init=True, ) KEYWORD_PRED = predictor.get_keyword_predictor() def info2text(info: dict) -> str:
# ################ # Exception Handler # ################ @APP.exception_handler(pydantic.error_wrappers.ValidationError) async def handle_validation_error(request: Request, exc: pydantic.error_wrappers.ValidationError): """ Handles validation errors. """ return JSONResponse({"message": exc.errors()}, status_code=422) # ################ # Routing # ################ # Include routers. APP.include_router(router, prefix="/v2", tags=["v2"]) # mount the existing Flask app # v1 @ / APP.mount("/", WSGIMiddleware(create_app())) # Running of app. if __name__ == "__main__": uvicorn.run( "app.main:APP", host="127.0.0.1", port=int(os.getenv("PORT", 5000)), log_level="info", )
def get_app(cls, config): app = cls() app.mount("/", WSGIMiddleware(FlaskBiothingsAPI.get_app(config))) return app
user_db = fastusr.db.SQLAlchemyUserDatabase(user_db_model=mdl.UserDB, database=database, users=base.UserTable.__table__) jwt_authentication = fastusr.authentication.JWTAuthentication( secret=SECRET, lifetime_seconds=28800, tokenUrl='/auth/jwt/login') api_users = fastusr.FastAPIUsers(db=user_db, auth_backends=[jwt_authentication], user_model=mdl.User, user_create_model=mdl.UserCreate, user_update_model=mdl.UserUpdate, user_db_model=mdl.UserDB) # Flask AutoIndex module for exploring directories flask_app = Flask(__name__) AutoIndex(flask_app, browse_root=RESULTS_DIR) app.mount('/index', WSGIMiddleware(flask_app)) @app.on_event("startup") async def startup(): await database.connect() @app.on_event("shutdown") async def shutdown(): await database.disconnect() @app.get('/') async def root(): return star.responses.RedirectResponse(url='/docs')
import uvicorn from fastapi import FastAPI from fastapi.middleware.wsgi import WSGIMiddleware from app.database import init_db from app.flask_app import app as flask_app from app.routers import film, reviews, user app = FastAPI(title='Film rating service') app.include_router(film.router) app.include_router(user.router) app.include_router(reviews.router) app.mount('/', WSGIMiddleware(flask_app)) if __name__ == '__main__': # pragma: no cover init_db() uvicorn.run('main:app', host='127.0.0.1', port=8000, reload=True)
def create_visyn_server(*, fast_api_args: Optional[Dict] = {}, start_cmd: Optional[str] = None, workspace_config: Optional[Dict] = None) -> FastAPI: """ Create a new FastAPI instance while ensuring that the configuration and plugins are loaded, extension points are registered, database migrations are executed, ... Keyword arguments: fast_api_args: Optional dictionary of arguments directly passed to the FastAPI constructor. start_cmd: Optional start command for the server, i.e. db-migration exposes commands like `db-migration exec <..> upgrade head`. workspace_config: Optional override for the workspace configuration. If nothing is provided `load_workspace_config()` is used instead. """ from .. import manager from ..settings.model import GlobalSettings from ..settings.utils import load_workspace_config # Load the workspace config.json and initialize the global settings workspace_config = workspace_config if isinstance( workspace_config, dict) else load_workspace_config() manager.settings = GlobalSettings(**workspace_config) logging.config.dictConfig(manager.settings.tdp_core.logging) _log = logging.getLogger(__name__) _log.info("Workspace settings successfully loaded") # Load the initial plugins from ..plugin.parser import get_config_from_plugins, load_all_plugins plugins = load_all_plugins() # With all the plugins, load the corresponding configuration files and create a new model based on the global settings, with all plugin models as sub-models [plugin_config_files, plugin_settings_models] = get_config_from_plugins(plugins) visyn_server_settings = create_model("VisynServerSettings", __base__=GlobalSettings, **plugin_settings_models) # Patch the global settings by instantiating the new settings model with the global config, all config.json(s), and pydantic models manager.settings = visyn_server_settings( **deep_update(*plugin_config_files, workspace_config)) _log.info("All settings successfully loaded") app = FastAPI( debug=manager.settings.is_development_mode, title="Visyn Server", # TODO: Extract version from package.json version="1.0.0", docs_url="/api/docs", openapi_url="/api/openapi.json", redoc_url="/api/redoc", **fast_api_args, ) from ..middleware.exception_handler_middleware import ExceptionHandlerMiddleware from ..middleware.request_context_middleware import RequestContextMiddleware # TODO: For some reason, a @app.exception_handler(Exception) is not called here. We use a middleware instead. app.add_middleware(ExceptionHandlerMiddleware) # Store all globals also in app.state.<manager> to allow access in FastAPI routes via request.app.state.<manager>. app.state.settings = manager.settings # Initialize global managers. from ..plugin.registry import Registry app.state.registry = manager.registry = Registry() manager.registry.init_app(app, plugins) _log.info("Plugin registry successfully initialized") from ..dbmanager import DBManager app.state.db = manager.db = DBManager() manager.db.init_app(app) from ..dbmigration.manager import DBMigrationManager app.state.db_migration = manager.db_migration = DBMigrationManager() manager.db_migration.init_app( app, manager.registry.list("tdp-sql-database-migration")) from ..security.manager import create_security_manager app.state.security = manager.security = create_security_manager() manager.security.init_app(app) from ..id_mapping.manager import create_id_mapping_manager app.state.id_mapping = manager.id_mapping = create_id_mapping_manager() # TODO: Allow custom command routine (i.e. for db-migrations) from .cmd import parse_command_string alternative_start_command = parse_command_string(start_cmd) if alternative_start_command: _log.info(f"Received start command: {start_cmd}") alternative_start_command() _log.info("Successfully executed command, exiting server...") # TODO: How to properly exit here? Should a command support the "continuation" of the server, i.e. by returning True? sys.exit(0) # Load all namespace plugins as WSGIMiddleware plugins from .utils import init_legacy_app, load_after_server_started_hooks namespace_plugins = manager.registry.list("namespace") _log.info( f"Registering {len(namespace_plugins)} legacy namespaces via WSGIMiddleware" ) for p in namespace_plugins: _log.info(f"Registering legacy namespace: {p.namespace}") app.mount(p.namespace, WSGIMiddleware(init_legacy_app(p.load().factory()))) # Load all FastAPI apis router_plugins = manager.registry.list("fastapi_router") _log.info(f"Registering {len(router_plugins)} API-routers") # Load all namespace plugins as WSGIMiddleware plugins for p in router_plugins: _log.info(f"Registering router: {p.id}") app.include_router(p.load().factory()) # load `after_server_started` extension points which are run immediately after server started, # so all plugins should have been loaded at this point of time # the hooks are run in a separate (single) thread to not block the main execution of the server # TODO: Use FastAPI mechanism for that t = threading.Thread(target=load_after_server_started_hooks) t.daemon = True t.start() # TODO: Check mainapp.py what it does and transfer them here. Currently, we cannot mount a flask app at root, such that the flask app is now mounted at /app/ from .mainapp import build_info, health # Call init_app callback for every plugin for p in plugins: p.plugin.init_app(app) # Add middleware to access Request "outside" app.add_middleware(RequestContextMiddleware) # TODO: Move up? app.add_api_route("/health", health) app.add_api_route("/api/buildInfo.json", build_info) return app
"path": "/", "summary": "Landing" }, { "method": "GET", "path": "/status", "summary": "App status" }, { "method": "GET", "path": "/dash", "summary": "Sub-mounted Dash application" }, ] } @app.get("/status") def get_status(): return {"status": "ok"} # A bit odd, but the only way I've been able to get prefixing of the Dash app # to work is by allowing the Dash/Flask app to prefix itself, then mounting # it to root dash_app = create_dash_app(routes_pathname_prefix="/dash/") app.mount("/", WSGIMiddleware(dash_app.server)) if __name__ == "__main__": uvicorn.run(app, port=8000)
timelines: bool = True): """ Getting specific location by id. """ return {'location': request.state.source.get(id).serialize(timelines)} @V2.get('/sources') async def sources(): """ Retrieves a list of data-sources that are availble to use. """ return {'sources': list(data_sources.keys())} # Include routers. APP.include_router(V2, prefix='/v2', tags=['v2']) # mount the existing Flask app # v1 @ / APP.mount('/', WSGIMiddleware(create_app())) # Running of app. if __name__ == '__main__': uvicorn.run( 'app.main:APP', host='127.0.0.1', port=int(os.getenv('PORT', 5000)), log_level='info', )
title="Sample", description="Sample API", version="1.0.0", # docs_url=None, # redoc_url=None, openapi_url="/api/v1/openapi.json", docs_url="/api/v1/docs", redoc_url="/api/v1/redoc") # Middleware Settings app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") async def root() -> JSONResponse: return JSONResponse(status_code=200, content={"message": "Hello World, This is FastAPI"}) # mount Flask API application with FastAPI Endpoint # check at http://localhost:8088/flask_api/ app.mount(path="/flask_api", app=WSGIMiddleware(flask_app)) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8088, log_level='debug')