async def metrics(request: Request): content, http_headers = render( app.registry, [request.headers.get("accept", "application/json")]) return PlainTextResponse(content, headers=http_headers)
def homepage(request): return PlainTextResponse("OK", status_code=200)
async def error(request): await localfunc('func_arg1', 'func_arg2', 1) return PlainTextResponse("You shouldn't be seeing this")
async def health_check(request): return PlainTextResponse('up', status_code=200)
def homepage(request): return PlainTextResponse("Homepage")
async def get(self, request): data = request.path_params['this'] return PlainTextResponse(data)
from starlette.routing import Mount from starlette_api.users import UsersApp, auth from starlette_api.warehouse import WarehouseApp from . import settings from .database import database routes = [Mount("/", app=WarehouseApp), Mount("/users", app=UsersApp)] app = Starlette(routes=routes) app.debug = settings.DEBUG app.add_middleware( AuthenticationMiddleware, backend=auth.ModelTokenAuth(), on_error=lambda _, exc: PlainTextResponse(str(exc), status_code=401), ) @app.on_event("startup") async def startup() -> None: await database.connect() @app.on_event("shutdown") async def shutdown() -> None: await database.disconnect() if __name__ in ["__main__", "app"]: uvicorn.run(app, host="0.0.0.0", port=8000)
def index(req): return PlainTextResponse("hello")
async def duplicated_data_handler(*args, **kwargs): # pylint:disable=unused-argument return PlainTextResponse("Email is not available for use", 409)
async def should_not_be_here() -> PlainTextResponse: return PlainTextResponse( "If you are simplechrome controlled browser why are you here? Otherwise welcome friend!" )
async def index(request): return PlainTextResponse('Zdraviya jelau')
def _get_error_response(self, request: Request) -> Response: return PlainTextResponse( content="CSRF token verification failed", status_code=403 )
def endpoint(request): return PlainTextResponse(request.user.display_name)
async def index(request): return PlainTextResponse('My index page!')
def custom_subdomain(request): return PlainTextResponse("Subdomain: " + request.path_params["subdomain"])
async def not_found_data_handler(*args, **kwargs): # pylint:disable=unused-argument return PlainTextResponse("Not Found", 404)
def homepage(request): return PlainTextResponse('Welcome to MetaDrive!')
async def homepage(request): if request.user.is_authenticated: return PlainTextResponse('Hello, ' + request.user.display_name) return HTMLResponse(f'<html><body><h1>Hello, you</h1><br></body></html>')
async def get(self, request): # Handle web requests session_cookie = request.cookies.get(SESSION_COOKIE_NAME) if SESSIONS: new_cookie = False if session_cookie: try: session_id = cookie_signer.unsign(session_cookie).decode( "utf-8") except: return PlainTextResponse('Bad Session') request.state.session_id = session_id request.session_id = session_id else: # Create new session_id request.state.session_id = str(uuid.uuid4().hex) request.session_id = request.state.session_id new_cookie = True logging.debug(f'New session_id created: {request.session_id}') for route in Route.instances: func = route.matches(request['path'], request) if func: func_to_run = func break func_parameters = len(inspect.signature(func_to_run).parameters) assert func_parameters < 2, f"Function {func_to_run.__name__} cannot have more than one parameter" if inspect.iscoroutinefunction(func_to_run): if func_parameters == 1: load_page = await func_to_run(request) else: load_page = await func_to_run() else: if func_parameters == 1: load_page = func_to_run(request) else: load_page = func_to_run() if isinstance(load_page, Response): logging.debug('Returning raw starlette.responses.Response.') return load_page assert issubclass(type(load_page), WebPage), 'Function did not return a web page' assert len( load_page ) > 0 or load_page.html, '\u001b[47;1m\033[93mWeb page is empty, add components\033[0m' page_options = { 'reload_interval': load_page.reload_interval, 'body_style': load_page.body_style, 'body_classes': load_page.body_classes, 'css': load_page.css, 'head_html': load_page.head_html, 'body_html': load_page.body_html, 'display_url': load_page.display_url, 'dark': load_page.dark, 'title': load_page.title, 'redirect': load_page.redirect, 'highcharts_theme': load_page.highcharts_theme, 'debug': load_page.debug, 'events': load_page.events, 'favicon': load_page.favicon if load_page.favicon else FAVICON } if load_page.use_cache: page_dict = load_page.cache else: page_dict = load_page.build_list() template_options['tailwind'] = load_page.tailwind context = { 'request': request, 'page_id': load_page.page_id, 'justpy_dict': json.dumps(page_dict, default=str), 'use_websockets': json.dumps(WebPage.use_websockets), 'options': template_options, 'page_options': page_options, 'html': load_page.html } response = templates.TemplateResponse(load_page.template_file, context) if SESSIONS and new_cookie: cookie_value = cookie_signer.sign(request.state.session_id) cookie_value = cookie_value.decode("utf-8") response.set_cookie(SESSION_COOKIE_NAME, cookie_value, max_age=COOKIE_MAX_AGE, httponly=True) for k, v in load_page.cookies.items(): response.set_cookie(k, v, max_age=COOKIE_MAX_AGE, httponly=True) if LATENCY: await asyncio.sleep(LATENCY / 1000) return response
async def test(request): if request.user.is_authenticated: return PlainTextResponse('Hello, ' + request.user.display_name)
async def homepage(request): assert ctxvar.get() == "set by middleware" ctxvar.set("set by endpoint") return PlainTextResponse("Homepage")
async def async_homepage(request): return PlainTextResponse("Hello, world!")
async def dispatch(self, request, call_next): await call_next(request) return PlainTextResponse("Custom")
def get(self, request): return PlainTextResponse("Hello, world!")
async def closure(_): return PlainTextResponse(self.version)
def all_users_page(request): return PlainTextResponse("Hello, everyone!")
async def root(request): return PlainTextResponse('hello world')
def user_page(request): username = request.path_params["username"] return PlainTextResponse(f"Hello, {username}!")
def user(request): username = request.path_params["username"] return PlainTextResponse("Hello, %s!" % username)
async def health(request: Request) -> PlainTextResponse: return PlainTextResponse(content=b"", status_code=500)