Python flask.request.query_string() Examples

The following are 14 code examples of flask.request.query_string(). 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: srv.py    From rate.sx with MIT License 5 votes vote down vote up
def answer(topic = None):
    """
    Main rendering function, it processes incoming weather queries.
    Depending on user agent it returns output in HTML or ANSI format.

    Incoming data:
        request.args
        request.headers
        request.remote_addr
        request.referrer
        request.query_string
    """

    user_agent = request.headers.get('User-Agent', '').lower()
    html_needed = is_html_needed(user_agent)
    options = parse_query(request.args)
    hostname = request.headers['Host']

    if request.headers.getlist("X-Forwarded-For"):
       ip = request.headers.getlist("X-Forwarded-For")[0]
       if ip.startswith('::ffff:'):
           ip = ip[7:]
    else:
       ip = request.remote_addr

    if topic is None:
        topic = ":firstpage"

    answer = cmd_wrapper(topic, hostname=hostname, request_options=options, html=is_html_needed(user_agent))
    
    if ip not in SKIP_LOGGING_FOR_THIS_IPS:
        log_query(ip, hostname, topic, user_agent)
    return answer 
Example #2
Source File: flask_utils.py    From Quiver-alfred with MIT License 5 votes vote down vote up
def get_current_url():
    if not request.query_string:
        return request.path
    return '%s?%s' % (request.path, request.query_string) 
Example #3
Source File: views.py    From MegaQC with GNU General Public License v3.0 5 votes vote down vote up
def get(self, args):
        # We need to give each resource a unique ID so the client doesn't try to cache
        # or reconcile different plots
        request_hash = sha1(request.query_string).hexdigest()

        plots = plot.trend_data(plot_prefix=request_hash, **args)

        return schemas.TrendSchema(many=True, unknown=INCLUDE).dump(plots) 
Example #4
Source File: app.py    From shamer with MIT License 5 votes vote down vote up
def go_view(object_key):
  url = url_for('{}_view'.format(constants.get('MODE')), object_key=object_key)
  response = redirect('{}?{}'.format(url, request.query_string))
  return cached(response, datetime.datetime.utcnow(), expires=0) 
