Python flask.request.path() Examples
The following are 30
code examples of flask.request.path().
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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: password-pwncheck.py From password_pwncheck with MIT License | 7 votes |
def StaticRequests(): reqfile = request.path[1:] sp = os.path.join(app.root_path,cfg.staticdir) mimetype=None if reqfile == 'image.svg': mimetype = 'image/svg+xml' return send_from_directory(sp,reqfile,mimetype=mimetype)
Example #2
Source File: views.py From FXTest with MIT License | 6 votes |
def get(self): wrok = Work.query.all() projects = Project.query.filter_by(status=False).all() if current_user.is_sper == True: pagination = (User.query.order_by('-id').all()) else: pagination = [] id = [] for projec in current_user.quanxians: if (projec.user.all() in id) is False: pagination.append(projec.user.all()) id.append(projec.user.all()) pagination = (hebinglist(pagination)) pager_obj = Pagination(request.args.get("page", 1), len(pagination), request.path, request.args, per_page_count=PageShow) index_list = pagination[pager_obj.start:pager_obj.end] html = pager_obj.page_html() return render_template('home/useradmin.html', users=index_list, html=html, wroks=wrok, projects=projects)
Example #3
Source File: autoapp.py From osm-wikidata with GNU General Public License v3.0 | 6 votes |
def log_request(code='-'): proto = request.environ.get('SERVER_PROTOCOL') msg = request.method + ' ' + request.path + ' ' + proto code = str(code) if code[0] == '1': # 1xx - Informational msg = color(msg, attrs=['bold']) if code[0] == '2': # 2xx - Success msg = color(msg, color='white') elif code == '304': # 304 - Resource Not Modified msg = color(msg, color='cyan') elif code[0] == '3': # 3xx - Redirection msg = color(msg, color='green') elif code == '404': # 404 - Resource Not Found msg = color(msg, color='yellow') elif code[0] == '4': # 4xx - Client Error msg = color(msg, color='red', attrs=['bold']) else: # 5xx, or any other response msg = color(msg, color='magenta', attrs=['bold']) logger.info('%s - - [%s] "%s" %s', request.remote_addr, log_date_time_string(), msg, code)
Example #4
Source File: __init__.py From osm-wikidata with GNU General Public License v3.0 | 6 votes |
def log_exception(self, exc_info): self.logger.error(""" Path: %s HTTP Method: %s Client IP Address: %s User Agent: %s User Platform: %s User Browser: %s User Browser Version: %s GET args: %s view args: %s URL: %s """ % ( request.path, request.method, request.remote_addr, request.user_agent.string, request.user_agent.platform, request.user_agent.browser, request.user_agent.version, dict(request.args), request.view_args, request.url ), exc_info=exc_info)
Example #5
Source File: app.py From discreETLy with MIT License | 6 votes |
def setup_authentication(app): oauth = OAuth(app) def handle_redirects(remote, token, user_info): if 'hd' in user_info: if user_info['hd'] == app.config['OAUTH_DOMAIN'] \ or (isinstance(app.config['OAUTH_DOMAIN'], List) and user_info['hd'] in app.config['OAUTH_DOMAIN']): session['user'] = user_info return redirect(session.get('next', '/')) return redirect(url_for('page.login')) def ensure_user_is_authorized(app): if 'user' not in session and request.path not in ['/oauth/login', '/oauth/auth', '/login', '/healthcheck'] and not request.path.startswith('/static/'): session['next'] = request.url return redirect(url_for('page.login')) app.register_blueprint( create_flask_blueprint(Google, oauth, handle_redirects), url_prefix='/oauth') app.before_request(lambda: ensure_user_is_authorized(app))
Example #6
Source File: honeyku.py From honeyku with GNU General Public License v3.0 | 6 votes |
def generate_http_response(req, conf): """ Generate HTTP response """ args = ["{}={}".format(key, value) for key, value in request.args.items()] path = req.path con_type = None body_path = None if path in conf['traps']: # Check if the token is defined and has a custom http response for token in args: if (token in conf['traps'][path]) and ("token-response" in conf['traps'][path][token]): con_type = conf['traps'][path][token]['token-response']['content-type'] body_path = conf['traps'][path][token]['token-response']['body'] # if the 'body_path' is still empty, use the trap/uri response (if there's any) if ("trap-response" in conf['traps'][path]) and body_path is None: con_type = conf['traps'][path]['trap-response']['content-type'] body_path = conf['traps'][path]['trap-response']['body'] # Load the default HTTP response if the 'body_path' is None if body_path is None: con_type = conf['default-http-response']['content-type'] body_path = conf['default-http-response']['body'] return con_type, body_path
Example #7
Source File: security.py From white with GNU General Public License v2.0 | 6 votes |
def security(role=None): def decorator(f): @wraps(f) def _decorator(*args, **kw): me = g.user if me.is_guest() and request.path != 'admin/login': return redirect(url_for('admin.login')) access = False if me.is_root(): access = True elif me.inactive(): access = False elif me.role == role: access = True elif me.is_admin and role in (User.EDITOR, None): access = True if access: return f(*args, **kw) else: return render_template('admin/403.html') return _decorator return decorator
Example #8
Source File: decorators.py From flask-security with MIT License | 6 votes |
def default_unauthz_handler(func, params): unauthz_message, unauthz_message_type = get_message("UNAUTHORIZED") if _security._want_json(request): payload = json_error_response(errors=unauthz_message) return _security._render_json(payload, 403, None, None) view = config_value("UNAUTHORIZED_VIEW") if view: if callable(view): view = view() else: try: view = get_url(view) except BuildError: view = None do_flash(unauthz_message, unauthz_message_type) redirect_to = "/" if request.referrer and not request.referrer.split("?")[0].endswith( request.path ): redirect_to = request.referrer return redirect(view or redirect_to) abort(403)
Example #9
Source File: webserver.py From fame with GNU General Public License v3.0 | 5 votes |
def delete_query(*new_values): args = request.args.copy() for key in new_values: del args[key] return '{}?{}'.format(request.path, url_encode(args))
Example #10
Source File: views.py From fame with GNU General Public License v3.0 | 5 votes |
def init_saml_auth(req): saml_auth = OneLogin_Saml2_Auth(req, custom_base_path=os.path.join(os.path.dirname(os.path.dirname(__file__)), 'saml/config')) return saml_auth
Example #11
Source File: utils.py From ansible-runner-service with Apache License 2.0 | 5 votes |
def log_request(logger): ''' wrapper function for HTTP request logging ''' def real_decorator(f): @wraps(f) def wrapper(*args, **kwargs): """ Look at the request, and log the details """ # logger.info("{}".format(request.url)) logger.debug("Request received, content-type :" "{}".format(request.content_type)) if request.content_type == 'application/json': sfx = ", parms={}".format(request.get_json()) else: sfx = '' logger.info("{} - {} {}{}".format(request.remote_addr, request.method, request.path, sfx)) return f(*args, **kwargs) return wrapper return real_decorator
Example #12
Source File: utils.py From airflow with Apache License 2.0 | 5 votes |
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')
Example #13
Source File: views.py From fame with GNU General Public License v3.0 | 5 votes |
def prepare_auth_request(request): url_data = urlparse(request.url) return { "https": 'on', 'http_host': request.host, 'server_port': url_data.port, 'script_name': request.path, 'get_data': request.args.copy(), 'post_data': request.form.copy(), # Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144 # 'lowercase_urlencoding': True, 'query_string': request.query_string }
Example #14
Source File: server.py From MoePhoto with Apache License 2.0 | 5 votes |
def videoEnhancePrep(req): if not os.path.exists(uploadDir): os.mkdir(uploadDir) for k in ('url', 'cmd'): v = req.values.get(k, None) if v: return (v, k, *readOpt(req)) vidfile = req.files['file'] path ='{}/{}'.format(uploadDir, vidfile.filename) vidfile.save(path) return (path, False, *setOutputName(readOpt(req), vidfile))
Example #15
Source File: server.py From MoePhoto with Apache License 2.0 | 5 votes |
def setOutputName(args, fp): if not len(args): args = ({'op': 'output'},) if 'file' in args[-1]: return args base, ext = os.path.splitext(fp.filename) path = '{}/{}{}'.format(outDir, base, ext) i = 0 while os.path.exists(path): i += 1 path = '{}/{}_{}{}'.format(outDir, base, i, ext) args[-1]['file'] = path return args
Example #16
Source File: server.py From MoePhoto with Apache License 2.0 | 5 votes |
def checkMsgMatch(request): if not 'path' in request.values: return True path = request.values['path'] return path == current.path
Example #17
Source File: server.py From MoePhoto with Apache License 2.0 | 5 votes |
def controlPoint(path, fMatch, fUnmatch, fNoCurrent, check=lambda *_: True): def f(): if not 'session' in request.values: return E403 session = request.values['session'] if not session: return E403 if current.session: return spawn(fMatch, getKey(session, request)).get() if current.session == session and check(request) else fUnmatch() else: return fNoCurrent(session, request) app.route(path, methods=['GET', 'POST'], endpoint=path)(f)
Example #18
Source File: webserver.py From fame with GNU General Public License v3.0 | 5 votes |
def modify_query(key, value): args = request.args.copy() args[key] = value return '{}?{}'.format(request.path, url_encode(args))
Example #19
Source File: server.py From MoePhoto with Apache License 2.0 | 5 votes |
def acquireSession(request): if current.session: return busy() while noter.poll(): noter.recv() current.session = request.values['session'] current.path = request.values['path'] if 'path' in request.values else request.path current.key = current.path + str(current.session) spawn(pollNote) current.eta = 1 updateETA(request.values) return False if current.session else E403
Example #20
Source File: aaa.py From minemeld-core with Apache License 2.0 | 5 votes |
def _audit(self, f, audit_required): if not audit_required: return f @wraps(f) def audited_view(*args, **kwargs): if request and flask.ext.login.current_user: params = [] for key, values in request.values.iterlists(): if key == '_': continue params.append(('value:{}'.format(key), values)) for filename, files in request.files.iterlists(): params.append(('file:{}'.format(filename), [file.filename for file in files])) body = request.get_json(silent=True) if body is not None: params.append(['jsonbody', json.dumps(body)[:1024]]) LOG.audit( user_id=flask.ext.login.current_user.get_id(), action_name='{} {}'.format(request.method, request.path), params=params ) else: LOG.critical('no request or current_user in audited_view') return f(*args, **kwargs) return audited_view
Example #21
Source File: registry.py From appr with Apache License 2.0 | 5 votes |
def test_error(): raise InvalidUsage("error message", {"path": request.path})
Example #22
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 #23
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 #24
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 #25
Source File: wrappers.py From cloud-inquisitor with Apache License 2.0 | 5 votes |
def __check_auth(self, view): headers = {x[0]: x[1] for x in request.headers} if 'Authorization' in headers: try: token = jwt.decode( headers['Authorization'], get_jwt_key_data() ) if token['auth_system'] != current_app.active_auth_system.name: self.log.error('Token is from another auth_system ({}) than the current one ({})'.format( token['auth_system'], current_app.active_auth_system.name )) return view.make_unauth_response() if has_access(session['user'], self.role): return self.log.error('User {} attempted to access page {} without permissions'.format( session['user'].username, request.path )) return view.make_unauth_response() except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex: session.clear() view.log.info('Failed to decode signature or it had expired: {0}'.format(ex)) return view.make_unauth_response() session.clear() view.log.info('Failed to detect Authorization header') return view.make_unauth_response()
Example #26
Source File: views.py From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def index(): interesting = "" if os.path.exists("reading_list.txt"): with open("reading_list.txt", "r") as fp: raw_text = fp.read() interesting = markdown.markdown(raw_text, extensions=["mdx_linkify"]) interesting = WebMirror.API.processRaw(interesting) return render_template('index.html', title = 'Home', interesting_links = interesting, )
Example #27
Source File: views.py From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def not_found_error(dummy_error): print("404 for '{}'. Wat?".format(request.path)) return render_template('404.html'), 404
Example #28
Source File: views.py From FXTest with MIT License | 5 votes |
def post(self): data_post = request.get_json() name_is = Mockserver.query.filter_by(name=data_post['name']).first() if name_is: return jsonify({"code": 28, 'data': 'mockserver的名称不能重复'}) if data_post['checkout'] == u'是': is_check = True else: is_check = False if data_post['checkouheaders'] == u'是': is_headers = True else: is_headers = False if data_post['kaiqi'] == u'是': is_kaiqi = True else: is_kaiqi = False new_mock = Mockserver(name=data_post['name']) new_mock.make_uers = current_user.id new_mock.path = data_post['path'] new_mock.methods = data_post['meth'] new_mock.headers = data_post['headers'] new_mock.description = data_post['desc'] new_mock.fanhui = data_post['back'] new_mock.params = data_post['parm'] new_mock.rebacktype = data_post['type'] new_mock.status = is_kaiqi new_mock.ischeck = is_check new_mock.is_headers = is_headers new_mock.update_time = datetime.datetime.now() db.session.add(new_mock) try: db.session.commit() return jsonify({"code": 2, 'data': '添加mock成功'}) except: db.session.rollback() return jsonify({"code": 29, 'data': '创建新的mock接口出错,原因:%s' % Exception})
Example #29
Source File: test_terraformize_endpoint.py From terraformize with GNU Lesser General Public License v3.0 | 5 votes |
def test_terraformize_endpoint_apply_missing_module(self): configuration["terraform_modules_path"] = test_files_location configuration["terraform_binary_path"] = test_bin_location expected_body = { 'error': "[Errno 2] No such file or directory: '" + test_files_location + "/fake_test_module'" } with app.test_request_context('/v1/fake_test_module/test_workspace', method='POST'): self.assertEqual(request.path, '/v1/fake_test_module/test_workspace') return_body, terraform_return_code = apply_terraform("fake_test_module", "test_workspace") self.assertEqual(terraform_return_code, 404) self.assertEqual(return_body.json, expected_body)
Example #30
Source File: resources.py From zou with GNU Affero General Public License v3.0 | 5 votes |
def wrong_auth_handler(identity_user=None): if request.path not in ["/auth/login", "/auth/logout"]: abort(401) else: return identity_user