Python flask.request.full_path() Examples

The following are 30 code examples of flask.request.full_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 .
Example #1
Source File: models.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def __call__(self, *args, **kwargs):
            if not current_app.config.get('INDEXING_ENABLED', True):
                return self._route(*args, **kwargs)

            log = PageView(
                page=request.full_path,
                endpoint=request.endpoint,
                user_id=current_user.id,
                ip_address=request.remote_addr,
                version=__version__
            )
            errorlog = None
            log.object_id, log.object_type, log.object_action, reextract_after_request = self.extract_objects(*args, **kwargs)
            db_session.add(log)  # Add log here to ensure pageviews are accurate

            try:
                return self._route(*args, **kwargs)
            except Exception as e:
                db_session.rollback()  # Ensure no lingering database changes remain after crashed route
                db_session.add(log)
                errorlog = ErrorLog.from_exception(e)
                db_session.add(errorlog)
                db_session.commit()
                raise_with_traceback(e)
            finally:
                # Extract object id and type after response generated (if requested) to ensure
                # most recent data is collected
                if reextract_after_request:
                    log.object_id, log.object_type, log.object_action, _ = self.extract_objects(*args, **kwargs)

                if errorlog is not None:
                    log.id_errorlog = errorlog.id
                db_session.add(log)
                db_session.commit() 
Example #2
Source File: views.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def process_year_facet(request, facets):
    url_path = modify_query('.search', **{'date': None})
    year_facet = get_session_item(url_path)
    if len(year_facet) == 0 or (request.full_path[:-1] == url_path or request.full_path == url_path):
        # we update the facet if there is no value stored in the session,
        # or if the base url is the same as the stripped url
        year_facet = get_facet(facets, 'Date')
        if year_facet:
            year_facet = {decode_string(json.dumps(year_facet))}
            set_session_item(url_path, year_facet)

    if year_facet and len(year_facet) > 0:
        year_facet = list(year_facet)[0]

    return year_facet 
Example #3
Source File: Dr0p1t_Server.py    From Dr0p1t-Framework with MIT License 5 votes vote down vote up
def exceptions(e):
    tb = traceback.format_exc()
    timestamp = strftime('[%Y-%b-%d %H:%M]')
    f = open("server.log","a").write( "\n"+"--"*10+"\n"+'%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s'%(timestamp, request.remote_addr, request.method, request.scheme, request.full_path, tb) )
    return abort(500) 
Example #4
Source File: Dr0p1t_Server.py    From Dr0p1t-Framework with MIT License 5 votes vote down vote up
def after_request(response):
    timestamp = strftime('[%Y-%b-%d %H:%M]')
    f = open("server.log","a").write( "\n"+"--"*10+"\n"+'%s %s %s %s %s %s'%(timestamp, request.remote_addr, request.method, request.scheme, request.full_path, response.status) )
    return response 
Example #5
Source File: tor_cache.py    From freshonions-torscraper with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, f):
    	@functools.wraps(f)
        def my_decorator(*args, **kwargs):
        	global _is_cached
        	_is_cached = True
        	if _cache is None:
        		return f(*args, **kwargs)
        	response = _cache.get(request.full_path)
        	if response is None:
        		response = f(*args, **kwargs)
        		_cache.set(request.path, response, self.timeout)
        	_is_cached = False
        	
        	if self.render_layout:
        		wrapped_response = make_response("%s%s%s" % (render_template("layout_header.html"), response, render_template("layout_footer.html")))
        		if is_response(response):
        			wrapped_response.status_code = response.status_code
        			wrapped_response.headers     = response.headers
        			wrapped_response.status      = response.status
        			wrapped_response.mimetype    = response.mimetype
        		return wrapped_response
        	else:
        		return response

        functools.update_wrapper(my_decorator, f)
        return my_decorator 
