def app(request): return wrappers.Response('All is well', 200, content_type='text/html')
def test_response_stream_mixin(): response = wrappers.Response() response.stream.write("Hello ") response.stream.write("World!") assert response.response == ["Hello ", "World!"] assert response.get_data() == b"Hello World!"
def test_response_stream_mixin(): response = wrappers.Response() response.stream.write('Hello ') response.stream.write('World!') assert response.response == ['Hello ', 'World!'] assert response.get_data() == b'Hello World!'
def test_write_length(): response = wrappers.Response() length = response.stream.write(b"bar") assert length == 3
def test_base_response(): # unicode response = wrappers.BaseResponse(u"öäü") strict_eq(response.get_data(), u"öäü".encode("utf-8")) # writing response = wrappers.Response("foo") response.stream.write("bar") strict_eq(response.get_data(), b"foobar") # set cookie response = wrappers.BaseResponse() response.set_cookie( "foo", value="bar", max_age=60, expires=0, path="/blub", domain="example.org", samesite="Strict", ) strict_eq( response.headers.to_wsgi_list(), [ ("Content-Type", "text/plain; charset=utf-8"), ( "Set-Cookie", "foo=bar; Domain=example.org; Expires=Thu, " "01-Jan-1970 00:00:00 GMT; Max-Age=60; Path=/blub; " "SameSite=Strict", ), ], ) # delete cookie response = wrappers.BaseResponse() response.delete_cookie("foo") strict_eq( response.headers.to_wsgi_list(), [ ("Content-Type", "text/plain; charset=utf-8"), ( "Set-Cookie", "foo=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/", ), ], ) # close call forwarding closed = [] @implements_iterator class Iterable(object): def __next__(self): raise StopIteration() def __iter__(self): return self def close(self): closed.append(True) response = wrappers.BaseResponse(Iterable()) response.call_on_close(lambda: closed.append(True)) app_iter, status, headers = run_wsgi_app(response, create_environ(), buffered=True) strict_eq(status, "200 OK") strict_eq("".join(app_iter), "") strict_eq(len(closed), 2) # with statement del closed[:] response = wrappers.BaseResponse(Iterable()) with response: pass assert len(closed) == 1
def test_base_response(): # unicode response = wrappers.BaseResponse(u'öäü') strict_eq(response.get_data(), u'öäü'.encode('utf-8')) # writing response = wrappers.Response('foo') response.stream.write('bar') strict_eq(response.get_data(), b'foobar') # set cookie response = wrappers.BaseResponse() response.set_cookie('foo', value='bar', max_age=60, expires=0, path='/blub', domain='example.org') strict_eq(response.headers.to_wsgi_list(), [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'foo=bar; Domain=example.org; Expires=Thu, ' '01-Jan-1970 00:00:00 GMT; Max-Age=60; Path=/blub')]) # delete cookie response = wrappers.BaseResponse() response.delete_cookie('foo') strict_eq( response.headers.to_wsgi_list(), [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'foo=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/')]) # close call forwarding closed = [] @implements_iterator class Iterable(object): def __next__(self): raise StopIteration() def __iter__(self): return self def close(self): closed.append(True) response = wrappers.BaseResponse(Iterable()) response.call_on_close(lambda: closed.append(True)) app_iter, status, headers = run_wsgi_app(response, create_environ(), buffered=True) strict_eq(status, '200 OK') strict_eq(''.join(app_iter), '') strict_eq(len(closed), 2) # with statement del closed[:] response = wrappers.BaseResponse(Iterable()) with response: pass assert len(closed) == 1
def test_response_304_no_content_length(): resp = wrappers.Response("Test", status=304) env = create_environ() assert "content-length" not in resp.get_wsgi_headers(env)
def app(request): return wrappers.Response( "All is well", 200, content_type="text/html" )
def _eid_handler(self, request): eid = plugin_util.experiment_id(request.environ) body = json.dumps({"experiment_id": eid}) return wrappers.Response(body, 200, content_type="application/json")
def setUp(self): super(RemoteUserWebAuthManagerTest, self).setUp() self.manager = webauth.RemoteUserWebAuthManager() self.success_response = werkzeug_wrappers.Response("foobar")
def Handler(request, *args, **kwargs): del args, kwargs # Unused. self.assertEqual(request.user, user) return werkzeug_wrappers.Response("foobar", status=200)
def Handler(request, *args, **kwargs): del args, kwargs # Unused. self.assertEqual(request.user, "temp") return werkzeug_wrappers.Response("success", status=200)
def Handler(request, *args, **kwargs): del request, args, kwargs # Unused. return werkzeug_wrappers.Response("foobar", status=200)
def Respond(request, content, content_type, code=200, expires=0, content_encoding=None, encoding='utf-8'): """Construct a werkzeug Response. Responses are transmitted to the browser with compression if: a) the browser supports it; b) it's sane to compress the content_type in question; and c) the content isn't already compressed, as indicated by the content_encoding parameter. Browser and proxy caching is completely disabled by default. If the expires parameter is greater than zero then the response will be able to be cached by the browser for that many seconds; however, proxies are still forbidden from caching so that developers can bypass the cache with Ctrl+Shift+R. For textual content that isn't JSON, the encoding parameter is used as the transmission charset which is automatically appended to the Content-Type header. That is unless of course the content_type parameter contains a charset parameter. If the two disagree, the characters in content will be transcoded to the latter. If content_type declares a JSON media type, then content MAY be a dict, list, tuple, or set, in which case this function has an implicit composition with json_util.Cleanse and json.dumps. The encoding parameter is used to decode byte strings within the JSON object; therefore transmitting binary data within JSON is not permitted. JSON is transmitted as ASCII unless the content_type parameter explicitly defines a charset parameter, in which case the serialized JSON bytes will use that instead of escape sequences. Args: request: A werkzeug Request object. Used mostly to check the Accept-Encoding header. content: Payload data as byte string, unicode string, or maybe JSON. content_type: Media type and optionally an output charset. code: Numeric HTTP status code to use. expires: Second duration for browser caching. content_encoding: Encoding if content is already encoded, e.g. 'gzip'. encoding: Input charset if content parameter has byte strings. Returns: A werkzeug Response object (a WSGI application). """ mimetype = _EXTRACT_MIMETYPE_PATTERN.search(content_type).group(0) charset_match = _EXTRACT_CHARSET_PATTERN.search(content_type) charset = charset_match.group(1) if charset_match else encoding textual = charset_match or mimetype in _TEXTUAL_MIMETYPES if mimetype in _JSON_MIMETYPES and (isinstance(content, dict) or isinstance(content, list) or isinstance(content, set) or isinstance(content, tuple)): content = json.dumps(json_util.Cleanse(content, encoding), ensure_ascii=not charset_match) if charset != encoding: content = compat.as_text(content, encoding) content = compat.as_bytes(content, charset) if textual and not charset_match and mimetype not in _JSON_MIMETYPES: content_type += '; charset=' + charset if (not content_encoding and textual and _ALLOWS_GZIP_PATTERN.search( request.headers.get('Accept-Encoding', ''))): out = six.BytesIO() f = gzip.GzipFile(fileobj=out, mode='wb', compresslevel=3) f.write(content) f.close() content = out.getvalue() content_encoding = 'gzip' if request.method == 'HEAD': content = '' headers = [] headers.append(('Content-Length', str(len(content)))) if content_encoding: headers.append(('Content-Encoding', content_encoding)) if expires > 0: e = wsgiref.handlers.format_date_time(time.time() + float(expires)) headers.append(('Expires', e)) headers.append(('Cache-Control', 'private, max-age=%d' % expires)) else: headers.append(('Expires', '0')) headers.append(('Cache-Control', 'no-cache, must-revalidate')) return wrappers.Response(response=content, status=code, headers=headers, content_type=content_type)
def AuthError(self, message): return werkzeug_wrappers.Response(message, status=403)
def _foo_handler(self, request): return wrappers.Response(response='hello world', status=200)
def test_location_header_autocorrect(monkeypatch, auto, location, expect): monkeypatch.setattr(wrappers.Response, 'autocorrect_location_header', auto) env = create_environ('/a/b/c') resp = wrappers.Response('Hello World!') resp.headers['Location'] = location assert resp.get_wsgi_headers(env)['Location'] == expect
def _wildcard_special_handler(self, request): return wrappers.Response(status=300)
def test_response_content_length_uses_encode(): r = wrappers.Response(u"你好") assert r.calculate_content_length() == 6
def health_check_intercept_wrapper(request): """Capture a request to /_ah/health and respond with 200 OK.""" if request.path == '/_ah/health': # Only intercept exact matches. return wrappers.Response('healthy', status=httplib.OK) else: return app
def test_location_header_autocorrect(monkeypatch, auto, location, expect): monkeypatch.setattr(wrappers.Response, "autocorrect_location_header", auto) env = create_environ("/a/b/c") resp = wrappers.Response("Hello World!") resp.headers["Location"] = location assert resp.get_wsgi_headers(env)["Location"] == expect
def test_response_stream_mixin(self): response = wrappers.Response() response.stream.write('Hello ') response.stream.write('World!') self.assert_equal(response.response, ['Hello ', 'World!']) self.assert_equal(response.get_data(), b'Hello World!')
def application(request): return wrappers.Response("Hello World!")
def test_response_304_no_content_length(self): resp = wrappers.Response('Test', status=304) env = create_environ() assert 'content-length' not in resp.get_wsgi_headers(env)
def test_invalid_range_request(): env = create_environ() response = wrappers.Response("Hello World") env["HTTP_RANGE"] = "bytes=-" with pytest.raises(RequestedRangeNotSatisfiable): response.make_conditional(env, accept_ranges=True, complete_length=11)
def response(self): """Generate a response object from the request information.""" data = json.dumps(self.data, cls=json_encoder.GrowJSONEncoder) return wrappers.Response(data, mimetype='application/json')
def _serve_health_pills_handler(self, request): """A (wrapped) werkzeug handler for serving health pills. Accepts POST requests and responds with health pills. The request accepts several POST parameters: node_names: (required string) A JSON-ified list of node names for which the client would like to request health pills. run: (optional string) The run to retrieve health pills for. Defaults to '.'. This data is sent via POST (not GET) since URL length is limited. step: (optional integer): The session run step for which to retrieve health pills. If provided, the handler reads the health pills of that step from disk (which is slow) and produces a response with only health pills at that step. If not provided, the handler returns a response with health pills at all steps sampled by the event multiplexer (the fast path). The motivation here is that, sometimes, one desires to examine health pills at a specific step (to say find the first step that causes a model to blow up with NaNs). get_plugin_apps must be called before this slower feature is used because that method passes the logdir (directory path) to this plugin. This handler responds with a JSON-ified object mapping from node names to a list (of size 1) of health pill event objects, each of which has these properties. { 'wall_time': float, 'step': int, 'node_name': string, 'output_slot': int, # A list of 12 floats that summarizes the elements of the tensor. 'value': float[], } Node names for which there are no health pills to be found are excluded from the mapping. Args: request: The request issued by the client for health pills. Returns: A werkzeug BaseResponse object. """ if request.method != 'POST': logging.error( '%s requests are forbidden by the debugger plugin.', request.method) return wrappers.Response(status=405) if _NODE_NAMES_POST_KEY not in request.form: logging.error( 'The %r POST key was not found in the request for health pills.', _NODE_NAMES_POST_KEY) return wrappers.Response(status=400) jsonified_node_names = request.form[_NODE_NAMES_POST_KEY] try: node_names = json.loads(jsonified_node_names) except Exception as e: # pylint: disable=broad-except # Different JSON libs raise different exceptions, so we just do a # catch-all here. This problem is complicated by how Tensorboard might be # run in many different environments, as it is open-source. logging.error('Could not decode node name JSON string %r: %s', jsonified_node_names, e) return wrappers.Response(status=400) if not isinstance(node_names, list): logging.error('%r is not a JSON list of node names:', jsonified_node_names) return wrappers.Response(status=400) run = request.form.get(_RUN_POST_KEY, _DEFAULT_RUN) step_string = request.form.get(_STEP_POST_KEY, None) if step_string is None: # Use all steps sampled by the event multiplexer (Relatively fast). mapping = self._obtain_sampled_health_pills(run, node_names) else: # Read disk to obtain the health pills for that step (Relatively slow). # Make sure that the directory for the run exists. # Determine the directory of events file to read. events_directory = self._logdir if run != _DEFAULT_RUN: # Use the directory for the specific run. events_directory = os.path.join(events_directory, run) step = int(step_string) try: mapping = self._obtain_health_pills_at_step( events_directory, node_names, step) except IOError as error: logging.error( 'Error retrieving health pills for step %d: %s', step, error) return wrappers.Response(status=404) # Convert event_accumulator.HealthPillEvents to JSON-able dicts. jsonable_mapping = {} for node_name, events in mapping.items(): jsonable_mapping[node_name] = [e._asdict() for e in events] return http_util.Respond(request, jsonable_mapping, 'application/json')
def salutation_world(request): salutation = request.args.get('salutation', 'Hello') return wrappers.Response('%s World!' % salutation)
def test_response_headers_passthrough(): headers = wrappers.Headers() resp = wrappers.Response(headers=headers) assert resp.headers is headers
def _send_file(self, file_path): with open(file_path, 'rb') as file_obj: mimetype = mimetypes.guess_type(file_path)[0] return wrappers.Response( file_obj.read(), content_type=mimetype)