def redirect( where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, _anchor: Optional[str] = None, _cls: Optional[Union[object, type]] = None, _external: Optional[bool] = False, _external_host: Optional[str] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values, ) -> Response: """ An improved version of flask's redirect function :param where: A URL, endpoint, or config key name to redirect to :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, allows a method name to be passed to where, default, and/or override :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, _external_host=_external_host, _method=_method, _scheme=_scheme, **values) urls = [ url_for(request.args.get('next'), **flask_url_for_kwargs), url_for(request.form.get('next'), **flask_url_for_kwargs) ] if where: urls.append(url_for(where, _cls=_cls, **flask_url_for_kwargs)) if default: urls.append(url_for(default, _cls=_cls, **flask_url_for_kwargs)) if override: urls.insert(0, url_for(override, _cls=_cls, **flask_url_for_kwargs)) for url in urls: if _validate_redirect_url(url, _external_host): return flask_redirect(url) return flask_redirect('/')
def validation_error(path=None): if choose_media_type(acceptable_media_types(request), [html]): if path: return flask_redirect(path) else: return flask_redirect(request.referrer) else: return render_json({'errors': get_flashed_messages()})
def validation_error(path=None): if should_render_as_html(): if path: return flask_redirect(path) return flask_redirect(request.referrer) return render_json({'errors': get_flashed_messages()})
def add_system(): # We accept JSON or form-encoded for convenience if request.json: if 'fqdn' not in request.json: raise BadRequest400('Missing fqdn key') new_fqdn = request.json['fqdn'] elif request.form: if 'fqdn' not in request.form: raise BadRequest400('Missing fqdn parameter') new_fqdn = request.form['fqdn'] else: raise UnsupportedMediaType415 with convert_internal_errors(): if System.query.filter(System.fqdn == new_fqdn).count() != 0: raise Conflict409('System with fqdn %r already exists' % new_fqdn) system = System(fqdn=new_fqdn, owner=identity.current.user) session.add(system) # new systems are visible to everybody by default system.custom_access_policy = SystemAccessPolicy() system.custom_access_policy.add_rule(SystemPermission.view, everybody=True) # XXX this should be 201 with Location: /systems/FQDN/ but 302 is more # convenient because it lets us use a traditional browser form without AJAX # handling, and for now we're redirecting to /view/FQDN until that is moved # to /systems/FQDN/ return flask_redirect(url(u'/view/%s#essentials' % system.fqdn))
def search(query): if g.user is not None and is_email(query): g.user.set_hide_search_hint() return flask_redirect(url_for("page", title=query)) title = name_to_title(query) can_create = False try: Page.find(title) except PageNotFound: can_create = g.user is not None and g.user.can_create if g.user is not None: bookmarks_pages = BookmarksPage.search(query) search_pages = [ page for page in Page.search(query) if page not in bookmarks_pages ] pages = bookmarks_pages + search_pages else: pages = Page.search(query) return render_template( "search.html", pages=pages, query=query, can_create=can_create, title_to_create=title, )
def skip_interstitial(url, *args, **kwargs): if url == url_for('main.to_idp'): idp = session.get('suggested_idp') url = url_for('broker.auth', idp_hint=idp) return flask_redirect(url, *args, **kwargs)
def redirects_middleware(): from_url = RedirectModel.normalize_url(request.url) redirect = RedirectModel.query.filter_by( from_url=from_url).one_or_none() if redirect is not None: status = 301 if redirect.permanent else 307 return flask_redirect(redirect.url, code=status)
def groups_mine(): """ Redirect for compatibility. """ return flask_redirect( absolute_url('/groups/', q='member.user_name:%s' % identity.current.user.user_name))
def d1(*args, **kwargs): if session.get(logged_in_key) is None: return flask_redirect(url_for(redirect_endpoint, **redirect_kwargs)) if datetime.now()>session['oauth_token_expires']: prov = PROVIDERS[session['oauth_provider']] prov.refresh() return fn(*args, **kwargs)
def redirect(url, status_code=302, output_format=None, data_structure=None): if not output_format: output_format = _desired_format() if output_format == "json": data = {"next_page": url} data.update(data_structure) return render_response(None, data, output_format="json") return flask_redirect(url, code=status_code)
def wrapped_fun(*args, **kwargs): try: return fun(*args, **kwargs) except Malformed as e: abort(400) except NotAllowed: # abort(401) return flask_redirect(url_for("recent")) except PageNotFound: abort(404)
def redirect(url, status_code=302, output_format=None, data_structure=None): if not output_format: output_format = _desired_format() if output_format == 'json': data = {'next_page': url} data.update(data_structure) return render_response(None, data, output_format='json') return flask_redirect(url, code=status_code)
def redirect(autoimage_slug: ObjectId, method: str): """only for public images (user not forwarded)""" if method not in ["http", "torrent", "magnet"]: raise errors.NotFound() response = json_document(autoimage_slug) if response.status_code != 200: return response return flask_redirect(location=response.get_json()[f"{method}_url"], code=302)
def authorize(apikey, provider, return_url, code, redirect): server_api_key = os.getenv("API_KEY", "") # print("server api key:", server_api_key, ", request api key:", apikey, flush=True) if apikey != server_api_key: return "Unauthorized", 401 providers = os.getenv("PROVIDERS", "") if not providers: return "No provider is supported", 500 providers = json.loads(providers) if provider not in providers.keys(): return "requested provider is not supported", 500 auth_url = providers[provider]['AUTH_URL'] if not code and 'LOGIN_URL' not in providers[provider]: return "Fail to authenticate: no token code is provided for the provider", 400 q_auth_url = f"{auth_url}?code={code}" r = requests.get(q_auth_url) if return_url.endswith('/'): return_url = return_url[:-1] if r.status_code == 200: r_json = r.json() # print(r_json, flush=True) if redirect: key_val_str = '' for key, val in r.json().items(): key_val_str = f"{key_val_str}&{key}={val}" redirect_url = f"{return_url}?status=success{key_val_str}" #return redirect_url, 200 return flask_redirect(redirect_url) else: return r_json else: r_json = {'content': str(r.content), 'status_code': r.status_code} # print(r_json, flush=True) if redirect: # print(r.status_code, r.content, flush=True) status_code = r.status_code redirect_url = f"{return_url}?status=failure&status_code={status_code}" # return redirect_url, status_code return flask_redirect(redirect_url) else: return r_json, r.status_code
def get_recipe_log(id, path): """ Redirects to the actual storage location for the requested recipe log. :param id: Recipe's id. :param path: Log path. """ recipe = _get_recipe_by_id(id) for log in recipe.logs: if log.combined_path == path: return flask_redirect(log.absolute_url, code=307) return NotFound404('Recipe log %s for recipe %s not found' % (path, id))
def get_group_by_id_or_name(): """ Created for backwards compatibility. Will redirect to /groups/<group_name>. :queryparam group_id: Group's id. :queryparam group_name: Group's name. """ if 'group_id' in request.args: with convert_internal_errors(): group = Group.by_id(request.args['group_id']) elif 'group_name' in request.args: group = _get_group_by_name(request.args['group_name']) else: raise NotFound404 return flask_redirect(absolute_url(group.href))
def redirect(location, code=302): """Redirect the client to a desired location. Behaves the same as Flask's :func:`flask.redirect` function with an awareness of OSF view-only links. IMPORTANT: This function should always be used instead of flask.redirect to ensure the correct behavior of view-only links. """ view_only = request.args.get('view_only', '') if view_only: url = furl.furl(location) url.args['view_only'] = view_only location = url.url return flask_redirect(location, code=code)
def init_login(verify_endpoint, redirect=False, *args): def d0(fn): @wraps(fn) def d1(provider): # get any extra arguments on the query path _args = dict([(a, request.args[a]) for a in args if a in request.args]) callback = url_for(verify_endpoint, provider=provider, _external=True, **_args) redirect_url = api.init_login(provider, callback) # abort should stop us from getting here if we won't have a 'redirect' key return fn(redirect_url) return d1 # if redirect is True, then return an instance of the decorator # that automatically does the flask redirection if redirect: return d0(lambda url: flask_redirect(url)) return d0
def redirect(*args, **kws): code = kws.pop("code", 302) try: to = args[0] or kws.pop("to", "/") except IndexError as e: to = "/" from werkzeug import exceptions from flask import current_app, request if current_app.is_ssl_request() and not to.startswith('https'): try: endpoint = current_app.url_map.bind(request.host, to).match()[0] if endpoint in current_app.ssl_required_endpoints: to = "https://%s%s" % (request.host, to) except exceptions.NotFound as e: pass return flask_redirect(to, code=code)
def redirect(location, **kwargs): """assembles kwargs as querystring""" kwargs = ['%s=%s' % pair for pair in kwargs.items()] location = location + '?' + '&'.join(kwargs) return flask_redirect(location)
def un_authorized_response_or_redirect(self): if self.redirect: from flask import redirect as flask_redirect return flask_redirect('/') return un_authorized_response()
def redirect(url=None): url = url or request.args.get('referer', '/') return flask_redirect(url)
def redirect(data, path): if choose_media_type(acceptable_media_types(request), [html]): return flask_redirect(path) else: return render_json(data)
def groups_mine(): """ Redirect for compatibility. """ return flask_redirect(absolute_url('/groups/', q='member.user_name:%s' % identity.current.user.user_name))
def redirect(url): if request.is_xhr: return jsonify(redirect=url) return flask_redirect(url)
def d1(*args, **kwargs): if session.get(logged_in_key) is None: return flask_redirect(url_for(redirect_endpoint, **redirect_kwargs)) return fn(*args, **kwargs)
def redirect(target, code=302, **kw): return patch_response(flask_redirect(target, code=code), **kw)
def old_get_group(): if 'id' in request.args: user = User.by_id(request.args['id']) if user is not None: return flask_redirect(absolute_url(user.href)) raise NotFound404()
def redirect_back(default='home.home', **values): return flask_redirect(get_safe_redirect_url(default, **values))
def redirect(error: RedirectToClient) -> Response: """ For Redirect exceptions, performs a redirection to the client. """ return flask_redirect(app.config['CLIENT'] + request.full_path)
def login(): if g.user is not None: return flask_redirect(url_for("bookmarks")) return render_template("login-page.html", hide_header_login=True)
def index(): if g.user is None: return flask_redirect(url_for("recent")) return flask_redirect(url_for("bookmarks"))
def decorated_function(*args, **kwargs): try: log.trace("Api Call to %s <%s>" % (path.split(RELATIVE_PATH, 1)[-1], func_name)) if auth != 'Anonymous' and not ( current_user.is_authenticated and current_user.is_auth_level(auth)): return "Insufficent Authority", 401, { 'Content-Type': 'application/json' } response_code = 200 # OK kwargs = get_request_kwargs(func_args, arg_types, args, kwargs) next_url = kwargs.pop( 'next_url', redirect_url) # this is for custom redirect if FILE_HANDLER: record_api_call(FILE_HANDLER, kwargs) try: validate_arguments(func_args, arg_types, args_required, validator, kwargs) except BadRequestException as e: log.error("Api Call bad_arguments %s" % e.kwargs) return e.message, BadRequestException.status_code, { 'Content-Type': 'application/json' } if 'bypass_cache' in kwargs: pass if cache is not None: html_format = 'text/html' in request.accept_mimetypes and not request.accept_mimetypes.accept_json cache_key, ret = MEMCACHE.get(cache, kwargs, html_format) if ret is not None: return ret if cache_clear is not None: MEMCACHE.delete(cache_clear, kwargs) log.trace("Api Call kwargs: %s" % str(kwargs)) try: try: ret = func(**kwargs) except Exception as ex: raise if ret is None: raise NotFoundException() if add: assert isinstance(ret, ApiModel) or (isinstance(ret, list) and isinstance(ret[0], ApiModel)), \ '%s did not return an ApiModel to commit' % func.__name__ if isinstance(ret, (list, tuple)): db.session.add_all(ret) else: db.session.add(ret) if delete: assert isinstance(ret, ApiModel) or (isinstance(ret, list) and ( not ret or isinstance(ret[0], ApiModel))), \ '%s did not return an ApiModel to commit' % func.__name__ if isinstance(ret, (list, tuple)): for i, r in enumerate(ret): ret[i] = r.serialize() db.session.delete(r) else: serialized_ret = ret.serialize() db.session.delete(ret) ret = serialized_ret if commit: db.session.commit() except Exception as e: db.session.rollback() # db.session.close() log.critical("Api Call Exception <%s> \n%s\n\n%s" % (e.__class__, e.args, traceback.format_exc())) if isinstance(e, RestException): return e.message, e.status_code, { 'Content-Type': 'application/json' } else: raise if isinstance(ret, tuple) and len(ret) == 2 and isinstance( ret[1], int): # error raise DeprecationWarning # these should have been raised as Rest Exceptions if isinstance(ret, (ApiModel, LocalProxy)): ret = ret.serialize() if isinstance(ret, list) and ret and isinstance( ret[0], (ApiModel, LocalProxy)): ret = [row.serialize() or row for row in ret] if 'text/html' in request.accept_mimetypes and not request.accept_mimetypes.accept_json: if response_code != GOOD_REQUEST and html: return render_template(html, data=kwargs, errors=ret), response_code elif next_url: return flask_redirect(next_url) elif html: ret = render_template(html, data=kwargs, errors=ret) if cache is not None: MEMCACHE.set(cache_key, ret, cache_hours) return ret ret = json.dumps(ret) if cache is not None: MEMCACHE.set(cache_key, ret, cache_hours) return ret, response_code, {'Content-Type': 'application/json'} except Exception as e: log.critical("Api Call Exception %s" % traceback.format_exc()) raise
def redirect(*args, **kwargs): if request.values.get('api') == '1': return jsonify(success=False) return flask_redirect(*args, **kwargs)
def redirect(): user_context = getattr(g, 'user_context', None) if user_context is None or not user_context.is_authenticated: return flask_redirect(url_for('auth.login_page')) return flask_redirect(url_for('spending.index'))
def redirect(self, url, **kwargs): """Check vaid url and redirect to it, if valid.""" url = str(url) check_redirect_url(url) return flask_redirect(url, **kwargs)
def pageorbookmarks(): if g.user is None: return flask_redirect(url_for("recent")) elif g.user.passhash is None: return flask_redirect(url_for("bookmarks")) return flask_redirect(url_for("page", title=g.user.email))
def redirect(data, path): if should_render_as_html(): return flask_redirect(path) return render_json(data)