def hello(request): return web.Response(body=b"Hello, world")
async def dataint(req): row = find_first_row("GeneralInt", 1, "data") return web.Response(text=cache["dataint"].format(str(row[2])), content_type="text/html")
async def api_v1_visits(req): row = find_first_row("GeneralInt", 1, "visits") datasend = {"visits": row[2]} return web.Response(text=json.dumps(datasend), content_type="text/json")
async def upload(self, request): denied = True auth = request.headers.get('Authorization') if auth: if auth.startswith('Basic '): try: auth = binascii.a2b_base64(auth[6:]).decode() if ':' in auth: user, password = auth.split(':', 1) if await self.middleware.call('auth.check_user', user, password): denied = False except binascii.Error: pass elif auth.startswith('Token '): auth_token = auth.split(" ", 1)[1] token = await self.middleware.call('auth.get_token', auth_token) if token: denied = False else: qs = urllib.parse.parse_qs(request.query_string) if 'auth_token' in qs: auth_token = qs.get('auth_token')[0] token = await self.middleware.call('auth.get_token', auth_token) if token: denied = False if denied: resp = web.Response() resp.set_status(401) return resp reader = await request.multipart() part = await reader.next() if not part: resp = web.Response(status=405, body='No part found on payload') resp.set_status(405) return resp if part.name != 'data': resp = web.Response(status=405, body='"data" part must be the first on payload') resp.set_status(405) return resp try: data = json.loads(await part.read()) except Exception as e: return web.Response(status=400, body=str(e)) if 'method' not in data: return web.Response(status=422) filepart = await reader.next() if not filepart or filepart.name != 'file': resp = web.Response(status=405, body='"file" not found as second part on payload') resp.set_status(405) return resp def copy(): while True: read = asyncio.run_coroutine_threadsafe( filepart.read_chunk(1048576), loop=self.loop, ).result() if read == b'': break job.pipes.input.w.write(read) try: job = await self.middleware.call(data['method'], *(data.get('params') or []), pipes=Pipes(input=self.middleware.pipe())) try: await self.middleware.run_in_io_thread(copy) finally: await self.middleware.run_in_io_thread(job.pipes.input.w.close) except CallError as e: if e.errno == CallError.ENOMETHOD: status_code = 422 else: status_code = 412 return web.Response(status=status_code, body=str(e)) except Exception as e: return web.Response(status=500, body=str(e)) resp = web.Response( status=200, headers={ 'Content-Type': 'application/json', }, body=json.dumps({'job_id': job.id}).encode(), ) return resp
async def index(request): index_file = open('examples/rasa_demo/templates/index.html') return web.Response(body=index_file.read().encode('utf-8'), headers={'content-type': 'text/html'})
async def metrics(request): resp = web.Response(body=prometheus_client.generate_latest()) resp.content_type = CONTENT_TYPE_LATEST return resp
async def hello(request): return web.Response(text="Hi")
async def hello(request): await asyncio.sleep(0.5) text = '<h1>Welcome, %s!</h1>' % request.match_info['name'] return web.Response(body=text.encode('utf-8'), content_type='text/html')
async def index(request): await asyncio.sleep(0.5) return web.Response(body=b'<h1>Welcome to homepage!</h1>', content_type='text/html')
async def get_networks(request): global wifi print('get_networks') return web.Response(text=json.dumps(wifi.access_points))
async def post_connect(request): global wifi d = await request.json() request.loop.call_later(1, wifi.connect, d['name'], d['passphrase']) return web.Response()
if retraining: min_duration = int(retraining['min_duration']) max_participants = int(retraining['max_participants']) else: min_duration = max_participants = None except KeyError: raise web.HTTPBadRequest( reason= 'fields "min_duration" and "max_participants" are mandatory for retraining' ) manager = request.app['monitoring'] try: await manager.schedule_training(conf_name, calls, threshold, min_duration, max_participants) return web.Response() except ValidationError as e: return web.HTTPBadRequest(reason=str(e)) async def schedule_inference(request): if (conf_name := request.match_info.get('conf_name', None)) is None: raise web.HTTPBadRequest(reason='no conference name given') manager = request.app['monitoring'] await manager.schedule_inference(conf_name) return web.Response() async def unschedule_inference(request): if (conf_name := request.match_info.get('conf_name', None)) is None:
def index(request): return web.Response(body=b'<h1>Awesome</h1>', content_type='text/html')
def cookie_handler(request): resp = web.Response(body=b"Hello, world") resp.set_cookie('cookie', 'val') return resp
async def javascript(self,request): LOGGER.debug('DashboardRouteHandler: javascript=%s',request.path) content = open(os.path.join(ROOT,'app/js/'+request.path[1:]), 'r', encoding='utf-8').read() return web.Response(content_type='application/javascript', text=content)
class PlexImageView(HomeAssistantView): """Media player view to serve a Plex image.""" name = "api:plex:image" url = "/api/plex_image_proxy/{server_id}/{media_content_id}" async def get( # pylint: disable=no-self-use self, request: web.Request, server_id: str, media_content_id: str, ) -> web.Response: """Start a get request.""" if not request[KEY_AUTHENTICATED]: return web.Response(status=HTTPStatus.UNAUTHORIZED) hass = request.app["hass"] if (server := hass.data[PLEX_DOMAIN][SERVERS].get(server_id)) is None: return web.Response(status=HTTPStatus.NOT_FOUND) if (image_url := server.thumbnail_cache.get(media_content_id)) is None: return web.Response(status=HTTPStatus.NOT_FOUND) data, content_type = await async_fetch_image(_LOGGER, hass, image_url) if data is None: return web.Response(status=HTTPStatus.SERVICE_UNAVAILABLE) headers: LooseHeaders = {CACHE_CONTROL: "max-age=3600"} return web.Response(body=data, content_type=content_type, headers=headers)
def index(request): return web.Response(body=b'<h1>awesome</h1>')
async def handler(request: web.Request) -> web.Response: assert "b3" in request.headers assert request.path == BlobUrlRotes.DELETE_BUCKET.format(bucket=name) assert request.query == {} return web.Response(status=204)
async def handle(_): a, b = get_row() return web.Response(text=json.dumps({"a": str(a).zfill(10), "b": b}))
async def handler(request: web.Request) -> web.StreamResponse: assert "b3" in request.headers assert request.path == f"/blob/o/{bucket_name}/{key}" return web.Response(status=204)
async def download(self, request): path = request.path.split('/') if not request.path[-1].isdigit(): resp = web.Response() resp.set_status(404) return resp job_id = int(path[-1]) qs = urllib.parse.parse_qs(request.query_string) denied = False filename = None if 'auth_token' not in qs: denied = True else: auth_token = qs.get('auth_token')[0] token = await self.middleware.call('auth.get_token', auth_token) if not token: denied = True else: if (token['attributes'] or {}).get('job') != job_id: denied = True else: filename = token['attributes'].get('filename') if denied: resp = web.Response() resp.set_status(401) return resp job = self.middleware.jobs.get(job_id) if not job: resp = web.Response() resp.set_status(404) return resp if job_id not in self.jobs: resp = web.Response() resp.set_status(410) return resp resp = web.StreamResponse(status=200, reason='OK', headers={ 'Content-Type': 'application/octet-stream', 'Content-Disposition': f'attachment; filename="{filename}"', 'Transfer-Encoding': 'chunked', }) await resp.prepare(request) def do_copy(): while True: read = job.pipes.output.r.read(1048576) if read == b'': break asyncio.run_coroutine_threadsafe(resp.write(read), loop=self.loop).result() try: await self.middleware.run_in_io_thread(do_copy) finally: await self._cleanup_job(job_id) await resp.drain() return resp
def state_http_response(request): return web.Response(text=json.dumps(get_state()))
def json_response(data, **kwargs): kwargs.setdefault('content_type', 'application/json') return web.Response(text=ujson.dumps(data), **kwargs)
async def handler(request): if text: return web.Response(text=text) else: return web.Response(status=404, text='Not found')
async def root(req): return web.Response(text=cache["index"], content_type="text/html")
async def handler(request): return web.Response(text=text)
async def scripts_dataint(req): return web.Response(text=cache["datascript"], content_type="text/javascript")
async def home(self, request: web.Request) -> web.Response: return web.Response(text='Hello, world!')
async def index(request): with open('index.html') as f: return web.Response(text=f.read(), content_type='text/html')
async def home(request: web.Request) -> web.Response: return web.Response(text='Hello client!')