Example #6
Source File: app.py    From freshonions-torscraper with GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_session():

    session.permanent = True
    app.permanent_session_lifetime = timedelta(days=365*30)
    if not 'uuid' in session:
    	session['uuid'] = str(uuid.uuid4())
    	g.uuid_is_fresh = True
    else:
    	g.uuid_is_fresh = False
    now = datetime.now()
    
    referrer  = request.headers.get('Referer', '')
    path      = request.path
    full_path = request.full_path
    agent     = request.headers.get('User-Agent', '')

    if agent in BLACKLIST_AGENT or len(agent) < 15:
        g.request_log_id = 0
        return render_template('error.html',code=200,message="Layer 8 error. If you want my data, DON'T SCRAPE (too much cpu load), contact me and I will give it to you"), 200

    with db_session:
    	req_log   = RequestLog( uuid=session['uuid'], 
    							uuid_is_fresh=g.uuid_is_fresh, 
    							created_at=now, 
    							agent=agent,
    							referrer=referrer,
    							path=path,
    							full_path=full_path)
    	flush()
    	g.request_log_id = req_log.id 
Example #7
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def get_current_user():
    if authed():
        user = Users.query.filter_by(id=session["id"]).first()

        # Check if the session is still valid
        session_hash = session.get("hash")
        if session_hash:
            if session_hash != hmac(user.password):
                logout_user()
                if request.content_type == "application/json":
                    error = 401
                else:
                    error = redirect(url_for("auth.login", next=request.full_path))
                abort(error)

        return user
    else:
        return None 
Example #8
Source File: visibility.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def check_account_visibility(f):
    @functools.wraps(f)
    def _check_account_visibility(*args, **kwargs):
        v = get_config(ConfigTypes.ACCOUNT_VISIBILITY)
        if v == AccountVisibilityTypes.PUBLIC:
            return f(*args, **kwargs)

        elif v == AccountVisibilityTypes.PRIVATE:
            if authed():
                return f(*args, **kwargs)
            else:
                if request.content_type == "application/json":
                    abort(403)
                else:
                    return redirect(url_for("auth.login", next=request.full_path))

        elif v == AccountVisibilityTypes.ADMINS:
            if is_admin():
                return f(*args, **kwargs)
            else:
                abort(404)

    return _check_account_visibility 
Example #9
Source File: visibility.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def check_challenge_visibility(f):
    @functools.wraps(f)
    def _check_challenge_visibility(*args, **kwargs):
        v = get_config(ConfigTypes.CHALLENGE_VISIBILITY)
        if v == ChallengeVisibilityTypes.PUBLIC:
            return f(*args, **kwargs)

        elif v == ChallengeVisibilityTypes.PRIVATE:
            if authed():
                return f(*args, **kwargs)
            else:
                if request.content_type == "application/json":
                    abort(403)
                else:
                    return redirect(url_for("auth.login", next=request.full_path))

        elif v == ChallengeVisibilityTypes.ADMINS:
            if is_admin():
                return f(*args, **kwargs)
            else:
                if authed():
                    abort(403)
                else:
                    return redirect(url_for("auth.login", next=request.full_path))

    return _check_challenge_visibility 
Example #10
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def require_team(f):
    @functools.wraps(f)
    def require_team_wrapper(*args, **kwargs):
        if get_config("user_mode") == TEAMS_MODE:
            team = get_current_team()
            if team is None:
                if request.content_type == "application/json":
                    abort(403)
                else:
                    return redirect(url_for("teams.private", next=request.full_path))
        return f(*args, **kwargs)

    return require_team_wrapper 
Example #11
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def admins_only(f):
    """
    Decorator that requires the user to be authenticated and an admin
    :param f:
    :return:
    """

    @functools.wraps(f)
    def admins_only_wrapper(*args, **kwargs):
        if is_admin():
            return f(*args, **kwargs)
        else:
            if request.content_type == "application/json":
                abort(403)
            else:
                return redirect(url_for("auth.login", next=request.full_path))

    return admins_only_wrapper 