Example #5
Source File: views.py    From fame with GNU General Public License v3.0 5 votes vote down vote up
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 #6
Source File: views.py    From yeti with Apache License 2.0 5 votes vote down vote up
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 #7
Source File: utils.py    From yabgp with Apache License 2.0 5 votes vote down vote up
def log_request(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        LOG.info('API request url %s', request.url)
        if request.query_string:
            LOG.info('API query string %s', request.query_string)
        LOG.info('API request method %s', request.method)
        if request.method == 'POST':
            LOG.info('API POST data %s', request.json)
        LOG.debug('API request environ %s', request.environ)
        return f(*args, **kwargs)
    return decorated_function 
Example #8
Source File: saml.py    From InfraBox with Apache License 2.0 5 votes vote down vote up
def init_saml_auth():
    parsed_url = urlparse(request.url)
    request_data = {
        "https": "on" if request.scheme == "https" else "off",
        "http_host": request.host,
        "server_port": parsed_url.port,
        "script_name": request.path,
        "get_data": request.args.copy(),
        "post_data": request.form.copy(),
        "query_string": request.query_string
        }

    auth = OneLogin_Saml2_Auth(request_data, custom_base_path=get_env("INFRABOX_ACCOUNT_SAML_SETTINGS_PATH"))
    return auth 
Example #9
Source File: views.py    From aeon-ztps with Apache License 2.0 5 votes vote down vote up
def _get_devices():
    db = aeon_ztp.db.session
    to_json = device_schema

    # ---------------------------------------------------------------
    # if the request has arguments, use these to form an "and" filter
    # and return only the subset of items matching
    # ---------------------------------------------------------------

    if request.args:
        try:
            recs = find_devices(db, request.args.to_dict())
            if len(recs) == 0:
                return jsonify(ok=False,
                               message='Not Found: %s' % request.query_string), 404

            items = [to_json.dump(rec).data for rec in recs]
            return jsonify(count=len(items), items=items)

        except AttributeError:
            return jsonify(ok=False, message='invalid arguments'), 500

    # -------------------------------------------
    # otherwise, return all items in the database
    # -------------------------------------------

    items = [to_json.dump(rec).data for rec in db.query(Device).all()]
    return jsonify(count=len(items), items=items)


# -----------------------------------------------------------------------------
#                                 POST /api/devices
# ----------------------------------------------------------------------------- 
Example #10
Source File: views.py    From aeon-ztps with Apache License 2.0 5 votes vote down vote up
def _delete_devices():
    if request.args.get('all'):
        try:
            db = aeon_ztp.db.session
            db.query(Device).delete()
            db.commit()

        except Exception as exc:
            return jsonify(
                ok=False,
                message='unable to delete all records: {}'.format(exc.message)), 400

        return jsonify(ok=True, message='all records deleted')

    elif request.args:
        db = aeon_ztp.db.session
        try:
            recs = find_devices(db, request.args.to_dict())
            n_recs = len(recs)
            if n_recs == 0:
                return jsonify(ok=False,
                               message='Not Found: %s' % request.query_string), 404

            for dev in recs:
                db.delete(dev)
            db.commit()
            return jsonify(
                ok=True, count=n_recs,
                message='{} records deleted'.format(n_recs))

        except AttributeError:
            return jsonify(ok=False, message='invalid arguments'), 500

        except Exception as exc:
            msg = 'unable to delete specific records: {}'.format(exc.message)
            return jsonify(ok=False, message=msg), 500
    else:
        return jsonify(ok=False, message='all or filter required'), 400 
Example #11
Source File: utils.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def _get_uri_from_request(request):
    """
    The uri returned from request.uri is not properly urlencoded
    (sometimes it's partially urldecoded) This is a weird hack to get
    werkzeug to return the proper urlencoded string uri
    """
    uri = request.base_url
    if request.query_string:
        uri += '?' + request.query_string.decode('utf-8')
    return uri 
Example #12
Source File: rspet_server_api.py    From RSPET with MIT License 5 votes vote down vote up
def get_hosts():
    """Return all hosts."""
    #Check for query string, redirect to endpoint with trailling '/'.
    if request.query_string:
        return redirect(url_for('run_cmd') + '?' + request.query_string)
    hosts = RSPET_API.get_hosts()
    return jsonify({'hosts': [make_public_host(hosts[h_id], h_id) for h_id in hosts]}) 
Example #13
Source File: rspet_server_api.py    From RSPET with MIT License 5 votes vote down vote up
def get_host(host_id):
    """Return specific host."""
    #Check for query string, redirect to endpoint with trailling '/'.
    if request.query_string:
        return redirect(url_for('run_cmd_host', host_id=host_id) + '?' + request.query_string)
    hosts = RSPET_API.get_hosts()
    try:
        host = hosts[host_id]
    except KeyError:
        abort(404)
    return jsonify(make_public_host(host, host_id)) 
Example #14
Source File: login.py    From analytics-quarry-web with MIT License 5 votes vote down vote up
def oauth_callback():
    handshaker = Handshaker(
        "https://meta.wikimedia.org/w/index.php",
        oauth_token,
        user_agent=user_agent
    )
    try:
        access_token = handshaker.complete(session['request_token'], request.query_string)
    except (OAuthException, KeyError) as e:
        exception(e)
        flash('Fatal error occured while login (%s). Please try again after cleaning the cookies in your browser.'
              % str(e), 'danger')
        return redirect(url_for('index'))
    session['access_token'] = access_token
    identity = handshaker.identify(access_token)
    wiki_uid = identity['sub']
    user = g.conn.session.query(User).filter(User.wiki_uid == wiki_uid).first()
    if user is None:
        user = User(username=identity['username'], wiki_uid=wiki_uid)
        g.conn.session.add(user)
        g.conn.session.commit()
        flash('Welcome to Quarry, %s!' % user.username, 'success')
    elif user.username != identity['username']:
        user.username = identity['username']
        g.conn.session.add(user)
        try:
            g.conn.session.commit()
        except IntegrityError as e:
            if e[0] == 1062:  # Duplicate
                g.conn.session.rollback()
            else:
                raise

    session['user_id'] = user.id
    return_to_url = session.get('return_to_url')
    del session['request_token']
    del session['return_to_url']
    return redirect(return_to_url)