return AuthCredentials(credentials), ExtendedUser(username, is_admin) webgui_config = Config("configuration/webgui.env") # Note: PutSomethingRandomHere is the default value in the shipped configuration file. # The app will not start with this value, forcing the users to set their onw secret # key. Therefore, the value is used as default here as well. SECRET_KEY = webgui_config("SECRET_KEY", cast=Secret, default="PutSomethingRandomHere") WEBGUI_PORT = webgui_config("PORT", cast=int, default=8000) WEBGUI_HOST = webgui_config("HOST", default="0.0.0.0") DEBUG_MODE = webgui_config("DEBUG", cast=bool, default=True) app = Starlette(debug=DEBUG_MODE) # Don't check the existence of the static folder because the wrong parent folder is used if the # source code is parsed by sphinx. This would raise an exception and lead to failure of sphinx. app.mount("/static", StaticFiles(directory="webinterface/statics", check_dir=False), name="static") app.add_middleware(AuthenticationMiddleware, backend=SessionAuthBackend()) app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, session_cookie="mercure_session") app.mount("/modules", modules.modules_app) app.mount("/queue", queue.queue_app) async def async_run(cmd): """Executes the given command in a way compatible with ayncio.""" proc = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() return proc.returncode, stdout, stderr ###################################################################################
username = request.path_params['username'] return PlainTextResponse('Hello, %s!' % username) async def websocket_endpoint(websocket): await websocket.accept() await websocket.send_text('Hello, websocket!') await websocket.close() async def start_up(): print("Ready to Go!") async def shutting_down(): print("Shutting Down Everything!") routes = [ Route('/', homepage), Route('/user/me', user_me), Route('/user/{username}', user), WebSocketRoute('/ws', websocket_endpoint), Mount('/static', StaticFiles(directory="static")), ] app = Starlette(debug=True, routes=routes, on_startup=[start_up], on_shutdown=[shutting_down])
from typing import List load_dotenv() # getting info about app version from package.json with open("./package.json") as json_file: package_json = json.load(json_file) app = FastAPI( title="Notes Manager", description=package_json["description"], version=package_json["version"], ) app.mount("/node_modules", StaticFiles(directory="node_modules"), name="node_modules") app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") class Note(BaseModel): id: str = None content: str title: str created: int = None updated: int = None _score: int = None tags: List[str] = []
allow_headers=["*"], allow_methods=["*"], allow_credentials=True, ) ] routes = [ Route("/", home), Route("/redirect", redirect_page), Route("/get-access-token", fetch_access_token, methods=["POST"]), Route("/{provider}/get-emails", get_emails, methods=["POST"]), Route("/{provider}/get-email-content", get_email_content, methods=["POST"]), Mount( "/static", StaticFiles( directory=os.path.join(BASE_DIR, "gsheet_service", "static")), name="static", ), Route("/oauth-callback", oauth_callback, methods=["GET"]), Mount("/oauth", routes=oauth_views.routes), Mount("/media", routes=media_views.routes), Mount("/scheduler", routes=scheduler_views.routes), Mount("/sc", routes=spell_check_views.routes), Mount("", routes=sheet_views.routes), # Route("/secrets", secrets), ] on_startup = [] + sheet_views.on_startup on_shutdown = [] + sheet_views.on_shutdown app = Starlette(
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter from django.conf import settings from django.core.asgi import get_asgi_application from starlette.responses import Response from starlette.staticfiles import StaticFiles from karrot.utils.asgi_utils import CommunityProxy, AllowedHostsAndFileOriginValidator, cached from karrot.subscriptions.consumers import WebsocketConsumer, TokenAuthMiddleware api_app = get_asgi_application() api_prefixes = ['/api/', '/docs/', '/api-auth/'] media_app = StaticFiles(directory=settings.MEDIA_ROOT) frontend_app = None static_app = None community_proxy_app = None if settings.DEBUG: # in DEBUG mode they are served by the main api app via config/urls.py api_prefixes += ['/static/'] else: static_app = StaticFiles(directory=settings.STATIC_ROOT) if settings.FRONTEND_DIR: frontend_app = StaticFiles(directory=settings.FRONTEND_DIR, html=True) if settings.PROXY_DISCOURSE_URL: community_proxy_app = CommunityProxy(proxy_url=settings.PROXY_DISCOURSE_URL)
from itsdangerous import BadSignature, Signer from starlette.applications import Starlette from starlette.endpoints import HTTPEndpoint from starlette.middleware.cors import CORSMiddleware from starlette.middleware.gzip import GZipMiddleware from starlette.requests import Request from starlette.responses import FileResponse, HTMLResponse, PlainTextResponse, Response from starlette.staticfiles import StaticFiles from . import config, utils __all__ = ['route', 'run'] app: Any = Starlette(debug=config.DEBUG) app.mount(config.STATIC_ROUTE, StaticFiles(directory=config.STATIC_DIRECTORY), name=config.STATIC_NAME) app.add_middleware(GZipMiddleware) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) cookie_signer = Signer(config.SECRET_KEY) routes: List[Dict[str, Any]] = [] F = TypeVar('F', bound=Callable)
@app.delete("/api/query/{job_id}", response_model=StatusSchema) def query_remove(job_id: str) -> StatusSchema: job = db.get_job(JobId(job_id)) if job.userid != "unknown": db.remove_query(JobId(job_id)) return StatusSchema(status="ok") @app.get("/recent", include_in_schema=False) @app.get("/status", include_in_schema=False) @app.get("/query", include_in_schema=False) @app.get("/ratelimits", include_in_schema=False) @app.get("/about", include_in_schema=False) def serve_index_sub() -> FileResponse: return FileResponse("mqueryfront/build/index.html") app.mount( "/", StaticFiles( directory=os.path.join(os.path.dirname(__file__), "mqueryfront", "build"), html=True, ), ) if __name__ == "__main__": uvicorn.run(app)
from fastapi import FastAPI, File, UploadFile from starlette.responses import HTMLResponse, StreamingResponse import os import request_predict from starlette.templating import Jinja2Templates from starlette.requests import Request from starlette.staticfiles import StaticFiles import cv2 import io app = FastAPI() templates = Jinja2Templates(directory="templates") app.mount('/uploadfiles/static', StaticFiles(directory='static'), name='static') @app.post("/uploadfiles/") async def create_upload_files(request: Request, files: List[UploadFile] = File(...)): fnames = [] bins = [] for f in files: fnames.append(f.filename) bins.append(f.file.read()) endpoint = os.getenv("ENDPOINT") rets = request_predict.request_bins(bins, endpoint) #save images
dest="port", type=int, help="The port the webserver should be run on.", default=None) return parser app = FastAPI(title="SeqColAPI", description="An API for Sequence Collections", version=seqcolapi_version) STATIC_DIRNAME = "static" STATIC_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), STATIC_DIRNAME) app.mount("/" + STATIC_DIRNAME, StaticFiles(directory=STATIC_PATH), name=STATIC_DIRNAME) TEMPLATES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates") templates = Jinja2Templates(directory=TEMPLATES_PATH) @app.get("/test") async def root(): return Response(content="Welcome to the test seqcol server.") @app.get("/") @app.get("/index") async def index(request: Request): """
import os from fastapi import FastAPI from fastapi import Query from elasticsearch import Elasticsearch from starlette.staticfiles import StaticFiles host = os.environ.get('ELASTICSEARCH_URL', 'localhost') es = Elasticsearch(host) index_name = 'cdli-catalogue' app = FastAPI() app.mount('/vue', StaticFiles(directory='vue'), name='static') @app.get('/') async def hello(): return {'about': 'CDLI API service'} @app.get('/search') def search( q: str = Query(..., title='Query string', description='String to search for in the database.', min_length=2), skip: int = 0, limit: int = 8, ): 'General text search.' return es.search(index=index_name, q=q)
import aioredis from fastapi import FastAPI, HTTPException #from fastapi.responses import HTMLResponse #from .routers import login, messages #from .services import util, statsd from .services import util, redis from starlette.websockets import WebSocket from starlette.requests import Request from starlette.staticfiles import StaticFiles from starlette.responses import RedirectResponse, JSONResponse, HTMLResponse app = FastAPI() # This is only really for serving test files. We would probably serve static # files from S3 directly. app.mount("/static", StaticFiles(directory="/app/app/static"), name="static") #app.include_router(login.router, prefix="/login") #app.include_router(messages.router, prefix="/messages") 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>
import base64 import urllib.parse import sys import uvicorn import irodshelper app = Starlette() app.debug = True app.add_middleware(GZipMiddleware, minimum_size=1000) app.add_middleware(SessionMiddleware, secret_key="t6dX0AkQOcJ7+6X2c1JUoAzhZ27LHr6QS+8DuYOye1E=") # website >> app.mount('/static', StaticFiles(directory="client/build/static")) @app.route('/') def index(request): return FileResponse("./client/build/index.html") @app.route('/favicon.ico') def favicon(request): return FileResponse("./client/build/favicon.ico") @app.route('/manifest.json') def manifest(request): return FileResponse("./client/build/manifest.json")
exception_handlers = {HTTPException: http_exception, ClientError: client_error} _middlewares = [ Middleware(DBSessionMiddleware, database_url=DATABASE_URL), Middleware(AuthenticationMiddleware, backend=BasicAuthBackend(), on_error=on_auth_error) ] static_path = Path(__file__).parent.parent / 'static' templates_path = Path(__file__).parent.parent / 'templates' app = Starlette(debug=True, routes=[ Mount('/users', routes=user_routes), Mount('/snippets', routes=snippet_routes), Mount('/static', StaticFiles(directory=f'{static_path.absolute()}'), name='static'), WebSocketRoute('/feed', Feed), Route('/schema', endpoint=openapi_schema, include_in_schema=False) ], middleware=_middlewares, exception_handlers=exception_handlers) app.state.templates = Jinja2Templates(directory=f'{templates_path.absolute()}') # websocket handling app.state.channels = CHANNELS
@api.get("/") async def webui_redir(): return RedirectResponse(url="/landing/", status_code=302) # served by nginx if Path(landing_dir("index.html")).is_file(): logger.info("[email protected] - Registering landing routers") @api.get("/landing/") async def web_index(): return FileResponse(landing_dir("index.html")) api.mount("/landing", StaticFiles(directory=landing_dir())) # served by nginx if Path(webui_dir("dist")).is_dir(): logger.info("[email protected] - Registering webui routers") # served by nginx @api.get("/webui") async def webui_redir(): return RedirectResponse(url="/webui/", status_code=302) # served by nginx w/ slight rewrite @api.get("/webui/assets") async def webui_index(): return FileResponse(webui_dir(join("dist", "index.html")))
'dirs': [dict(d) for d in dirs], 'files': [dict(f) for f in files], } def ensure_existed(node): if not node: raise HTTPException(404, 'Not found') def ensure_type(node, type): if node.type != type: raise HTTPException(400, f'Node is {node.type} instead of {type}') def ensure_is_file(node): ensure_type(node, 'file') def ensure_is_dir(node): ensure_type(node, 'dir') def ensure_me(request): user = get_user(request) if user['username'] != 'fans656': raise HTTPException(401, 'require fans656 login') app.mount('/', StaticFiles(directory='../frontend/out/', html=True))
from starlette.responses import HTMLResponse from starlette.routing import Mount from starlette.staticfiles import StaticFiles from src import views from src.database import prepare_database from src.logs import setup_logging from src.settings import Settings THIS_DIR = Path(__file__).parent.resolve() routes = [ APIRoute('/', views.index, name='index', response_class=HTMLResponse), APIRoute('/list/', views.games_list, name='index', response_class=HTMLResponse), Mount('/static', StaticFiles(directory=THIS_DIR / 'static'), name='static'), ] settings = Settings() engine = prepare_database(delete_existing=False, settings=settings) app = FastAPI(debug=settings.debug, routes=routes) setup_logging() # For running locally if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000)
def create_application( database_url: str, secret_key: str, jwt_key: typing.Union[None, bytes, JWKRepr] = None, jwt_signature_algorithm: str = "RS256", jwt_signature_params: typing.Dict[str, str] = {}, jwt_encryption_algorithm: str = "RS256", jwt_encryption_params: typing.Dict[str, str] = {}, debug: bool = False, max_pool_workers: int = 10, jwt_ttl: timedelta = timedelta(seconds=3600), region: str = "mars-east-1", prepended_routes: typing.Iterable[BaseRoute] = [], ): from .views import admin as admin_views from .views import index as index_views from .views import oauth2 as oauth2_views from .views import pools as pools_views logging.basicConfig( level=logging.DEBUG if debug else logging.INFO, force=True, ) if max_pool_workers > 0: executor.executor = concurrent.futures.ThreadPoolExecutor( max_workers=max_pool_workers) session_factory.configure(bind=sa.create_engine(database_url), ) if jwt_key is None: jwt_key = generate_jwk(jwt_encryption_algorithm) jwt_public_key = jwt_key if isinstance(jwt_key, dict): if "kid" not in jwt_key: jwt_key = dict(jwt_key) jwt_key["kid"] = generate_key(16) jwt_public_key = build_jwt_public_key_from_private_key(jwt_key) jwt_config = JWTConfiguration( key=jwt_key, public_key=jwt_public_key, signature_algorithm=jwt_signature_algorithm, signature_params=jwt_signature_params, encryption_algorithm=jwt_encryption_algorithm, encryption_params=jwt_encryption_params, issuer="", ttl=jwt_ttl, ) routes: typing.List[BaseRoute] = list(prepended_routes) routes += [ Mount( "/static", app=StaticFiles(directory=str(basedir / "static")), name="static", ), Mount( "/admin", name="admin", app=admin_views.routes, ), Mount( "/oauth2", name="oauth2", app=oauth2_views.routes, ), Route( "/logout", oauth2_views.LogoutEndpoint, ), Mount( "/{pool}", name="pools", app=apply_middlewares( pools_views.routes, middleware=[ Middleware(PoolDetectionMiddleware), Middleware(AuthenticationMiddleware, backend=SessionAuthenticationBackend()), ], ), ), Mount("/", index_views.routes), ] app = Starlette( debug=debug, routes=routes, middleware=[ Middleware(RequestTimeMiddleware), Middleware(SQLAlchemyMiddleware), Middleware(SessionMiddleware, secret_key=secret_key), Middleware(TemplateShortcutMiddleware), ], on_shutdown=[ lambda: (executor.executor.shutdown(wait=True) if executor.executor is not None else None), ], ) app.state.jwt_config = jwt_config app.state.region = region app.state.templates = Jinja2Templates(directory=str(basedir / "templates")) app.state.kdf = PasswordHasher() app.state.uuidgen = lambda: str(uuid.uuid4()) return app
'tailwind': TAILWIND, 'quasar': QUASAR, 'quasar_version': QUASAR_VERSION, 'highcharts': HIGHCHARTS, 'aggrid': AGGRID, 'aggrid_enterprise': AGGRID_ENTERPRISE, 'static_name': STATIC_NAME, 'component_file_list': component_file_list, 'no_internet': NO_INTERNET } logging.basicConfig(level=LOGGING_LEVEL, format='%(levelname)s %(module)s: %(message)s') app = Starlette(debug=DEBUG) app.mount(STATIC_ROUTE, StaticFiles(directory=STATIC_DIRECTORY), name=STATIC_NAME) app.mount('/templates', StaticFiles(directory=current_dir + '/templates'), name='templates') app.add_middleware(GZipMiddleware) if SSL_KEYFILE and SSL_CERTFILE: app.add_middleware(HTTPSRedirectMiddleware) def initial_func(request): wp = WebPage() Div(text='JustPy says: Page not found', classes='inline-block text-5xl m-3 p-3 text-white bg-blue-600', a=wp) return wp
homepage_html = get_homepage_html(__location__ + "/../") @app.get("/", include_in_schema=False) def root(request: Request, templates=deps.depends(Jinja2Templates)): return templates.TemplateResponse( "page.html", { "content": homepage_html, "request": request, }, ) @app.get("/is/{possible_seven}", response_model=IsSevenResult) @lru_cache(maxsize=128) def check(possible_seven: str, checkers=deps.depends(Collection[SevenChecker])): # type: ignore for checker in checkers: result = checker(possible_seven) if result.isseven: return result return nope("We tried. This doesn't seem to be seven") # If no other route matches assume that it might be a static file app.mount("/", StaticFiles(directory=__location__ + "/../static_assets"), name="static")
templates = Jinja2Templates(directory="templates") async def homepage(request): return templates.TemplateResponse("mountains.html", {"request": request}) # @app.route("/upload", methods=["POST"]) async def upload(request): data = await request.form() print(data) image_data = await (data["file"].read()) result = brain.predict(image_data) return templates.TemplateResponse( "mountains.html", { "request": request, "label": result["label"], "confidence": result["confidence"], }, ) routes = [ Route("/", endpoint=homepage), Route("/upload", endpoint=upload, methods=["POST"]), Mount("/static", StaticFiles(directory="static"), name="static"), ] app = Starlette(debug=True, routes=routes)
async def homepage(request): ''' Home page ''' return templates.TemplateResponse('index.html', {'request': request}) async def chat_window(request): ''' Chat window ''' return templates.TemplateResponse('chat.html', {'request': request}) routes = [ Route('/', endpoint=homepage), Route('/chat', endpoint=chat_window), Mount('/static', StaticFiles(directory='app/static'), name='static') ] # Class vocabulary classes = ['account_blocked','application_status','apr','balance','bill_balance','bill_due','card_declined','credit_limit','credit_limit_change','credit_score','damaged_card','direct_deposit','exchange_rate','expiration_date','freeze_account','improve_credit_score','insurance','insurance_change','interest_rate','international_fees','min_payment','new_card','oos','order_checks','pay_bill','pin_change','redeem_rewards','replacement_card_duration','report_fraud','report_lost_card','rewards_balance','rollover_401k','taxes','transactions','transfer'] # ULMFiT async def setup_learner(): ''' Load model ''' learn = load_learner(path, 'models/ULMFiT_classifier_model_cpu.pkl') return learn # OOS async def setup_learner_oos(): ''' Load OOS model '''
from quetz import auth_github from quetz import config from quetz.dao import Dao from .database import SessionLocal from quetz import rest_models from quetz import db_models from quetz import authorization app = FastAPI() app.add_middleware( SessionMiddleware, secret_key=config.QUETZ_SESSION_SECRET, https_only=config.QUETZ_SESSION_HTTPS_ONLY) app.mount('/static', StaticFiles(directory='static', html=True), name='static') app.include_router(auth_github.router) # Dependency injection def get_db(): db = SessionLocal() try: yield db finally: db.close() def get_dao(db: Session = Depends(get_db)):
import os from fastapi import FastAPI, HTTPException from starlette.requests import Request from starlette.responses import JSONResponse from starlette.staticfiles import StaticFiles from .. import constants from .routes import router app = FastAPI(title="API docs of ReArq") app.mount( "/static", StaticFiles(directory=os.path.join(constants.BASE_DIR, "rearq", "server", "static")), name="static", ) app.include_router(router) @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content={"msg": exc.detail}, )
def padding(request): """ Dynamically generated data, maximum 50MB. """ size = min(50000000, request.path_params["size"]) return PlainTextResponse("Z" * size) @app.websocket_route("/ws") async def ws(websocket): """ WebSocket echo endpoint. """ if "chat" in websocket.scope["subprotocols"]: subprotocol = "chat" else: subprotocol = None await websocket.accept(subprotocol=subprotocol) try: while True: message = await websocket.receive_text() await websocket.send_text(message) except WebSocketDisconnect: pass app.mount("/httpbin", WsgiToAsgi(httpbin.app)) app.mount("/", StaticFiles(directory=os.path.join(ROOT, "htdocs"), html=True))
db._state.reset() def get_db(db_state=Depends(reset_db_state)): try: db.connect() yield finally: if not db.is_closed(): db.close() app = FastAPI() app.mount("/static", StaticFiles(directory="stilio/frontend/static"), name="static") templates = Jinja2Templates(directory="stilio/frontend/templates") @app.on_event("startup") def startup(): db.connect(reuse_if_open=True) @app.on_event("shutdown") def shutdown(): if not db.is_closed(): db.close()
dir_html=''' <html> <body> <dir> <ul> {% for user in id %} <br>{{ user }}</br> <a href="/files/1?q={{q}}/{{ user }}">{{ user }}</a> {% endfor %} </ul> {{ id1 }} </body> </html> ''' app = FastAPI() app.mount('/static', StaticFiles(directory=location), name='static') templates = Jinja2Templates(directory="templates") @app.get("/dir") def read_root(): #return {"Hello": "World"} return RedirectResponse(url='/files/1?q=') @app.get("/files/{item_id}") def read_files(request:Request, item_id: str, q: str = None): #return {"item_id": item_id, "q": q} data=['hello','china'] print('q before:') q0=location+'/'+q
"description": "Методы для получения информации про игровые статики" }]) # Middlewares use_content_type(app) origins = ["http://localhost:3000", "*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(character.router, prefix="/characters", tags=['Персонажи']) app.include_router(guild.router, prefix="/guild", tags=['Гильдия']) app.include_router(mythic.router, prefix="/mythic", tags=['Мифик']) app.include_router(posts.router, prefix="/posts", tags=['Записи']) app.include_router(btusers.router, prefix="/users", tags=['Пользователи']) app.include_router(files.router, prefix="/files", tags=['Файлы']) app.include_router(statics_router, prefix="/statics", tags=['Статики']) app.mount("/static", StaticFiles(directory="static")) # Entry point if __name__ == "__main__": uvicorn.run("main:app", host=app_server, port=app_port, reload=True)
def __init__( self, *, title=None, version=None, openapi=None, openapi_route="/schema.yml", static_dir="static", static_route="/static", templates_dir="templates", auto_escape=True, secret_key="NOTASECRET", enable_hsts=False, ): self.secret_key = secret_key self.title = title self.version = version self.openapi_version = openapi self.static_dir = Path(os.path.abspath(static_dir)) self.static_route = static_route self.templates_dir = Path(os.path.abspath(templates_dir)) self.built_in_templates_dir = Path( os.path.abspath(os.path.dirname(__file__) + "/templates")) self.routes = {} self.schemas = {} self.session_cookie = "Responder-Session" self.hsts_enabled = enable_hsts self.static_files = StaticFiles(directory=str(self.static_dir)) self.apps = {self.static_route: self.static_files} self.formats = get_formats() # Make the static/templates directory if they don't exist. for _dir in (self.static_dir, self.templates_dir): os.makedirs(_dir, exist_ok=True) # Cached requests session. self._session = None self.background = BackgroundQueue() if self.openapi_version: self.add_route(openapi_route, self.schema_response) self.default_endpoint = None self.app = self.dispatch self.add_middleware(GZipMiddleware) if self.hsts_enabled: self.add_middleware(HTTPSRedirectMiddleware) # Jinja enviroment self.jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader( [str(self.templates_dir), str(self.built_in_templates_dir)], followlinks=True, ), autoescape=jinja2.select_autoescape( ["html", "xml"] if auto_escape else []), ) self.jinja_values_base = {"api": self} # Give reference to self.
from starlette.middleware.cors import CORSMiddleware from starlette.responses import HTMLResponse, JSONResponse from starlette.staticfiles import StaticFiles #set url # export_file_url = 'https://drive.google.com/uc?export=download&id=1ZZ_2JRe39KcgqGu75watpeLOtQGfeDPA' model_config_name = 'app/models/model.config' model_file_name = 'app/models/best_model.h5' classes = ['0', '1', '2', '3'] path = Path(__file__).parent img_size = 224 app = Starlette() app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type']) app.mount('/static', StaticFiles(directory='app/static')) async def download_file(url, dest): if dest.exists(): return async with aiohttp.ClientSession() as session: async with session.get(url) as response: data = await response.read() with open(dest, 'wb') as f: f.write(data) async def setup_learner(): # await download_file(export_file_url, path / export_file_name) try: #learn = load_learner(path, export_file_name)
status_code=status.HTTP_404_NOT_FOUND, detail=f"{channel.name}/{path} not found", ) # from starlette.responses import FileResponse, HTMLResponse # @app.get("/.*", include_in_schema=False) # def root(): # with open("../quetz_frontend/dist/index.html") as fi: # index_content = fi.read() # return HTMLResponse(index_content) if os.path.isfile("../quetz_frontend/dist/index.html"): logger.info("dev frontend found") app.mount("/", StaticFiles(directory="../quetz_frontend/dist", html=True), name="frontend") elif os.path.isfile(f"{sys.prefix}/share/quetz/frontend/index.html"): logger.info("installed frontend found") app.mount( "/", StaticFiles(directory=f"{sys.prefix}/share/quetz/frontend/", html=True), name="frontend", ) else: logger.info("basic frontend") basic_frontend_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), "basic_frontend") app.mount("/", StaticFiles(directory=basic_frontend_dir, html=True),