Example #12
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def authed_only(f):
    """
    Decorator that requires the user to be authenticated
    :param f:
    :return:
    """

    @functools.wraps(f)
    def authed_only_wrapper(*args, **kwargs):
        if authed():
            return f(*args, **kwargs)
        else:
            if (
                request.content_type == "application/json"
                or request.accept_mimetypes.best == "text/event-stream"
            ):
                abort(403)
            else:
                return redirect(url_for("auth.login", next=request.full_path))

    return authed_only_wrapper 
Example #13
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def require_authentication_if_config(config_key):
    def _require_authentication_if_config(f):
        @functools.wraps(f)
        def __require_authentication_if_config(*args, **kwargs):
            value = get_config(config_key)
            if value and current_user.authed():
                return redirect(url_for("auth.login", next=request.full_path))
            else:
                return f(*args, **kwargs)

        return __require_authentication_if_config

    return _require_authentication_if_config 
Example #14
Source File: views.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def static_html(route):
    """
    Route in charge of routing users to Pages.
    :param route:
    :return:
    """
    page = get_page(route)
    if page is None:
        abort(404)
    else:
        if page.auth_required and authed() is False:
            return redirect(url_for("auth.login", next=request.full_path))

        return render_template("page.html", content=page.content) 
Example #15
Source File: helper.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def forward_request():
    pdns_api_url = Setting().get('pdns_api_url')
    pdns_api_key = Setting().get('pdns_api_key')
    headers = {}
    data = None

    msg_str = "Sending request to powerdns API {0}"

    if request.method != 'GET' and request.method != 'DELETE':
        msg = msg_str.format(request.get_json(force=True))
        current_app.logger.debug(msg)
        data = request.get_json(force=True)

    verify = False

    headers = {
        'user-agent': 'powerdns-admin/api',
        'pragma': 'no-cache',
        'cache-control': 'no-cache',
        'accept': 'application/json; q=1',
        'X-API-KEY': pdns_api_key
    }

    url = urljoin(pdns_api_url, request.full_path)

    resp = requests.request(request.method,
                            url,
                            headers=headers,
                            verify=verify,
                            json=data)

    return resp 
Example #16
Source File: web.py    From automatron with Apache License 2.0 5 votes vote down vote up
def before_request():
    ''' Pre-request hander '''
    logger.debug("Incoming Web Request: {0}".format(request.full_path))
    g.dbc = connect_db(app.config) 
Example #17
Source File: app.py    From SnowAlert with Apache License 2.0 5 votes vote down vote up
def error_handler(ex):
    logger.exception(
        'An error has occurred! ({} {} {} {})'.format(
            request.remote_addr, request.method, request.scheme, request.full_path
        )
    )
    return 'Internal Server Error', 500 
Example #18
Source File: WebApp.py    From AIOPS_PLATFORM with MIT License 5 votes vote down vote up
def exceptions(e):
    """ Logging after every Exception. """
    ts = strftime('[%Y-%b-%d %H:%M]')
    logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR',
                  ts,
                  request.remote_addr,
                  request.method,
                  request.scheme,
                  request.full_path)
    return("Internal Server Error", 500) 
Example #19
Source File: WebApp.py    From AIOPS_PLATFORM with MIT License 5 votes vote down vote up
def after_request(response):
    if response.status_code != 500:
        ts = strftime('[%Y-%b-%d %H:%M]')
        logger.info('%s %s %s %s %s %s',
                      ts,
                      request.remote_addr,
                      request.method,
                      request.scheme,
                      request.full_path,
                      response.status)
    return(response) 
Example #20
Source File: entrypoint.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def exceptions(e):
    """App exception logger."""
    tb = traceback.format_exc()
    service_log.error(
        '{} {} {} {} 5xx INTERNAL SERVER ERROR\n{}'.format(
            request.remote_addr, request.method, request.scheme,
            request.full_path, tb
        )
    )

    return e.status_code 
