Here are the examples of the python api flask.request.path taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
121 Examples
3
Example 1
def require_auth(fn):
@functools.wraps(fn)
def decorated(*args, **kwargs):
if current_app.config['ENABLE_GOOGLE_AUTH'] and not 'user' in session:
params = dict(response_type='code',
scope=' '.join(scope),
client_id=current_app.config['GOOGLE_CLIENT_ID'],
approval_prompt='auto',
redirect_uri=url_for('auth.google_callback',
_external=True,
_scheme=http_scheme()))
url = auth_uri + '?' + urllib.urlencode(params)
session['next'] = request.path
return redirect(url)
return fn(*args, **kwargs)
return decorated
3
Example 2
Project: bombolone Source File: app.py
@app.errorhandler(408)
def request_timeout(error):
"""Raise to signalize a timeout."""
message = '408 - Error caught in {1} : {0}'.format(error, request.path)
app.logger.critical(message)
return errorhandler(408, message)
3
Example 3
Project: osf.io Source File: node.py
@must_be_valid_project(retractions_valid=True)
@must_be_contributor_or_public
@process_token_or_pass
def view_project(auth, node, **kwargs):
primary = '/api/v1' not in request.path
ret = _view_project(node, auth, primary=primary)
ret['addon_capabilities'] = settings.ADDON_CAPABILITIES
# Collect the URIs to the static assets for addons that have widgets
ret['addon_widget_js'] = list(collect_addon_js(
node,
filename='widget-cfg.js',
config_entry='widget'
))
ret.update(rubeus.collect_addon_assets(node))
return ret
3
Example 4
@app.route('/mapreduce', methods=['GET', 'POST'])
def MapReduce():
"""Handler of MapReduce request."""
app.logger.info('ACCESS URL: %s', flask.request.path)
return flask.Response(
PerformMapReduce(
flask.request.values.get('input', ''),
flask.request.values.get('output', ''),
flask.request.values.get('mapper_type', 'identity'),
flask.request.values.get('mapper_url', ''),
flask.request.files.get('mapper_file', None),
int(flask.request.values.get('mapper_count', 5)),
flask.request.values.get('reducer_type', 'identity'),
flask.request.values.get('reducer_url', ''),
flask.request.files.get('reducer_file', None),
int(flask.request.values.get('reducer_count', 1))),
direct_passthrough=False, mimetype='text/plain')
3
Example 5
def requires_login(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
flash(u'You need to be signed in for this page.')
return redirect(url_for('frontends.login', next=request.path))
return f(*args, **kwargs)
return decorated_function
3
Example 6
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.project is None:
if g.admin is None:
flash(u'You need to login to view this page!')
return redirect(url_for('index', next=request.path))
return f(*args, **kwargs)
return decorated_function
3
Example 7
@app.errorhandler(404)
def page_not_found(e):
"""
404 error page.
"""
add_request(REQUEST_OTHER, request.path)
global error404_count
if request.path != '/favicon.ico':
error404_count += 1
if error404_count == 20:
add_request(REQUEST_RATE_LIMIT, request.path)
force_shutdown()
print(strings._('error_rate_limit'))
return render_template_string(open(helpers.get_resource_path('html/404.html')).read())
3
Example 8
Project: viaduct Source File: navigation.py
@staticmethod
def current_entry():
my_path = request.path
temp_strip = my_path.rstrip('0123456789')
if temp_strip.endswith('/'):
my_path = temp_strip
my_path = my_path.rstrip('/')
return db.session.query(NavigationEntry).filter_by(url=my_path)\
.first()
3
Example 9
Project: flask-website Source File: utils.py
def requires_login(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
flash(u'You need to be signed in for this page.')
return redirect(url_for('general.login', next=request.path))
return f(*args, **kwargs)
return decorated_function
3
Example 10
@login_manager.unauthorized_handler
def unauthorized():
# Save the path the user was rejected from.
session['denied_from'] = request.path
flash(_('You must be logged in to view this page.'), 'danger')
return redirect(url_for('user.sign_in'))
3
Example 11
Project: gae-init-upload Source File: resource.py
@auth.login_required
def get(self):
count = util.param('count', int) or 1
urls = []
for i in range(count):
urls.append({'upload_url': blobstore.create_upload_url(
flask.request.path,
gs_bucket_name=config.CONFIG_DB.bucket_name or None,
)})
return flask.jsonify({
'status': 'success',
'count': count,
'result': urls,
})
3
Example 12
Project: flask-cors Source File: extension.py
def make_after_request_function(resources):
def cors_after_request(resp):
# If CORS headers are set in a view decorator, pass
if resp.headers.get(ACL_ORIGIN):
LOG.debug('CORS have been already evaluated, skipping')
return resp
for res_regex, res_options in resources:
if try_match(request.path, res_regex):
LOG.debug("Request to '%s' matches CORS resource '%s'. Using options: %s",
request.path, get_regexp_pattern(res_regex), res_options)
set_cors_headers(resp, res_options)
break
else:
LOG.debug('No CORS rule matches')
return resp
return cors_after_request
3
Example 13
Project: flask-bluebone Source File: app.py
def configure_app_handlers(app):
@app.route('/')
def get():
abort(404)
@app.route('/i-used-to-be-here/')
def iusedtobehere():
abort(410)
@app.route('/robots.txt')
def static_from_root():
return send_from_directory(app.static_folder, request.path[1:])
@app.route('/sitemap.xml')
def sitemap():
url_root = request.url_root[:-1]
rules = app.url_map.iter_rules()
return render_template('sitemap.xml', url_root=url_root, rules=rules)
3
Example 14
Project: indico Source File: app.py
def handle_404(exception):
try:
if re.search(r'\.py(?:/\S+)?$', request.path):
# While not dangerous per se, we never serve *.py files as static
raise NotFound
try:
return send_from_directory(current_app.config['INDICO_HTDOCS'], request.path[1:], conditional=True)
except (UnicodeEncodeError, BadRequest):
raise NotFound
except NotFound:
if exception.description == NotFound.description:
# The default reason is too long and not localized
description = _("The page you are looking for doesn't exist.")
else:
description = exception.description
return render_error(_("Page not found"), description), 404
3
Example 15
Project: shiva-server Source File: resource.py
def verify_credentials(app):
g.user = None
if request.path == '/users/login/':
return None
if app.config.get('ALLOW_ANONYMOUS_ACCESS', False):
return None
token = request.args.get('token', '')
user = User.verify_auth_token(token)
if not user:
abort(HTTP.UNAUTHORIZED)
g.user = user
3
Example 16
Project: gae-angular-material-starter Source File: user.py
@app.route('/user/verify/<token>/', methods=['GET']) # pylint: disable=missing-docstring
def user_verify(token):
"""Verifies user's email by token provided in url"""
if auth.is_logged_in():
login.logout_user()
return flask.redirect(flask.request.path)
user_db = model.User.get_by('token', token)
if user_db and not user_db.verified:
# setting new token is necessary, so this one can't be reused
user_db.token = util.uuid()
user_db.verified = True
user_db.put()
auth.signin_user_db(user_db)
flask.flash('Welcome on board %s!' % user_db.username)
else:
flask.flash('Sorry, activation link is either invalid or expired.')
return flask.redirect(flask.url_for('index'))
3
Example 17
Project: blockstack-core Source File: errors.py
@app.errorhandler(404)
def resource_not_found(e):
if len(request.path) > 1 and request.path[1] == 'v':
error = PageNotFoundError()
response = jsonify({'error': error.to_dict()})
response.status_code = 400
return response
else:
return render_template('error.html', status_code=404,
error_message="Resource not found"), 404
3
Example 18
def context(self):
"""Convert input to Context
By default, convert json body to Convext for put/post request, convert args for get/delete request
:rtype: Context
:return Context object from request body or query
"""
caller = sys._getframe().f_back.f_code.co_name.lower()
if caller in ["post", "put"] and not request.path == "/api/user/file":
return Context.from_object(request.get_json(force=True))
else:
return Context.from_object(request.args)
3
Example 19
@app.route('/api/<codename>/<component>/<architecture>/<package>/')
def get_package_versions(codename, component, architecture, package):
g.breadcrumb = [{'name': 'browse', 'url': url_for('get_repository_detail')},
{'name': codename, 'url': url_for('get_codename_detail', codename=codename)},
{'name': component, 'url': url_for('get_component_detail', codename=codename, component=component)},
{'name': architecture, 'url': url_for('get_architecture_detail', codename=codename, component=component, architecture=architecture)},
{'name': package, 'url': request.path},]
# get any un-referenced versions of our package name
repository = Repository(settings.basedir)
all_versions = repository.list(codename, package)
print all_versions
return render_template('api/detail/package.html', package=package, versions=all_versions)
3
Example 20
@app.errorhandler(500)
def bad_request(error):
"""Raise if the browser sends something to the application the
application or server cannot handle."""
app.logger.critical("Path: {}".format(request.path))
app.logger.critical(logging.exception("Exception"))
message = "Something went wrong!"
return errorhandler(500, message)
3
Example 21
Project: pittsburgh-purchasing-suite Source File: decorators.py
def logview(f):
@wraps(f)
def decorated_function(*args, **kwargs):
current_app.logger.info('SHERPAVIEW - Viewing page at {}'.format(
request.path
))
return f(*args, **kwargs)
return decorated_function
3
Example 22
Project: pittsburgh-purchasing-suite Source File: views.py
@blueprint.route('/filter', methods=['GET'])
def filter_no_department():
'''The landing page for filtering by departments
:status 200: Renders the appropriate landing page.
'''
return render_template(
'scout/filter.html',
search_form=SearchForm(),
results=[],
choices=Department.choices(),
path='{path}?{query}'.format(
path=request.path, query=request.query_string
)
)
3
Example 23
Project: sopython-site Source File: login.py
@bp.app_errorhandler(LoginError)
def handle_login_error(e):
"""Redirect to the login page when LoginError is raised.
If the user is logged in but doesn't have permission, don't try to log in, it will result in an infinite loop.
Raise 403 Forbidden instead.
"""
if not current_user.authenticated:
return redirect_for('auth.login', next=request.path)
# abort(403)
# can't raise other handled exception from error handler, results in 500
# so simulate what flask would do
try:
abort(403)
except Exception as e:
return current_app.handle_user_exception(e)
3
Example 24
Project: peewee Source File: app.py
def login_required(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
if session.get('logged_in'):
return fn(*args, **kwargs)
return redirect(url_for('login', next=request.path))
return inner
3
Example 25
Project: viaduct Source File: errors.py
@app.errorhandler(403)
def permission_denied(e):
"""When permission denied and not logged in you will be redirected."""
content = "403, The police has been notified!"
image = '/static/img/403.jpg'
# Save the path you were rejected from.
session['denied_from'] = request.path
if current_user.is_authenticated:
flash(_('You do not have the rights to view this page.'), 'danger')
return redirect(url_for('user.sign_in'))
return render_template('page/403.htm', content=content, image=image), 403
3
Example 26
Project: dropboxwindow Source File: main.py
@window.route('/robots.txt')
@window.route('/humans.txt')
@window.route('/qrcode.ttf')
@window.route('/manifest.webapp')
def serve_static_content():
return send_from_directory(window.static_folder, request.path[1:])
3
Example 27
Project: Flexget Source File: authentication.py
@api_app.before_request
def check_valid_login():
# Allow access to root, login and swagger docuementation without authentication
if request.path == '/' or request.path.startswith('/auth/login') or \
request.path.startswith('/auth/logout') or request.path.startswith('/swagger'):
return
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
3
Example 28
Project: viaduct Source File: __init__.py
@app.context_processor
def inject_urls():
return dict(
request_path=request.path,
request_base_url=request.base_url,
request_url=request.url,
request_url_root=request.url_root)
3
Example 29
@app.errorhandler(404)
def handle_404(ex):
"""Handle 404s, sending index.html for unhandled paths."""
path = flask.request.path[1:]
try:
return app.send_static_file(path)
except (exceptions.NotFound, UnicodeEncodeError):
if '.' not in path and not path.startswith('api/'):
app.logger.info('%s -> index.html', path)
return render_index()
return '404 Not Found', 404
3
Example 30
@app.before_request
def log_entry():
context = {
'url': request.path,
'method': request.method,
'ip': request.environ.get('REMOTE_ADDR')
}
app.logger.debug(
'Handling %(method)s request from %(ip)s for %(url)s', context)
3
Example 31
Project: backdrop Source File: api.py
def _record_write_error(e):
app.logger.exception(e)
name_or_path = getattr(g, 'data_set_name', request.path)
statsd.incr("write.error", data_set=name_or_path)
if getattr(e, 'code', None) == 401:
statsd.incr("write_api.bad_token", data_set=name_or_path)
3
Example 32
Project: white Source File: front.py
def page_redirect():
path = request.path
page = page_service.get_by_redirect(path)
if not page:
return theme_render('404.html', page_title='Not Found'), 404
return theme_render('page.html',
page_content=page.content,
page_title=page.title,
page=page)
3
Example 33
@app.before_request
def before_request():
context = {
'url': request.path,
'method': request.method,
'ip': request.environ.get("REMOTE_ADDR")
}
logging.debug("%(method)s from %(ip)s for %(url)s", context)
3
Example 34
Project: ReproWeb Source File: views.py
@app.route('/api/<codename>/<component>/')
def get_component_detail(codename, component):
"""Render a view listing all of the architectures of the selected component"""
g.breadcrumb = [{'name': 'browse', 'url': url_for('get_repository_detail')},
{'name': codename, 'url': url_for('get_codename_detail', codename=codename)},
{'name': component, 'url': request.path},]
repository = Repository(settings.basedir)
archs = repository.list_architectures(codename)
packages = repository.list(codename)
if archs:
for a in archs:
a['url'] = url_for('get_architecture_detail', codename=codename, component=component, architecture=a['architecture'])
a['count'] = len( [x for x in packages if x['component'] == component and x['architecture'] == a['architecture'] ] )
return render_template('api/detail/component.html', codename=codename, component=component, archs=archs)
return render_template('api/detail/component.html', codename=codename, component=component)
3
Example 35
def active(*url_patterns, **kwargs):
partial = kwargs.get('partial')
path = norm_url(request.path)
# Accept single patterns also
if len(url_patterns) == 1 and isinstance(url_patterns[0], (list, tuple)):
url_patterns = url_patterns[0]
for urlp in url_patterns:
urlp = norm_url(urlp)
if fnmatch(path, urlp) or (partial and path.startswith(urlp)):
return 'active'
return u''
3
Example 36
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.admin is None:
flash(u'You need to be an admin to view this page!')
return redirect(url_for('index', next=request.path))
return f(*args, **kwargs)
return decorated_function
3
Example 37
def make_cache_key(*args, **kwargs):
'''
Used by cache to get a unique key per URL
'''
path = request.path
args = str(hash(frozenset(request.args.items())))
return (path + args).encode('ascii', 'ignore')
3
Example 38
Project: docklet Source File: web.py
@app.route("/monitor/hosts/<comid>/<infotype>/", methods=['POST'])
@app.route("/monitor/vnodes/<comid>/<infotype>/", methods=['POST'])
@login_required
def monitor_request(comid,infotype):
data = {
"user": session['username']
}
result = dockletRequest.post(request.path, data)
return json.dumps(result)
3
Example 39
Project: balrog Source File: base.py
@app.errorhandler(500)
def ise(error):
log.error("Caught ISE 500 error.")
log.debug("Request path is: %s", request.path)
log.debug("Request environment is: %s", request.environ)
log.debug("Request headers are: %s", request.headers)
return error
3
Example 40
@mod.route('/')
def index():
url_prefix = request.path
url_prefix = url_prefix if not url_prefix.endswith('/') else url_prefix[:-1]
service_url = url_prefix.replace('/browse', '')
return render_template('browse/index.html', service_url=service_url, url_prefix=url_prefix)
3
Example 41
Project: flask-restplus Source File: api.py
def _help_on_404(self, message=None):
rules = dict([(RE_RULES.sub('', rule.rule), rule.rule)
for rule in current_app.url_map.iter_rules()])
close_matches = difflib.get_close_matches(request.path, rules.keys())
if close_matches:
# If we already have a message, add punctuation and continue it.
message = ''.join((
(message.rstrip('.') + '. ') if message else '',
'You have requested this URI [',
request.path,
'] but did you mean ',
' or '.join((rules[match] for match in close_matches)),
' ?',
))
return message
3
Example 42
@app.route('/api/packages/')
def get_packages():
"""Render a view listing _all_ of the packages within the repository."""
g.breadcrumb = [ {'name': 'search', 'url': request.path}, ]
repository = Repository(settings.basedir)
package_list = []
for dist in repository.list_dists():
package_list.extend(repository.list(dist['Codename']))
for package in package_list:
package['url'] = url_for('get_package_detail', codename = package.get('codename'),
component = package.get('component'),
architecture = package.get('architecture'),
package = package.get('package'),
version = package.get('version') )
return render_template('api/packages.html', packages=sorted(package_list))
3
Example 43
Project: bombolone Source File: app.py
@app.errorhandler(413)
def request_too_large(error):
"""Like 413 but for too long URLs."""
message = '413 - Error caught in {1} : {0}'.format(error, request.path)
app.logger.critical(message)
return errorhandler(408, message)
3
Example 44
Project: sheer Source File: views.py
def serve_error_page(error_code):
request = flask.request
# TODO: this seems silly
# We shouldn't even need to send the request object,
# and the second argument should usually be request.path anyways
search_path = build_search_path_for_request(
request, request.path, append=['_layouts', '_includes'], include_start_directory=True)
template_path = find_in_search_path('%s.html' % error_code, search_path)
if template_path:
with codecs.open(template_path, encoding="utf-8") as template_source:
return flask.render_template_string(template_source.read()), error_code
else:
return "Please provide a %s.html!" % error_code, error_code
3
Example 45
Project: viaduct Source File: navigation.py
@staticmethod
def parent_entry():
my_path = request.path
temp_strip = my_path.rstrip('0123456789')
if temp_strip.endswith('/'):
my_path = temp_strip
my_path = my_path.rstrip('/')
return db.session.query(NavigationEntry).filter_by(url=my_path)\
.first()
3
Example 46
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
response.headers.add('Access-Control-Allow-Credentials', 'true')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type, *')
response.headers.add('Cache-Control', 'no-cache')
response.headers.add('Cache-Control', 'no-store')
if api.auth.is_logged_in():
if 'token' in session:
response.set_cookie('token', session['token'])
else:
csrf_token = api.common.token()
session['token'] = csrf_token
response.set_cookie('token', csrf_token)
# JB: This is a hack. We need a better solution
if request.path[0:19] != "/api/autogen/serve/":
response.mimetype = 'appication/json'
return response
3
Example 47
Project: ReproWeb Source File: views.py
@app.route('/api/<codename>/')
def get_codename_detail(codename):
"""Render a view listing all of the components of the selected distribution"""
g.breadcrumb = [{'name': 'browse', 'url': url_for('get_repository_detail')},
{'name': codename, 'url': request.path},]
repository = Repository(settings.basedir)
components = repository.list_components(codename)
packages = repository.list(codename)
if components:
for c in components:
c['url'] = url_for('get_component_detail', codename=codename, component=c['component'])
c['count'] = len( [x for x in packages if x['component'] == c['component']] )
return render_template('api/detail/codename.html', codename=codename, components=components)
return render_template('api/detail/codename.html', codename=codename)
3
Example 48
Project: get5-web Source File: api.py
def rate_limit_key():
try:
match = _matchid_re.search(request.path)
matchid = int(match.group(1))
if matchid:
# If the key matches, rate limit by the api key
api_key = Match.query.get_or_404(matchid).api_key
if api_key == request.values.get('key'):
return api_key
except Exception:
pass
# Otherwise, rate limit by IP address
return flask_limiter.util.get_remote_address()
3
Example 49
Project: viaduct Source File: errors.py
@app.errorhandler(404)
def page_not_found(e):
# Search for file extension.
if re.match(r'(?:.*)\.[a-zA-Z]{3,}$', request.path):
return '', 404
page = Page(request.path.lstrip('/'))
return render_template('page/404.htm', page=page), 404
3
Example 50
Project: open-event-orga-server Source File: request_context_task.py
def _include_request_context(self, kwargs):
"""Includes all the information about current Flask request context
as an additional argument to the task.
"""
if not has_request_context():
return
# keys correspond to arguments of :meth:`Flask.test_request_context`
context = {
'path': request.path,
'base_url': request.url_root,
'method': request.method,
'headers': dict(request.headers),
}
if '?' in request.url:
context['query_string'] = request.url[(request.url.find('?') + 1):]
kwargs[self.CONTEXT_ARG_NAME] = context