Python werkzeug.wrappers.Response() Examples
The following are 30
code examples of werkzeug.wrappers.Response().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
werkzeug.wrappers
, or try the search function
.
Example #1
Source File: exceptions.py From lambda-packs with MIT License | 6 votes |
def abort(status, *args, **kwargs): ''' Raises an :py:exc:`HTTPException` for the given status code or WSGI application:: abort(404) # 404 Not Found abort(Response('Hello World')) Can be passed a WSGI application or a status code. If a status code is given it's looked up in the list of exceptions and will raise that exception, if passed a WSGI application it will wrap it in a proxy WSGI exception and raise that:: abort(404) abort(Response('Hello World')) ''' return _aborter(status, *args, **kwargs)
Example #2
Source File: __init__.py From beavy with Mozilla Public License 2.0 | 6 votes |
def api_only(fn): @wraps(fn) def wrapped(*args, **kwargs): accepted = set(request.accept_mimetypes.values()) explicit = not(not request.args.get("json", False)) if not (accepted & API_MIMETYPES) and not explicit: return abort(415, "Unsupported Media Type") resp = fn(*args, **kwargs) if not isinstance(resp, ResponseBase): data, code, headers = unpack(resp) # we've found one, return json if isinstance(data, MarshalResult): data = data.data resp = make_response(json.dumps(data, indent=explicit and 4 or 0), code) if headers: resp.headers.update(headers) resp.headers["Content-Type"] = 'application/json' return resp return wrapped
Example #3
Source File: test_response_normalization.py From flex with MIT License | 6 votes |
def test_werkzeug_response_normalization(httpbin): from werkzeug.wrappers import Request, Response from werkzeug.test import create_environ raw_request = Request(create_environ( path='/get', base_url=httpbin.url, query_string='key=val', method='GET', )) raw_response = Response( response=b'{"key2": "val2"}', content_type='application/json', ) response = normalize_response(raw_response, raw_request) assert response.path == '/get' assert response.content_type == 'application/json' assert response.url == httpbin.url + '/get?key=val' assert response.status_code == '200'
Example #4
Source File: flask.py From keycloak-client with GNU General Public License v3.0 | 6 votes |
def callback(self, session: Dict, request: Request) -> Response: """ Authentication callback handler """ # validate state state = request.args.get("state", "unknown") _state = session.pop("state", None) if state != _state: return Response("Invalid state", status=403) # fetch user tokens code: str = request.args.get("code", "unknown") tokens = self.kc.callback(code) session["tokens"] = json.dumps(tokens) # fetch user info access_token = tokens["access_token"] user = self.kc.fetch_userinfo(access_token) session["user"] = json.dumps(user) return redirect(self.redirect_uri)
Example #5
Source File: test_clients.py From mergify-engine with Apache License 2.0 | 6 votes |
def _do_test_client_retry_429(httpserver, retry_after, expected_seconds): records = [] def record_date(_): records.append(datetime.datetime.utcnow()) return Response("It works now !", 200) httpserver.expect_oneshot_request("/").respond_with_data( "This is an 429 error", status=429, headers={"Retry-After": retry_after} ) httpserver.expect_request("/").respond_with_handler(record_date) with http.Client() as client: now = datetime.datetime.utcnow() client.get(httpserver.url_for("/")) assert len(httpserver.log) == 2 elapsed_seconds = (records[0] - now).total_seconds() assert expected_seconds - 1 < elapsed_seconds <= expected_seconds + 1 httpserver.check_assertions()
Example #6
Source File: http.py From prometheus-pve-exporter with Apache License 2.0 | 6 votes |
def on_index(self): """ Request handler for index route (/). """ response = Response( """<html> <head><title>Proxmox VE Exporter</title></head> <body> <h1>Proxmox VE Exporter</h1> <p>Visit <code>/pve?target=1.2.3.4</code> to use.</p> </body> </html>""" ) response.headers['content-type'] = 'text/html' return response
Example #7
Source File: http.py From prometheus-pve-exporter with Apache License 2.0 | 6 votes |
def on_pve(self, module='default', target='localhost'): """ Request handler for /pve route """ if module in self._config: start = time.time() output = collect_pve(self._config[module], target) response = Response(output) response.headers['content-type'] = CONTENT_TYPE_LATEST self._duration.labels(module).observe(time.time() - start) else: response = Response("Module '{0}' not found in config".format(module)) response.status_code = 400 return response
Example #8
Source File: test_response_normalization.py From flex with MIT License | 6 votes |
def test_webob_response_normalization(httpbin): import webob raw_request = webob.Request.blank(httpbin.url + '/get') raw_request.query_string = 'key=val' raw_request.method = 'GET' raw_request.content_type = 'application/json' raw_response = webob.Response() raw_response.content_type = 'application/json' response = normalize_response(raw_response, raw_request) assert response.path == '/get' assert response.content_type == 'application/json' assert response.url == httpbin.url + '/get?key=val' assert response.status_code == '200'
Example #9
Source File: authorization.py From python-sdk with GNU Lesser General Public License v3.0 | 6 votes |
def __call__(self, environ, start_response): if _ENABLE_TEST: global current_environ current_environ = environ self.parse_header(environ) app_params = environ["_app_params"] if not any(app_params.values()): # all app_params's value is None self.parse_body(environ) unauth_response = Response( json.dumps({"code": 401, "error": "Unauthorized."}), status=401, mimetype="application/json", ) if app_params["id"] is None: return unauth_response(environ, start_response) if (APP_ID == app_params["id"]) and ( app_params["key"] in [MASTER_KEY, APP_KEY, ANDX_KEY] ): return self.app(environ, start_response) if (APP_ID == app_params["id"]) and (app_params["master_key"] == MASTER_KEY): return self.app(environ, start_response) return unauth_response(environ, start_response)
Example #10
Source File: server.py From google-analytics with ISC License | 6 votes |
def single_serve(message=None, port=5000): import logging from werkzeug.wrappers import Request, Response from werkzeug.serving import run_simple log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) captured = {} def application(environ, start_response): request = Request(environ) request.environ.get('werkzeug.server.shutdown')() captured.update(dict(request.args.items())) if message: print(message) response = Response(message, mimetype='text/plain') return response(environ, start_response) run_simple('localhost', port, application) return captured
Example #11
Source File: exceptions.py From RSSNewsGAE with Apache License 2.0 | 6 votes |
def abort(status, *args, **kwargs): ''' Raises an :py:exc:`HTTPException` for the given status code or WSGI application:: abort(404) # 404 Not Found abort(Response('Hello World')) Can be passed a WSGI application or a status code. If a status code is given it's looked up in the list of exceptions and will raise that exception, if passed a WSGI application it will wrap it in a proxy WSGI exception and raise that:: abort(404) abort(Response('Hello World')) ''' return _aborter(status, *args, **kwargs)
Example #12
Source File: renderer.py From paws with MIT License | 6 votes |
def application(request): file_path = request.path.lstrip(URL_PREFIX) full_path = os.path.join(BASE_PATH, file_path) # Protect against path traversal attacks, if they make it this far. if not full_path.startswith(BASE_PATH): # DANGER! return Response("Suspicious url", status=403) format = request.args.get('format', None) if format == 'raw': # Let nginx serve raw files accel_path = os.path.join('/accelredir/', file_path) return Response('', headers={'X-Accel-Redirect': accel_path}) try: extension = get_extension(full_path, format) if extension and extension in handlers: return handlers[extension](full_path, format) else: return Response("No handlers for format %s" % extension, status=400) except FileNotFoundError: return Response("Not found", status=404) return Response(full_path)
Example #13
Source File: mock_server.py From zerotest with MIT License | 5 votes |
def get_count(self, request): return Response(json.dumps(dict(count=self.count)), content_type='application/json; charset=utf-8')
Example #14
Source File: mock_server.py From zerotest with MIT License | 5 votes |
def post_echo(self, request): return Response(request.data, content_type=request.headers['content_type'])
Example #15
Source File: mock_server.py From zerotest with MIT License | 5 votes |
def post_raw_to_json(self, request): data = request.data return Response(data, content_type='application/json')
Example #16
Source File: http.py From prometheus-pve-exporter with Apache License 2.0 | 5 votes |
def on_metrics(self): """ Request handler for /metrics route """ response = Response(generate_latest()) response.headers['content-type'] = CONTENT_TYPE_LATEST return response
Example #17
Source File: service.py From Python-Programming-Blueprints with MIT License | 5 votes |
def create_html_response(content): headers = {'Content-Type': 'text/html'} return Response(content, status=200, headers=headers)
Example #18
Source File: utils.py From RSSNewsGAE with Apache License 2.0 | 5 votes |
def redirect(location, code=302, Response=None): """Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. .. versionadded:: 0.10 The class used for the Response object can now be passed in. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. :param class Response: a Response class to use when instantiating a response. The default is :class:`werkzeug.wrappers.Response` if unspecified. """ if Response is None: from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): # Safe conversion is necessary here as we might redirect # to a broken URI scheme (for instance itms-services). from werkzeug.urls import iri_to_uri location = iri_to_uri(location, safe_conversion=True) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response
Example #19
Source File: exceptions.py From Financial-Portfolio-Flask with MIT License | 5 votes |
def get_response(self, environ=None): """Get a response object. If one was passed to the exception it's returned directly. :param environ: the optional environ for the request. This can be used to modify the response depending on how the request looked like. :return: a :class:`Response` object or a subclass thereof. """ if self.response is not None: return self.response if environ is not None: environ = _get_environ(environ) headers = self.get_headers(environ) return Response(self.get_body(environ), self.code, headers)
Example #20
Source File: exceptions.py From RSSNewsGAE with Apache License 2.0 | 5 votes |
def get_response(self, environ=None): """Get a response object. If one was passed to the exception it's returned directly. :param environ: the optional environ for the request. This can be used to modify the response depending on how the request looked like. :return: a :class:`Response` object or a subclass thereof. """ if self.response is not None: return self.response if environ is not None: environ = _get_environ(environ) headers = self.get_headers(environ) return Response(self.get_body(environ), self.code, headers)
Example #21
Source File: actions.py From flask-calendar with The Unlicense | 5 votes |
def hide_repetition_task_instance_action(calendar_id: str, year: str, month: str, day: str, task_id: str) -> Response: calendar_data = CalendarData(current_app.config["DATA_FOLDER"], current_app.config["WEEK_STARTING_DAY"]) calendar_data.hide_repetition_task_instance( calendar_id=calendar_id, year_str=year, month_str=month, day_str=day, task_id_str=task_id, ) return cast(Response, jsonify({}))
Example #22
Source File: actions.py From flask-calendar with The Unlicense | 5 votes |
def update_task_day_action(calendar_id: str, year: str, month: str, day: str, task_id: str) -> Response: new_day = request.data.decode("utf-8") calendar_data = CalendarData(current_app.config["DATA_FOLDER"], current_app.config["WEEK_STARTING_DAY"]) calendar_data.update_task_day( calendar_id=calendar_id, year_str=year, month_str=month, day_str=day, task_id=int(task_id), new_day_str=new_day, ) return cast(Response, jsonify({}))
Example #23
Source File: actions.py From flask-calendar with The Unlicense | 5 votes |
def delete_task_action(calendar_id: str, year: str, month: str, day: str, task_id: str) -> Response: calendar_data = CalendarData(current_app.config["DATA_FOLDER"], current_app.config["WEEK_STARTING_DAY"]) calendar_data.delete_task( calendar_id=calendar_id, year_str=year, month_str=month, day_str=day, task_id=int(task_id), ) return cast(Response, jsonify({}))
Example #24
Source File: actions.py From flask-calendar with The Unlicense | 5 votes |
def save_task_action(calendar_id: str) -> Response: title = request.form["title"].strip() date = request.form.get("date", "") if len(date) > 0: date_fragments = re.split("-", date) year = int(date_fragments[0]) # type: Optional[int] month = int(date_fragments[1]) # type: Optional[int] day = int(date_fragments[2]) # type: Optional[int] else: year = month = day = None is_all_day = request.form.get("is_all_day", "0") == "1" due_time = request.form["due_time"] details = request.form["details"].replace("\r", "").replace("\n", "<br>") color = request.form["color"] has_repetition = request.form.get("repeats", "0") == "1" repetition_type = request.form.get("repetition_type") repetition_subtype = request.form.get("repetition_subtype") repetition_value = int(request.form["repetition_value"]) calendar_data = CalendarData(current_app.config["DATA_FOLDER"], current_app.config["WEEK_STARTING_DAY"]) calendar_data.create_task( calendar_id=calendar_id, year=year, month=month, day=day, title=title, is_all_day=is_all_day, due_time=due_time, details=details, color=color, has_repetition=has_repetition, repetition_type=repetition_type, repetition_subtype=repetition_subtype, repetition_value=repetition_value, ) if year is None: return redirect("{}/{}/".format(current_app.config["BASE_URL"], calendar_id), code=302) else: return redirect("{}/{}/?y={}&m={}".format(current_app.config["BASE_URL"], calendar_id, year, month), code=302,)
Example #25
Source File: actions.py From flask-calendar with The Unlicense | 5 votes |
def do_login_action() -> Response: username = request.form.get("username", "") password = request.form.get("password", "") authentication = get_authentication() if authentication.is_valid(username, password): session_id = new_session_id() add_session(session_id, username) response = make_response(redirect("/")) cookie_kwargs = { "key": constants.SESSION_ID, "value": session_id, # 1 month "max_age": 2678400, "secure": current_app.config["COOKIE_HTTPS_ONLY"], "httponly": True, } samesite_policy = current_app.config.get("COOKIE_SAMESITE_POLICY", None) # Certain Flask versions don't support 'samesite' param if samesite_policy: cookie_kwargs.update({"samesite": samesite_policy}) response.set_cookie(**cookie_kwargs) return cast(Response, response) else: return redirect("/login")
Example #26
Source File: actions.py From flask-calendar with The Unlicense | 5 votes |
def login_action() -> Response: return cast(Response, render_template("login.html"))
Example #27
Source File: routes.py From dino with Apache License 2.0 | 5 votes |
def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): state = is_authorized() if state is False: if request.path.startswith('/api'): return api_response(400, message="Invalid authentication.") return redirect(internal_url_for('/login')) if isinstance(state, Response): return state return f(*args, **kwargs) return decorated
Example #28
Source File: utils.py From lambda-packs with MIT License | 5 votes |
def redirect(location, code=302, Response=None): """Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. .. versionadded:: 0.10 The class used for the Response object can now be passed in. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. :param class Response: a Response class to use when instantiating a response. The default is :class:`werkzeug.wrappers.Response` if unspecified. """ if Response is None: from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): # Safe conversion is necessary here as we might redirect # to a broken URI scheme (for instance itms-services). from werkzeug.urls import iri_to_uri location = iri_to_uri(location, safe_conversion=True) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response
Example #29
Source File: utils.py From Financial-Portfolio-Flask with MIT License | 5 votes |
def redirect(location, code=302, Response=None): """Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. .. versionadded:: 0.10 The class used for the Response object can now be passed in. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. :param class Response: a Response class to use when instantiating a response. The default is :class:`werkzeug.wrappers.Response` if unspecified. """ if Response is None: from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): # Safe conversion is necessary here as we might redirect # to a broken URI scheme (for instance itms-services). from werkzeug.urls import iri_to_uri location = iri_to_uri(location, safe_conversion=True) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response
Example #30
Source File: controllers.py From indico-plugins with MIT License | 5 votes |
def _process(self): with current_plugin.engine_plugin.plugin_context(): form = current_plugin.search_form(formdata=request.args, prefix='search-', csrf_enabled=False) result = None if form.validate_on_submit(): result = current_plugin.perform_search(form.data, self.obj, self.obj_type) if isinstance(result, Response): # probably a redirect or a json response return result view_class = WPSearchConference if isinstance(self.obj, Event) else WPSearchCategory return view_class.render_template('results.html', self.obj, only_public=current_plugin.only_public, form=form, obj_type=self.obj_type, result=result)