def request_context(self, _request: Request) -> RequestContext: if self.config['SERVER_NAME'] and not _request.host.startswith( self.config['SERVER_NAME']): # this is a wildcard request try: bucket, host = _request.host.split('.', 1) _request.headers['__path'] = _request.path _request.headers['__host'] = _request.host _request.headers['host'] = host url = '/%s%s' % (bucket, _request.path) _request.path = url except: app.logger.exception('bad vhost') return super().request_context(_request)
async def handle_rest_message(self, message): received_message_id = message['messageId'] method = check_json_field(message, 'method', str, True) path = check_json_field(message, 'path', str, True) queries = check_json_field(message, 'queryStrings', list, False) headers = check_json_field(message, 'headers', list, False) data_format = check_json_field(message, 'dataFormat', str, False) message_body = check_json_field(message, 'messageBody', (str, dict), False) header_dict = multidict.CIMultiDict() if (data_format): header_dict.add("Content-Type", data_format) if (headers): for header in headers: header_dict.add(header['name'], header['value']) if (queries): for query in queries: path += f"&{query['name']}={query['value']}" query_part = b'' request = Request(method, "http", path, query_part, header_dict) if ('messageBody' in message): if isinstance(message_body, dict): request.body.set_result( json.dumps(message_body).encode('utf-8')) else: request.body.set_result(message_body.encode('utf-8')) header_dict.add('Content-Length', len(message_body)) else: request.body.set_result(b'') response = await asyncio.ensure_future(app.handle_request(request)) await self.handle_rest_response(received_message_id, response)
async def parse_args(self, req: Request = None, strict=False): """ Parse all arguments from the provided request and return the results as a ParseResult """ if req is None: req = request result = self.result_class() # A record of arguments not yet parsed; as each is found # among self.args, it will be popped out req.unparsed_arguments = dict( await self.argument_class('').source(req)) if strict else {} errors = {} for arg in self.args.values(): value, found = await arg.parse(req, self.bundle_errors) if isinstance(value, ValueError): errors.update(found) found = None if found or arg.store_missing: result[arg.dest or arg.name] = value if errors: abort(HTTPStatus.BAD_REQUEST, 'Input payload validation failed', errors=errors) if strict and req.unparsed_arguments: arguments = ', '.join(req.unparsed_arguments.keys()) err = exceptions.BadRequest() err.description = 'Unknown arguments: {0}'.format(arguments) raise err return result
async def test_create_http_json_response(self, query_with_answer): headers = Headers() headers.add(key="accept", value=DOH_CONTENT_TYPE) request = Request( headers=headers, method="GET", scheme="https", path="/dns-query", http_version="1.1", query_string= b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAAAgACAAEAAEAAA", root_path="", send_push_promise=None, ) result = await create_http_json_response(request, query_with_answer) assert result.status_code == 200 assert result.headers.get("content-length") == "2" assert result.headers.get("content-type") == DOH_JSON_CONTENT_TYPE assert await result.get_data() == b"{}" result = await create_http_json_response(request, "query_with_answer") assert result.status_code == 200 assert result.headers.get("content-length") == "32" assert result.headers.get("content-type") == "text/html; charset=utf-8" assert await result.get_data() == b'{"content": "query_with_answer"}'
async def run(awaitable): fk = Request( "GET", "http", "/background/pseudo", b"", Headers([("host", "lnbits.background")]), "", "1.1", send_push_promise=lambda x, h: None, ) async with main_app.request_context(fk): g.db = open_db() await awaitable
async def run_on_pseudo_request(func: Callable, *args): fk = Request( "GET", "http", "/background/pseudo", b"", Headers([("host", "lnbits.background")]), "", "1.1", send_push_promise=send_push_promise, ) assert main_app async def run(): async with main_app.request_context(fk): with open_db() as g.db: # type: ignore await func(*args) async with trio.open_nursery() as nursery: nursery.start_soon(run)
async def open(self, path: str, *, method: str = 'GET', headers: Union[dict, CIMultiDict] = None, data: AnyStr = None, form: dict = None, query_string: dict = None, json: Any = sentinel, scheme: str = 'http', base_url: str = None) -> Response: """Open a request to the app associated with this client. Arguemnts: path: The path to request. If the query_string argument is not defined this argument will be partitioned on a '?' with the following part being considered the query_string. method: The method to make the request with, defaults GET. headers: Headers to include in the request. data: Raw data to send in the request body. form: Data to send form encoded in the request body. query_string: To send as a dictionary, alternatively the query_string can be determined from the path. json: Data to send json encoded in the request body. scheme: The scheme to use in the request, default http. Returns: The response from the app handling the request. """ headers, path, query_string_bytes = make_test_headers_path_and_query_string( self.app, path, headers, query_string, ) if [json is not sentinel, form is not None, data is not None ].count(True) > 1: raise ValueError( "Quart test args 'json', 'form', and 'data' are mutually exclusive" ) request_data = b'' if isinstance(data, str): request_data = data.encode('utf-8') elif isinstance(data, bytes): request_data = data if json is not sentinel: request_data = dumps(json).encode('utf-8') headers['Content-Type'] = 'application/json' if form is not None: request_data = urlencode(form).encode('utf-8') headers['Content-Type'] = 'application/x-www-form-urlencoded' if self.cookie_jar is not None: headers.add('Cookie', self.cookie_jar.output(header='')) # type: ignore if base_url is not None: result = urlparse(base_url) scheme = result.scheme if result.path: path = '{}/{}'.format(result.path.rstrip('/'), path.lstrip('/')) headers.update({'Host': result.hostname}) request = Request(method, scheme, path, query_string_bytes, headers) # type: ignore request.body.set_result(request_data) response = await self.app.handle_request(request) if self.cookie_jar is not None and 'Set-Cookie' in response.headers: self.cookie_jar.load(";".join( response.headers.getall('Set-Cookie'))) return response
async def test_get_name_and_type_from_dns_question(self): headers = Headers() headers.add(key="accept", value=DOH_CONTENT_TYPE) request = Request( headers=headers, method="GET", scheme="https", path="/dns-query", http_version="1.1", query_string= b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAAAgACAAEAAEAAA", root_path="", send_push_promise=None, ) result = await get_name_and_type_from_dns_question(request) assert str(result.question[0]) == "s0.wp.com. IN AAAA" headers = Headers() headers.add(key="accept", value=DOH_JSON_CONTENT_TYPE) request = Request( headers=headers, method="GET", scheme="https", path="/dns-query", http_version="1.1", query_string=b"name=example.com&type=A", root_path="", send_push_promise=None, ) result = await get_name_and_type_from_dns_question(request) assert str(result.question[0]) == "example.com. IN A" headers = Headers() headers.add(key="content-type", value=DOH_CONTENT_TYPE) request = Request( headers=headers, method="POST", scheme="https", path="/dns-query", http_version="1.1", query_string= b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAAAgACAAEAAEAAA", root_path="", send_push_promise=None, ) request.body = return_body() result = await get_name_and_type_from_dns_question(request) assert result is None request = Request( headers=headers, method="GET", scheme="https", path="/dns-query", http_version="1.1", query_string= b"dns=AAABAAABAAAAAAABAnMwAndwA2NvbQAAHAABAAApEAAAAAAAgACAAEAAEAAA", root_path="", send_push_promise=None, ) result = await get_name_and_type_from_dns_question(request) assert result is None