Python flask.helpers.make_response() Examples
The following are 29
code examples of flask.helpers.make_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
flask.helpers
, or try the search function
.
Example #1
Source File: views.py From pyop with Apache License 2.0 | 6 votes |
def token_endpoint(): try: token_response = current_app.provider.handle_token_request(flask.request.get_data().decode('utf-8'), flask.request.headers) return jsonify(token_response.to_dict()) except InvalidClientAuthentication as e: current_app.logger.debug('invalid client authentication at token endpoint', exc_info=True) error_resp = TokenErrorResponse(error='invalid_client', error_description=str(e)) response = make_response(error_resp.to_json(), 401) response.headers['Content-Type'] = 'application/json' response.headers['WWW-Authenticate'] = 'Basic' return response except OAuthError as e: current_app.logger.debug('invalid request: %s', str(e), exc_info=True) error_resp = TokenErrorResponse(error=e.oauth_error, error_description=str(e)) response = make_response(error_resp.to_json(), 400) response.headers['Content-Type'] = 'application/json' return response
Example #2
Source File: views.py From pyop with Apache License 2.0 | 6 votes |
def authentication_endpoint(): # parse authentication request try: auth_req = current_app.provider.parse_authentication_request(urlencode(flask.request.args), flask.request.headers) except InvalidAuthenticationRequest as e: current_app.logger.debug('received invalid authn request', exc_info=True) error_url = e.to_error_url() if error_url: return redirect(error_url, 303) else: # show error to user return make_response('Something went wrong: {}'.format(str(e)), 400) # automagic authentication authn_response = current_app.provider.authorize(auth_req, 'test_user') response_url = authn_response.request(auth_req['redirect_uri'], should_fragment_encode(auth_req)) return redirect(response_url, 303)
Example #3
Source File: views.py From beagle with MIT License | 6 votes |
def get_graph_metadata(graph_id: int): """Returns the metadata for a single graph. This is automatically generated by the datasource classes. Parameters ---------- graph_id : int Graph ID. Returns 404 if the graph ID is not found Returns ------- Dict A dictionary representing the metadata of the current graph. """ graph_obj = Graph.query.filter_by(id=graph_id).first() if not graph_obj: return make_response(jsonify({"message": "Graph not found"}), 404) response = jsonify(graph_obj.meta) return response
Example #4
Source File: apiserver.py From cargo with Apache License 2.0 | 5 votes |
def post(self, nodeid, containerid): rc = reqHandler.doFailover(nodeid, containerid) return make_response("", codes.herror(rc))
Example #5
Source File: views.py From pyop with Apache License 2.0 | 5 votes |
def do_logout(end_session_request): try: current_app.provider.logout_user(end_session_request=end_session_request) except InvalidSubjectIdentifier as e: return make_response('Logout unsuccessful!', 400) redirect_url = current_app.provider.do_post_logout_redirect(end_session_request) if redirect_url: return redirect(redirect_url, 303) return make_response('Logout successful!')
Example #6
Source File: views.py From pyop with Apache License 2.0 | 5 votes |
def userinfo_endpoint(): try: response = current_app.provider.handle_userinfo_request(flask.request.get_data().decode('utf-8'), flask.request.headers) return jsonify(response.to_dict()) except (BearerTokenError, InvalidAccessToken) as e: error_resp = UserInfoErrorResponse(error='invalid_token', error_description=str(e)) response = make_response(error_resp.to_json(), 401) response.headers['WWW-Authenticate'] = AccessToken.BEARER_TOKEN_TYPE response.headers['Content-Type'] = 'application/json' return response
Example #7
Source File: views.py From pyop with Apache License 2.0 | 5 votes |
def registration_endpoint(): try: response = current_app.provider.handle_client_registration_request(flask.request.get_data().decode('utf-8')) return make_response(jsonify(response.to_dict()), 201) except InvalidClientRegistrationRequest as e: return make_response(jsonify(e.to_dict()), status=400)
Example #8
Source File: views.py From JWTConnect-Python-OidcRP with Apache License 2.0 | 5 votes |
def get_rp(op_hash): try: _iss = current_app.rph.hash2issuer[op_hash] except KeyError: logger.error('Unkown issuer: {} not among {}'.format( op_hash, list(current_app.rph.hash2issuer.keys()))) return make_response("Unknown hash: {}".format(op_hash), 400) else: try: rp = current_app.rph.issuer2rp[_iss] except KeyError: return make_response("Couldn't find client for {}".format(_iss), 400) return rp
Example #9
Source File: views.py From JWTConnect-Python-OidcRP with Apache License 2.0 | 5 votes |
def rp(): try: iss = request.args['iss'] except KeyError: link = '' else: link = iss try: uid = request.args['uid'] except KeyError: uid = '' if link or uid: if uid: args = {'user_id': uid} else: args = {} session['op_hash'] = link try: result = current_app.rph.begin(link, **args) except Exception as err: return make_response('Something went wrong:{}'.format(err), 400) else: return redirect(result['url'], 303) else: _providers = current_app.rp_config.clients.keys() return render_template('opbyuid.html', providers=_providers)
Example #10
Source File: render.py From love with MIT License | 5 votes |
def make_json_response(data, *args): response = make_response(json.dumps(data), *args) response.headers['Content-Type'] = 'application/json' return response
Example #11
Source File: decorators.py From love with MIT License | 5 votes |
def api_key_required(f): @wraps(f) def decorated_function(*args, **kwargs): api_key = request.form.get('api_key') or request.args.get('api_key') valid_api_key = False if api_key is not None: valid_api_key = AccessKey.query(AccessKey.access_key == api_key).get(keys_only=True) is not None if not valid_api_key: return make_response('Invalid API Key', 401, { 'WWWAuthenticate': 'Basic realm="Login Required"', }) return f(*args, **kwargs) return decorated_function
Example #12
Source File: views.py From beagle with MIT License | 5 votes |
def get_graph(graph_id: int): # pragma: no cover - hard to test due to building path. """Returns the JSON object for this graph. This is a networkx node_data JSON dump: >>> { directed: boolean, links: [ {...} ], multigraph: boolean, nodes: [ {...} ] } Returns 404 if the graph is not found. Parameters ---------- graph_id : int The graph ID to fetch data for Returns ------- Dict See https://networkx.github.io/documentation/stable/reference/readwrite/generated/networkx.readwrite.json_graph.node_link_graph.html """ graph_obj = Graph.query.filter_by(id=graph_id).first() if not graph_obj: return make_response(jsonify({"message": "Graph not found"}), 404) dest_path = f"{Config.get('storage', 'dir')}/{graph_obj.category}/{graph_obj.file_path}" json_data = json.load(open(dest_path, "r")) response = jsonify(json_data) return response
Example #13
Source File: views.py From beagle with MIT License | 5 votes |
def get_category_items(category: str): # pragma: no cover """Returns the set of items that exist in this category, the path to their JSON files, the comment made on them, as well as their metadata. >>> { comment: str, file_path: str, id: int, metadata: Dict[str, Any] } Returns 404 if the category is invalid. Parameters ---------- category : str The category to fetch data for. Returns ------- List[dict] """ if category not in set( [source.category.replace(" ", "_").lower() for source in DATASOURCES.values()] ): return make_response(jsonify({"message": "Category not found"}), 404) # Return reversed. category_data = [graph.to_json() for graph in Graph.query.filter_by(category=category).all()] category_data = category_data[::-1] response = jsonify(category_data) return response
Example #14
Source File: openmoves.py From openmoves with MIT License | 5 votes |
def export_move(id): move = Move.query.filter_by(id=id).first_or_404() if not move.public and move.user != current_user: return app.login_manager.unauthorized() if "format" in request.args: format = request.args.get("format").lower() else: format = "gpx" # default format_handlers = {'gpx': gpx_export.gpx_export, 'csv': csv_export.csv_export} if format not in format_handlers: flash("Export format %s not supported" % format, 'error') return redirect(url_for('move', id=id)) export_file = format_handlers[format](move) if not export_file: return redirect(url_for('move', id=id)) # app.logger.debug("Move export (format %s):\n%s" % (format, export_file)) response = make_response(export_file) date_time = move.date_time.strftime('%Y-%m-%dT%H_%M_%S') if move.location_raw: address = move.location_raw['address'] city = get_city(address) country_code = address['country_code'].upper() filename = "Move_%s_%s_%s_%s.%s" % (date_time, country_code, city, move.activity, format) else: filename = "Move_%s_%s.%s" % (date_time, move.activity, format) response.headers['Content-Disposition'] = "attachment; filename=%s" % (quote_plus(filename)) return response
Example #15
Source File: apiserver.py From cargo with Apache License 2.0 | 5 votes |
def post(self, containerid): payload = request.data rc = reqHandler.updateStatus(containerid, payload) return make_response("", codes.herror(rc))
Example #16
Source File: apiserver.py From cargo with Apache License 2.0 | 5 votes |
def get(self, containerid): rc, msg = reqHandler.getStatus(containerid) return make_response(msg, codes.herror(rc))
Example #17
Source File: apiserver.py From cargo with Apache License 2.0 | 5 votes |
def delete(self): return make_response("", 200)
Example #18
Source File: apiserver.py From cargo with Apache License 2.0 | 5 votes |
def post(self): migreq = json.loads(request.data) rc = reqHandler.migrate(migreq) return make_response("", codes.herror(rc))
Example #19
Source File: apiserver.py From cargo with Apache License 2.0 | 5 votes |
def get(self): rc, msg = reqHandler.getAllContainers() return make_response(msg, codes.herror(rc))
Example #20
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def post(self, containerId): rc = reqHandler.doFailover(containerId) return make_response("", codes.herror(rc))
Example #21
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def delete(self, containerId, volumeId): rc = reqHandler.stopReplication(containerId, volumeId) return make_response("", codes.herror(rc))
Example #22
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def post(self, containerId, volumeId): payload = request.data idfile = os.path.join(CONFIG_DIR, AGENT_IDFILE) with open(idfile, 'r') as infile: for line in infile: nodeId = line rc = reqHandler.startReplication(containerId, volumeId, nodeId, cargoServer, payload) return make_response("", codes.herror(rc))
Example #23
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def get(self): config = request.data rc, msg = reqHandler.handleFSOp(config) return make_response(json.dumps(msg), codes.herror(rc))
Example #24
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def delete(self): rc = reqHandler.deleteContainer(None, containerId) return make_response("", 200)
Example #25
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def post(self, containerId): reqData = request.data rc = reqHandler.handleContainerOp(reqData, containerId) return make_response("", codes.herror(rc))
Example #26
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def get(self, containerId): rc, msg = reqHandler.getContainer(containerId) return make_response(msg, codes.herror(rc))
Example #27
Source File: agent.py From cargo with Apache License 2.0 | 5 votes |
def get(self): rc, msg = reqHandler.getAllContainers() return make_response(json.dumps(msg), codes.herror(rc))
Example #28
Source File: views.py From edwin with Apache License 2.0 | 4 votes |
def raw_svgs(): chart = pygal.Line(legend_at_bottom=True, legend_box_size=18) # ======================================= # Declare the location of svg.jquery.js and pygal-tooltips.js in server side. # ======================================= # It must be declare in server side, not html file # if not declare in server, by default it will load the two js files located in http://kozea.github.com/pygal.js. And it will slow down the page loading # 1, It works, load local js files SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) chart.js = [os.path.join(SITE_ROOT, "static/js/", "svg.jquery.js"), os.path.join(SITE_ROOT, "static/js/", "pygal-tooltips.js")] # 2.a, It Works, but it is ugly because it use local absolute http url # chart.js =['http://127.0.0.1:5000/static/js/svg.jquery.js', # 'http://127.0.0.1:5000/static/js/pygal-tooltips.js'] # 2.b, works, use local CDN absolute http url # chart.js =['http://another_server/pygal-tooltips.js', # 'http://another_server/svg.jquery.js'] # 3, Does not work, error raised at visiting, IOError: [Errno 2] No such file # chart.js = [url_for('static', filename='js/svg.jquery.js'), # url_for('static', filename='js/pygal-tooltips.js')] # disable xml root node chart.disable_xml_declaration = True chart.title = 'Browser usage evolution (in %)' chart.width = 2000 chart.height = 2000 chart.x_labels = map(str, range(2002, 2013)) chart.add('Firefox', [None, None, 0, 16.6, 25, 31, 36.4, 45.5, 46.3, 42.8, 37.1]) chart.add('Chrome', [None, None, None, None, None, None, 0, 3.9, 10.8, 23.8, 35.3]) chart.add('IE', [85.8, 84.6, 84.7, 74.5, 66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1]) chart.add('Others', [14.2, 15.4, 15.3, 8.9, 9, 10.4, 8.9, 5.8, 6.7, 6.8, 7.5]) svg_xml = chart.render() svg_xml = '<svg style="width:2000px" ' + svg_xml[4:] svg_xml1 = svg_xml[:100] response = make_response(render_template('test_svg.html', title=svg_xml1, svg_xml=svg_xml)) # response.headers['Content-Type']='image/svg+xml' 不能设置Content-Type为svg模式 return response
Example #29
Source File: views.py From JWTConnect-Python-OidcRP with Apache License 2.0 | 4 votes |
def finalize(op_hash, request_args): rp = get_rp(op_hash) if hasattr(rp, 'status_code') and rp.status_code != 200: logger.error(rp.response[0].decode()) return rp.response[0], rp.status_code session['client_id'] = rp.service_context.get('client_id') session['state'] = request_args.get('state') if session['state']: iss = rp.session_interface.get_iss(session['state']) else: return make_response('Unknown state', 400) session['session_state'] = request_args.get('session_state', '') logger.debug('Issuer: {}'.format(iss)) try: res = current_app.rph.finalize(iss, request_args) except OidcServiceError as excp: # replay attack prevention, is that code was already used before return excp.__str__(), 403 except Exception as excp: raise excp if 'userinfo' in res: endpoints = {} for k, v in rp.service_context.get('provider_info').items(): if k.endswith('_endpoint'): endp = k.replace('_', ' ') endp = endp.capitalize() endpoints[endp] = v kwargs = {} # Do I support session status checking ? _status_check_info = rp.service_context.add_on.get('status_check') if _status_check_info: # Does the OP support session status checking ? _chk_iframe = rp.service_context.get('provider_info').get('check_session_iframe') if _chk_iframe: kwargs['check_session_iframe'] = _chk_iframe kwargs["status_check_iframe"] = _status_check_info['rp_iframe_path'] # Where to go if the user clicks on logout kwargs['logout_url'] = "{}/logout".format(rp.service_context.base_url) return render_template('opresult.html', endpoints=endpoints, userinfo=res['userinfo'], access_token=res['token'], **kwargs) else: return make_response(res['error'], 400)