Example #21
Source File: entrypoint.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def after_request(response):
    """After request handler."""
    service_log.info(
        '{0} {1} {2} {3} {4}'.format(
            request.remote_addr, request.method, request.scheme,
            request.full_path, response.status
        )
    )

    return response 
Example #22
Source File: __init__.py    From hellogithub.com with GNU Affero General Public License v3.0 5 votes vote down vote up
def exceptions(e):
    tb = traceback.format_exc()
    tb = tb.decode('utf-8')
    logger.error('%s %s %s %s 5xx INTERNAL SERVER ERROR\n%s',
                 request.environ.get('HTTP_X_REAL_IP', request.remote_addr),
                 request.method, request.scheme, request.full_path, tb)
    return '500 INTERNAL SERVER ERROR', 500 
Example #23
Source File: __init__.py    From hellogithub.com with GNU Affero General Public License v3.0 5 votes vote down vote up
def after_request(response):
    logger.info('%s %s %s %s %s', request.method,
                request.environ.get('HTTP_X_REAL_IP', request.remote_addr),
                request.scheme, request.full_path, response.status)
    return response 
Example #24
Source File: honeyku.py    From honeyku with GNU General Public License v3.0 5 votes vote down vote up
def catch_all(path):
	# Load the config file
	config=load_config()
	# Honeytoken alerts
	if request.path in config['traps'] and request.path != "/favicon.ico":
		# Preparing the alert message
		alertMessage = alert_msg(request, config)
		# Slack alert
		if config['alert']['slack']['enabled'] == "true":
			WEBHOOK_URL = config['alert']['slack']['webhook-url']
			slack_alerter(alertMessage, WEBHOOK_URL)
		# Email alert
		if config['alert']['email']['enabled'] == "true":
			email_alerter(alertMessage, config)
		# SMS alert
		#TODO: Complete and test the SMS alert
		#if config['alert']['sms']['enabled'] == "true":
		#	sms_alerter(alertMessage, config)
		#TODO: HTTP Endpoint Support
	# Honeypot event logs
	if request.headers.getlist("X-Forwarded-For"):
		source_ip = request.headers.getlist("X-Forwarded-For")[0]
	else:
		source_ip = request.remote_addr
	logger.info('{{"sourceip":"{}","host":"{}","request":"{}","http_method":"{}","body":"{}","user_agent":"{}"}}'.format(
		source_ip, request.url_root, request.full_path, request.method, request.data, request.user_agent.string))
	# Prepare and send the custom HTTP response
	contype, body = generate_http_response(request, config)
	# Customize the response using a template (in case you want to return a dynamic response, etc.)
	# You can comment the next 2 lines if you don't want to use this. /Just an example/
	if body == "custom.html":
		return (render_template(body, browser = request.user_agent.browser, ua = request.user_agent.string))
	return (send_file(body, mimetype=contype) if "image" in contype else render_template(body)) 
Example #25
Source File: app.py    From shorty with MIT License 5 votes vote down vote up
def exceptions(e):
	tb = traceback.format_exc()
	timestamp = strftime('[%Y-%b-%d %H:%M]')
	logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s',
        timestamp, request.remote_addr, request.method,
        request.scheme, request.full_path, tb)
	return make_response(e , 405) 
Example #26
Source File: app.py    From shorty with MIT License 5 votes vote down vote up
def after_request(response):
	timestamp = strftime('[%Y-%b-%d %H:%M]')
	logger.error('%s %s %s %s %s %s',timestamp , request.remote_addr , \
				request.method , request.scheme , request.full_path , response.status)
	return response 
Example #27
Source File: before_after.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def teardown_request(exc):
    call_finalizers()
    log.debug(u"End handling of request {!r}".format(request.full_path)) 
