import uvicorn from starlette.exceptions import ExceptionMiddleware, HTTPException from starlette.responses import JSONResponse from starlette.routing import Router, Path, PathPrefix from starlette.middleware.cors import CORSMiddleware # this isn't currently working with starlette 0.3.6 on PyPI, but you can import from github. from demo.apps import homepage, chat app = Router([ Path('/', app=homepage.app, methods=['GET']), PathPrefix('/chat', app=chat.app), ]) app = CORSMiddleware(app, allow_origins=['*']) app = ExceptionMiddleware(app) def error_handler(request, exc): return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) app.add_exception_handler(HTTPException, error_handler) if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000)
def mount(self, path: str, app: ASGIApp, methods=None) -> None: prefix = PathPrefix(path, app=app, methods=methods) self.router.routes.append(prefix)
return Response("All users", media_type="text/plain") def user(scope): content = "User " + scope["kwargs"]["username"] return Response(content, media_type="text/plain") def staticfiles(scope): return Response("xxxxx", media_type="image/png") app = Router([ Path("/", app=homepage, methods=["GET"]), PathPrefix("/users", app=Router([Path("", app=users), Path("/{username}", app=user)])), PathPrefix("/static", app=staticfiles, methods=["GET"]), ]) @app.route("/func") def func_homepage(request): return Response("Hello, world!", media_type="text/plain") @app.websocket_route("/ws") async def websocket_endpoint(session): await session.accept() await session.send_text("Hello, world!") await session.close()
import os from starlette.applications import Starlette from starlette.exceptions import ExceptionMiddleware from starlette.middleware.wsgi import WSGIMiddleware from starlette.routing import Router, Path, PathPrefix import uvicorn from wsgi import application from .asgi_app import app as asgi_app app = Router([ PathPrefix("/v2", app=asgi_app), PathPrefix("", app=WSGIMiddleware(application)), ]) DEBUG = os.getenv("DJANGO_DEBUG", "True") if DEBUG == "True": app = ExceptionMiddleware(app, debug=True) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)