How to use the starlette.routing.Route function in starlette

To help you get started, we’ve selected a few starlette examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github encode / starlette / tests / test_routing.py View on Github external
return Response(content, media_type="text/plain")


def user_no_match(request):  # pragma: no cover
    content = "User fixed no match"
    return Response(content, media_type="text/plain")


app = Router(
    [
        Route("/", endpoint=homepage, methods=["GET"]),
        Mount(
            "/users",
            routes=[
                Route("/", endpoint=users),
                Route("/me", endpoint=user_me),
                Route("/{username}", endpoint=user),
                Route("/nomatch", endpoint=user_no_match),
            ],
        ),
        Mount("/static", app=Response("xxxxx", media_type="image/png")),
    ]
)


@app.route("/func")
def func_homepage(request):
    return Response("Hello, world!", media_type="text/plain")


@app.route("/func", methods=["POST"])
def contact(request):
github encode / starlette / tests / test_routing.py View on Github external
def user_no_match(request):  # pragma: no cover
    content = "User fixed no match"
    return Response(content, media_type="text/plain")


app = Router(
    [
        Route("/", endpoint=homepage, methods=["GET"]),
        Mount(
            "/users",
            routes=[
                Route("/", endpoint=users),
                Route("/me", endpoint=user_me),
                Route("/{username}", endpoint=user),
                Route("/nomatch", endpoint=user_no_match),
            ],
        ),
        Mount("/static", app=Response("xxxxx", media_type="image/png")),
    ]
)


@app.route("/func")
def func_homepage(request):
    return Response("Hello, world!", media_type="text/plain")


@app.route("/func", methods=["POST"])
def contact(request):
    return Response("Hello, POST!", media_type="text/plain")
github encode / starlette / tests / test_exceptions.py View on Github external
def not_modified(request):
    raise HTTPException(status_code=304)


class HandledExcAfterResponse:
    async def __call__(self, scope, receive, send):
        response = PlainTextResponse("OK", status_code=200)
        await response(scope, receive, send)
        raise HTTPException(status_code=406)


router = Router(
    routes=[
        Route("/runtime_error", endpoint=raise_runtime_error),
        Route("/not_acceptable", endpoint=not_acceptable),
        Route("/not_modified", endpoint=not_modified),
        Route("/handled_exc_after_response", endpoint=HandledExcAfterResponse()),
        WebSocketRoute("/runtime_error", endpoint=raise_runtime_error),
    ]
)


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


def test_not_acceptable():
    response = client.get("/not_acceptable")
    assert response.status_code == 406
    assert response.text == "Not Acceptable"
github scoutapp / scout_apm_python / tests / integration / test_starlette_py36plus.py View on Github external
pass

        async def async_noop():
            pass

        tasks = BackgroundTasks()
        tasks.add_task(sync_noop)
        tasks.add_task(async_noop)

        return PlainTextResponse("Triggering background jobs", background=tasks)

    routes = [
        Route("/", endpoint=home),
        Route("/sync-home/", endpoint=sync_home),
        Route("/hello/", endpoint=HelloEndpoint),
        Route("/sync-hello/", endpoint=SyncHelloEndpoint),
        Route("/crash/", endpoint=crash),
        Route("/return-error/", endpoint=return_error),
        Route("/background-jobs/", endpoint=background_jobs),
    ]

    async def raise_error_handler(request, exc):
        # Always raise exceptions
        raise exc

    if middleware is None:
        middleware = []

    # As per http://docs.scoutapm.com/#starlette
    Config.set(**scout_config)
    middleware.insert(0, Middleware(ScoutMiddleware))
github foxmask / yeoboseyo / yeoboseyo / app.py View on Github external
await trigger.update(mail=not trigger.mail)
            trace = f"switch mail trigger {trigger_id}"

        content = {'errors': ''}
        console.print(trace, style="blue")
    else:
        content = {'errors': {'message': 'Trigger id is missing'}}
        console.print(f"error during switch status trigger", style="red")
    return JSONResponse(content)


# The API Routes
api = Router(routes=[
    Mount('/yeoboseyo', app=Router([
        Route('/', endpoint=get_all, methods=['GET']),
        Route('/{trigger_id}', endpoint=get, methods=['GET']),
        Route('/', endpoint=create, methods=['POST']),
        Route('/{trigger_id}', endpoint=update, methods=['PATCH']),
        Route('/{trigger_id}', endpoint=delete, methods=['DELETE']),
        Route('/switch/{switch_type}/{trigger_id:int}', switch, methods=['PATCH'], name='switch'),
    ]))
])

app = Starlette(
    debug=True,
    routes=[
        Route('/', homepage, methods=['GET'], name='homepage'),
        Mount('/static', StaticFiles(directory="static")),
    ],
)

main_app.mount('/api', app=api)
github kevincarrogan / developer-arguments / main.py View on Github external
def home(request):
    challengers = random.choice(arguments)
    challengers = list(challengers)
    random.shuffle(challengers)

    challenger_one, challenger_two = challengers

    return templates.TemplateResponse(
        "argument.html", get_context_data(request, challenger_one, challenger_two)
    )


routes = [
    Route("/", home),
    Route("/{challenger_one}-vs-{challenger_two}/", permalink),
    Mount("/static", StaticFiles(directory="static")),
]

app = Starlette(debug=settings.DEBUG, routes=routes)
github TechEmpower / FrameworkBenchmarks / frameworks / Python / starlette / app.py View on Github external
num_queries = get_num_queries(request)
    updates = [(randint(1, 10000), randint(1, 10000)) for _ in range(num_queries)]
    worlds = [{'id': row_id, 'randomNumber': number} for row_id, number in updates]

    async with connection_pool.acquire() as connection:
        statement = await connection.prepare(READ_ROW_SQL)
        for row_id, number in updates:
            await statement.fetchval(row_id)
        await connection.executemany(WRITE_ROW_SQL, updates)

    return UJSONResponse(worlds)


routes = [
    Route('/json', UJSONResponse({'message': 'Hello, world!'})),
    Route('/db', single_database_query),
    Route('/queries', multiple_database_queries),
    Route('/fortunes', fortunes),
    Route('/updates', database_updates),
    Route('/plaintext', PlainTextResponse(b'Hello, world!')),
]

app = Starlette(routes=routes)
github accent-starlette / starlette-admin / starlette_admin / admin / base.py View on Github external
Route(
                    "/", endpoint=cls.list_view, methods=["GET"], name=f"{mount}_list"
                ),
                Route(
                    "/create",
                    endpoint=cls.create_view,
                    methods=["GET", "POST"],
                    name=f"{mount}_create",
                ),
                Route(
                    f"/{cls.routing_id_part}/edit",
                    endpoint=cls.update_view,
                    methods=["GET", "POST"],
                    name=f"{mount}_edit",
                ),
                Route(
                    f"/{cls.routing_id_part}/delete",
                    endpoint=cls.delete_view,
                    methods=["GET", "POST"],
                    name=f"{mount}_delete",
                ),
github drkane / find-that-charity / findthatcharity / apps / admin.py View on Github external
for b in es_results['aggregations']['sources']['buckets']
        }
    }

    return templates.TemplateResponse('admin/db_status.html', {
        'request': request,
        'db_status': db_results,
        "es_status": es_results,
    })
    return JSONResponseDate({
        "db_status": db_results,
        "es_status": es_results,
    })

routes = [
    Route('/scrapes/feed', get_scrapes_feed),
    Route('/scrapes', get_scrapes),
    Route('/scrape/{scrape_id}', get_scrape, name='get_scrape'),
    Route('/status', db_status, name='db_status'),
]