Example #28
Source File: before_after.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def log_begin_request():
    log.debug(u"Begin handling of request {!r}".format(request.full_path)) 
Example #29
Source File: __init__.py    From listenbrainz-server with GNU General Public License v2.0 4 votes vote down vote up
def create_app(config_path=None, debug=None):

    app = gen_app(config_path=config_path, debug=debug)

    # Static files
    import listenbrainz.webserver.static_manager
    static_manager.read_manifest()
    app.context_processor(lambda: dict(get_static_path=static_manager.get_static_path))
    app.static_folder = '/static'

    _register_blueprints(app)

    # Admin views
    from listenbrainz import model
    model.db.init_app(app)

    from flask_admin import Admin
    from listenbrainz.webserver.admin.views import HomeView
    admin = Admin(app, index_view=HomeView(name='Home'), template_mode='bootstrap3')
    from listenbrainz.model import Spotify as SpotifyModel
    from listenbrainz.model import User as UserModel
    from listenbrainz.model.spotify import SpotifyAdminView
    from listenbrainz.model.user import UserAdminView
    admin.add_view(UserAdminView(UserModel, model.db.session, endpoint='user_model'))
    admin.add_view(SpotifyAdminView(SpotifyModel, model.db.session, endpoint='spotify_model'))


    @app.before_request
    def before_request_gdpr_check():
        # skip certain pages, static content and the API
        if request.path == url_for('index.gdpr_notice') \
            or request.path == url_for('profile.delete') \
            or request.path == url_for('profile.export_data') \
            or request.path == url_for('login.logout') \
            or request.path.startswith('/static') \
            or request.path.startswith('/1'):
            return
        # otherwise if user is logged in and hasn't agreed to gdpr,
        # redirect them to agree to terms page.
        elif current_user.is_authenticated and current_user.gdpr_agreed is None:
            return redirect(url_for('index.gdpr_notice', next=request.full_path))

    return app 
Example #30
Source File: honeyku.py    From honeyku with GNU General Public License v3.0 4 votes vote down vote up
def alert_msg(req, conf):
	""" Prepare alert message dictionary """

	# Message fields
	url_root = req.url_root
	full_path = req.full_path
	path = req.path
	data = req.data
	http_method = req.method
	useragent_str = req.user_agent.string
	browser = req.user_agent.browser
	browser_version = req.user_agent.version
	browser_lang = req.user_agent.language
	platform = req.user_agent.platform
	headers = "{}".format(req.headers)
	args = ["{}={}".format(key, value) for key, value in request.args.items()]
	# X-Forwarded-For: the originating IP address of the client connecting to the Heroku router
	if req.headers.getlist("X-Forwarded-For"):
		source_ip = req.headers.getlist("X-Forwarded-For")[0]
	else:
		source_ip = req.remote_addr

	# Search the config for the token note
	note = None
	if path in conf['traps']:
		# Check if the token is defined and has note
		for token in args:
			if (token in conf['traps'][path]) and ("token-note" in conf['traps'][path][token]):
				note = conf['traps'][path][token]['token-note']
		# If the 'note' is still empty, use the trap/uri note (if there's any)
		if ("trap-note" in conf['traps'][path]) and note is None:
			note = conf['traps'][path]['trap-note']

	#TODO: Threat Intel Lookup (Cymon v2)

	# Message dictionary
	msg = {
		"token-note": note if note else "None",
		"host": url_root,
		"path": full_path if full_path else "None",
		"http-method": http_method,
		"token": args[0] if args else "None", #Only the first arg
		"body": data if data else "None",
		"source-ip": source_ip,
		"user-agent": useragent_str,
		"browser": browser if browser else "None",
		"browser_version": browser_version if browser_version else "None",
		"browser_lang": browser_lang if browser_lang else "None",
		"platform": platform if platform else "None",
		"http-headers": headers
		#"threat-intel": threat_intel
	}

	return msg