Exemplo n.º 1
0
    def add_route(self, path: str, route, methods=None) -> None:
        if not inspect.isclass(route):
            route = request_response(route)
            if methods is None:
                methods = ["GET"]

        instance = Path(path, route, protocol="http", methods=methods)
        self.router.routes.append(instance)
Exemplo n.º 2
0
    def add_websocket_route(self, path: str, route: typing.Callable) -> None:
        if not inspect.isclass(route):
            route = asgi_from_websocket(route, self.injector)
        else:
            route.injector = self.injector

        instance = Path(path, route, protocol="websocket")
        self.router.routes.append(instance)
Exemplo n.º 3
0
    def add_route(self,
                  path: str,
                  route: typing.Callable,
                  methods: typing.Sequence[str] = None) -> None:
        if not inspect.isclass(route):
            route = request_response(route)
            if methods is None:
                methods = ("GET", )

        instance = Path(path, route, protocol="http", methods=methods)
        self.router.routes.append(instance)
Exemplo n.º 4
0
    def add_route(
        self,
        path: str,
        route: typing.Callable,
        methods: typing.Sequence[str] = ()) -> None:
        if not inspect.isclass(route):
            route = asgi_from_http(route, self.injector)
            if not methods:
                methods = ("GET", )
        else:
            route.injector = self.injector

        instance = Path(path, route, protocol="http", methods=methods)
        self.router.routes.append(instance)
Exemplo n.º 5
0
import pytest
from starlette.responses import PlainTextResponse
from starlette.routing import Router, Path
from starlette.testclient import TestClient
from starlette.endpoints import HTTPEndpoint


class Homepage(HTTPEndpoint):
    async def get(self, request, username=None):
        if username is None:
            return PlainTextResponse("Hello, world!")
        return PlainTextResponse(f"Hello, {username}!")


app = Router(routes=[Path("/", Homepage), Path("/{username}", Homepage)])

client = TestClient(app)


def test_route():
    response = client.get("/")
    assert response.status_code == 200
    assert response.text == "Hello, world!"


def test_route_kwargs():
    response = client.get("/tomchristie")
    assert response.status_code == 200
    assert response.text == "Hello, tomchristie!"

Exemplo n.º 6
0
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)
Exemplo n.º 7
0
def users(scope):
    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()
Exemplo n.º 8
0
    def add_websocket_route(self, path: str, route) -> None:
        if not inspect.isclass(route):
            route = websocket_session(route)

        instance = Path(path, route, protocol="websocket")
        self.router.routes.append(instance)
Exemplo n.º 9
0
def users(scope):
    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"]),
])


def test_router():
    client = TestClient(app)

    response = client.get("/")
    assert response.status_code == 200
    assert response.text == "Hello, world"

    response = client.post("/")
Exemplo n.º 10
0
        raise HTTPException(status_code=304)

    return asgi


def handled_exc_after_response(scope):
    async def asgi(receive, send):
        response = PlainTextResponse("OK", status_code=200)
        await response(receive, send)
        raise HTTPException(status_code=406)

    return asgi


router = Router(routes=[
    Path("/runtime_error", app=raise_runtime_error),
    Path("/not_acceptable", app=not_acceptable),
    Path("/not_modified", app=not_modified),
    Path("/handled_exc_after_response", app=handled_exc_after_response),
])

app = ExceptionMiddleware(router)
client = TestClient(app)


def test_server_error():
    with pytest.raises(RuntimeError):
        response = client.get("/runtime_error")

    allow_500_client = TestClient(app, raise_server_exceptions=False)
    response = allow_500_client.get("/runtime_error")