Python flask.request.url() Examples
The following are 30
code examples of flask.request.url().
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.request
, or try the search function
.
Example #1
Source File: google.py From app with MIT License | 12 votes |
def google_login(): # to avoid flask-login displaying the login error message session.pop("_flashes", None) next_url = request.args.get("next") # Google does not allow to append param to redirect_url # we need to pass the next url by session if next_url: session["google_next_url"] = next_url google = OAuth2Session(GOOGLE_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri) authorization_url, state = google.authorization_url(_authorization_base_url) # State is used to prevent CSRF, keep this for later. session["oauth_state"] = state return redirect(authorization_url)
Example #2
Source File: server.py From grlc with MIT License | 8 votes |
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None): """Execute SPARQL query for a specific grlc-generated API endpoint""" glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha)) glogger.debug("Request accept header: " + request.headers["Accept"]) requestArgs = request.args acceptHeader = request.headers['Accept'] requestUrl = request.url formData = request.form query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url, sha=sha, content=content, requestArgs=requestArgs, acceptHeader=acceptHeader, requestUrl=requestUrl, formData=formData) if isinstance(query_response, list): query_response = jsonify(query_response) return make_response(query_response, status, headers) ### Server routes ###
Example #3
Source File: oauth_tester.py From app with MIT License | 7 votes |
def callback(): """ Step 3: Retrieving an access token. The user has been redirected back from the provider to your registered callback URL. With this redirection comes an authorization code included in the redirect URL. We will use that to obtain an access token. """ simplelogin = OAuth2Session(client_id, state=session["oauth_state"]) token = simplelogin.fetch_token( token_url, client_secret=client_secret, authorization_response=request.url ) # At this point you can fetch protected resources but lets save # the token and show how this is done from a persisted token # in /profile. session["oauth_token"] = token return redirect(url_for(".profile"))
Example #4
Source File: facebook.py From app with MIT License | 7 votes |
def facebook_login(): # to avoid flask-login displaying the login error message session.pop("_flashes", None) next_url = request.args.get("next") # Facebook does not allow to append param to redirect_uri # we need to pass the next url by session if next_url: session["facebook_next_url"] = next_url facebook = OAuth2Session( FACEBOOK_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri ) facebook = facebook_compliance_fix(facebook) authorization_url, state = facebook.authorization_url(_authorization_base_url) # State is used to prevent CSRF, keep this for later. session["oauth_state"] = state return redirect(authorization_url)
Example #5
Source File: zmirror.py From zmirror with MIT License | 6 votes |
def update_content_in_local_cache(url, content, method='GET'): """更新 local_cache 中缓存的资源, 追加content 在stream模式中使用""" if local_cache_enable and method == 'GET' and cache.is_cached(url): info_dict = cache.get_info(url) resp = cache.get_obj(url) resp.set_data(content) # 当存储的资源没有完整的content时, without_content 被设置为true # 此时该缓存不会生效, 只有当content被添加后, 缓存才会实际生效 # 在stream模式中, 因为是先接收http头, 然后再接收内容, 所以会出现只有头而没有内容的情况 # 此时程序会先将只有头部的响应添加到本地缓存, 在内容实际接收完成后再追加内容 info_dict['without_content'] = False if verbose_level >= 4: dbgprint('LocalCache_UpdateCache', url, content[:30], len(content)) cache.put_obj( url, resp, obj_size=len(content), expires=get_expire_from_mime(parse.mime), last_modified=info_dict.get('last_modified'), info_dict=info_dict, )
Example #6
Source File: advisory.py From arch-security-tracker with MIT License | 6 votes |
def advisory_atom(): return not_found() last_recent_entries = 15 data = get_advisory_data()['published'][:last_recent_entries] # TODO:fix me feed = AtomFeed('Arch Linux Security - Recent advisories', feed_url=request.url, url=request.url_root) for entry in data: advisory = entry['advisory'] package = entry['package'] title = '[{}] {}: {}'.format(advisory.id, package.pkgname, advisory.advisory_type) feed.add(title=title, content=render_template('feed.html', content=advisory.content), content_type='html', summary=render_template('feed.html', content=advisory.impact), summary_tpe='html', author='Arch Linux Security Team', url=TRACKER_ISSUE_URL.format(advisory.id), published=advisory.created, updated=advisory.created) return feed.get_response()
Example #7
Source File: routes.py From AUCR with GNU General Public License v3.0 | 6 votes |
def upload_file(): """Return File Upload flask app analysis blueprint.""" if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also submit a empty part without filename if file.filename == '': flash('No selected file, or that file type is not supported') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file_hash = get_upload_file_hash(file) flash("The " + str(filename) + " md5:" + file_hash + " has been uploaded!") return render_template('upload_file.html', title='Upload File')
Example #8
Source File: views.py From FXTest with MIT License | 6 votes |
def post(self): data = request.get_json() project = data['project'] model = data['model'] name = data['name'] url = data['url'] headers = data['headers'] xieyi = data['xieyi'] meth = data['meth'] project_id = Project.query.filter_by(project_name=project).first().id models_id = Model.query.filter_by(model_name=model).first().id try: new_interface = Interface(model_id=models_id, projects_id=project_id, Interface_name=name, Interface_url=url, Interface_meth=meth, Interface_user_id=current_user.id, Interface_headers=headers, interfacetype=xieyi) db.session.add(new_interface) db.session.commit() return jsonify({'data': interface_add_success, 'code': 2}) except Exception as e: db.session.rollback() return jsonify({'data': interface_add_erroe, 'code': 3})
Example #9
Source File: views.py From FXTest with MIT License | 6 votes |
def post(self): data = request.get_json() json_data = data project = json_data['project'] url = json_data['url'] desc = json_data['desc'] name = json_data['name'] host = json_data['host'] port = json_data['port'] usernmae = json_data['username'] password = json_data['password'] url_old = Interfacehuan.query.filter_by(url=str(url)).first() if url_old: return jsonify({"msg": u'测试环境必须是相互独立的', "code": 209, 'data': ''}) prkcyt = Project.query.filter_by(project_name=project).first() end = Interfacehuan(url=url, desc=desc, project=prkcyt.id, database=name, databaseuser=usernmae, databasepassword=password, dbhost=host, dbport=port, make_user=current_user.id) db.session.add(end) try: db.session.commit() return jsonify({"data": u'添加测试环境成功!', "code": 2}) except Exception as e: db.session.rollback() return jsonify({"data": u'添加测试用例失败!原因:%s' % e, "code": 211})
Example #10
Source File: decorators.py From flask-security with MIT License | 6 votes |
def default_reauthn_handler(within, grace): """ Default callback for 'freshness' related authn failures. If caller wants JSON - return 401 Otherwise - assume caller is html and redirect if possible to configured view. """ m, c = get_message("REAUTHENTICATION_REQUIRED") if _security._want_json(request): is_us = config_value("UNIFIED_SIGNIN") payload = json_error_response(errors=m) payload["reauth_required"] = True payload["unified_signin_enabled"] = is_us return _security._render_json(payload, 401, None, None) if config_value("UNIFIED_SIGNIN"): view = _security.us_verify_url else: view = _security.verify_url if view: do_flash(m, c) redirect_url = get_url(view, qparams={"next": request.url}) return redirect(redirect_url) abort(401)
Example #11
Source File: client.py From Flask-Discord with MIT License | 6 votes |
def callback(self): """A method which should be always called after completing authorization code grant process usually in callback view. It fetches the authorization token and saves it flask `session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_ object. """ if request.values.get("error"): return request.values["error"] discord = self._make_session(state=session.get("DISCORD_OAUTH2_STATE")) token = discord.fetch_token( configs.DISCORD_TOKEN_URL, client_secret=self.client_secret, authorization_response=request.url ) self._token_updater(token)
Example #12
Source File: __init__.py From flask-oidc with BSD 2-Clause "Simplified" License | 6 votes |
def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """ @wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated # Backwards compatibility
Example #13
Source File: app.py From SolveSudoku with MIT License | 6 votes |
def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) filename = str(uuid.uuid4()) + "." + filename.split('.')[1] file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file', filename=filename)) return render_template("home.html")
Example #14
Source File: webhook.py From Matrix-NEB with Apache License 2.0 | 6 votes |
def do_POST(self, service=""): log.debug("NebHookServer: Plugin=%s : Incoming request from %s", service, request.remote_addr) if service.split("/")[0] not in self.plugin_mappings: return ("", 404, {}) plugin = self.plugin_mappings[service.split("/")[0]] try: # tuple (body, status_code, headers) response = plugin.on_receive_webhook( request.url, request.get_data(), request.remote_addr, request.headers ) if response: return response return ("", 200, {}) except Exception as e: log.exception(e) return ("", 500, {})
Example #15
Source File: __init__.py From flask-oidc with BSD 2-Clause "Simplified" License | 6 votes |
def validate_token(self, token, scopes_required=None): """ This function can be used to validate tokens. Note that this only works if a token introspection url is configured, as that URL will be queried for the validity and scopes of a token. :param scopes_required: List of scopes that are required to be granted by the token before returning True. :type scopes_required: list :returns: True if the token was valid and contained the required scopes. An ErrStr (subclass of string for which bool() is False) if an error occured. :rtype: Boolean or String .. versionadded:: 1.1 """ valid = self._validate_token(token, scopes_required) if valid is True: return True else: return ErrStr(valid)
Example #16
Source File: zmirror.py From zmirror with MIT License | 6 votes |
def request_remote_site(): """ 请求远程服务器(high-level), 并在返回404/500时进行 domain_guess 尝试 """ # 请求被镜像的网站 # 注意: 在zmirror内部不会处理重定向, 重定向响应会原样返回给浏览器 parse.remote_response = send_request( parse.remote_url, method=request.method, headers=parse.client_header, data=parse.request_data_encoded, ) if parse.remote_response.url != parse.remote_url: warnprint("requests's remote url", parse.remote_response.url, 'does no equals our rewrited url', parse.remote_url) if 400 <= parse.remote_response.status_code <= 599: # 猜测url所对应的正确域名 dbgprint("Domain guessing for", request.url) result = guess_correct_domain() if result is not None: parse.remote_response = result
Example #17
Source File: zmirror.py From zmirror with MIT License | 6 votes |
def extract_url_path_and_query(full_url=None, no_query=False): """ Convert http://foo.bar.com/aaa/p.html?x=y to /aaa/p.html?x=y :param no_query: :type full_url: str :param full_url: full url :return: str """ if full_url is None: full_url = request.url split = urlsplit(full_url) result = split.path or "/" if not no_query and split.query: result += '?' + split.query return result # ################# End Client Request Handler ################# # ################# Begin Middle Functions #################
Example #18
Source File: views.py From oadoi with MIT License | 6 votes |
def bookmarklet_js(): base_url = request.url.replace( "browser-tools/bookmarklet.js", "static/browser-tools/" ) if "localhost:" not in base_url: # seems like this shouldn't be necessary. but i think # flask's request.url is coming in with http even when # we asked for https on the server. weird. base_url = base_url.replace("http://", "https://") rendered = render_template( "browser-tools/bookmarklet.js", base_url=base_url ) resp = make_response(rendered, 200) resp.mimetype = "application/javascript" return resp
Example #19
Source File: zmirror.py From zmirror with MIT License | 6 votes |
def try_get_cached_response(url, client_header=None): """ 尝试从本地缓存中取出响应 :param url: real url with query string :type client_header: dict :rtype: Union[Response, None] """ # Only use cache when client use GET if local_cache_enable and parse.method == 'GET' and cache.is_cached(url): if client_header is not None and 'if-modified-since' in client_header and \ cache.is_unchanged(url, client_header.get('if-modified-since', None)): dbgprint('FileCacheHit-304', url) return generate_304_response() else: cached_info = cache.get_info(url) if cached_info.get('without_content', True): # 关于 without_content 的解释, 请看update_content_in_local_cache()函数 return None # dbgprint('FileCacheHit-200') resp = cache.get_obj(url) assert isinstance(resp, Response) parse.set_extra_resp_header('x-zmirror-cache', 'FileHit') return resp else: return None
Example #20
Source File: info.py From appr with Apache License 2.0 | 5 votes |
def routes(): import urllib output = [] for rule in current_app.url_map.iter_rules(): options = {} for arg in rule.arguments: options[arg] = "[{0}]".format(arg) methods = ','.join(rule.methods) url = url_for(rule.endpoint, **options) line = urllib.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url)) output.append(line) lines = [] for line in sorted(output): lines.append(line) return jsonify({"routes": lines})
Example #21
Source File: info.py From appr with Apache License 2.0 | 5 votes |
def pre_request_logging(): jsonbody = request.get_json(force=True, silent=True) values = request.values.to_dict() if jsonbody: values.update(jsonbody) current_app.logger.info("request", extra={ "remote_addr": request.remote_addr, "http_method": request.method, "original_url": request.url, "path": request.path, "data": values, "headers": dict(request.headers.to_list())})
Example #22
Source File: __init__.py From cloud-inquisitor with Apache License 2.0 | 5 votes |
def get(self): def dscb(): session.clear() url = self.auth.process_slo(delete_session_cb=dscb) errors = self.auth.get_errors() if len(errors) == 0: if url: return self.auth.redirect_to(url) return redirect('/logout')
Example #23
Source File: __init__.py From cloud-inquisitor with Apache License 2.0 | 5 votes |
def _prepare_flask_request(): # If server is behind proxys or balancers use the HTTP_X_FORWARDED fields url_data = urlparse(request.url) port = url_data.port or (443 if request.scheme == 'https' else 80) return { 'https': 'on' if request.scheme == 'https' else 'off', 'http_host': request.host, 'server_port': port, 'script_name': request.path, 'get_data': request.args.copy(), 'post_data': request.form.copy() }
Example #24
Source File: registry.py From appr with Apache License 2.0 | 5 votes |
def pre_request_logging(): jsonbody = request.get_json(force=True, silent=True) values = request.values.to_dict() if jsonbody: values.update(jsonbody) current_app.logger.info("request", extra={ "remote_addr": request.remote_addr, "http_method": request.method, "original_url": request.url, "path": request.path, "data": values, "headers": dict(request.headers.to_list())})
Example #25
Source File: app.py From age-of-empires-II-api with BSD 3-Clause "New" or "Revised" License | 5 votes |
def show_resources(): resources = [('civilizations', '{}/civilizations'.format(request.url)), ('units', '{}/units'.format(request.url)), ('structures', '{}/structures'.format(request.url)), ('technologies', '{}/technologies'.format(request.url)) ] return jsonify({'resources': OrderedDict(resources)})
Example #26
Source File: views.py From oadoi with MIT License | 5 votes |
def repo_pulse_test_url(url): from endpoint import test_harvest_url response = test_harvest_url(url) results = { "check0_identify_status": response["harvest_identify_response"], "check1_query_status": response["harvest_test_recent_dates"], "sample_pmh_record": response["sample_pmh_record"] } return jsonify({"results": results})
Example #27
Source File: app.py From shamer with MIT License | 5 votes |
def preprocess_request(): if request.endpoint in {'redirect_view', 'proxy_view', 'pending_view', 'leaderboard_view', 'user_leaderboard_view'}: if request.view_args.get('object_key'): session['object_key'] = request.view_args.get('object_key') if session.get('verified') != True: session['next'] = request.url return redirect(url_for('login_view')) if session.get('next'): return redirect(session.pop('next')) if not s3: flash('Your S3 keys are invalid!', 'danger') return 'Your S3 keys are invalid!'
Example #28
Source File: api.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def add_cors_headers(response): """Allow any application to logout""" # if 'logout' in request.url: response.headers['Access-Control-Allow-Origin'] = '*' if request.method == 'OPTIONS': response.headers['Access-Control-Allow-Methods'] = ( 'DELETE, GET, POST, PUT' ) headers = request.headers.get('Access-Control-Request-Headers') if headers: response.headers['Access-Control-Allow-Headers'] = headers return response
Example #29
Source File: admin.py From website with MIT License | 5 votes |
def inaccessible_callback(self, name, **kwargs): # redirect to login page if user doesn't have access session["next_url"] = request.url return redirect(url_for("github.login"))
Example #30
Source File: experiment_server.py From Dallinger with MIT License | 5 votes |
def node_vectors(node_id): """Get the vectors of a node. You must specify the node id in the url. You can pass direction (incoming/outgoing/all) and failed (True/False/all). """ exp = Experiment(session) # get the parameters direction = request_parameter(parameter="direction", default="all") failed = request_parameter(parameter="failed", parameter_type="bool", default=False) for x in [direction, failed]: if type(x) == Response: return x # execute the request node = models.Node.query.get(node_id) if node is None: return error_response(error_type="/node/vectors, node does not exist") try: vectors = node.vectors(direction=direction, failed=failed) exp.vector_get_request(node=node, vectors=vectors) session.commit() except Exception: return error_response( error_type="/node/vectors GET server error", status=403, participant=node.participant, ) # return the data return success_response(vectors=[v.__json__() for v in vectors])