Python flask.request.environ() Examples

The following are 30 code examples for showing how to use flask.request.environ(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module flask.request , or try the search function .

Example 1
Project: geofront   Author: spoqa   File: server_test.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_identity_403(fx_app, fx_token_store, fx_token_id):
    expires_at = (datetime.datetime.now(datetime.timezone.utc) +
                  datetime.timedelta(hours=1))
    fx_token_store.set(
        fx_token_id,
        Token(Identity(DummyTeam, 1, False), expires_at)
    )
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 403
            data = json.loads(response.get_data())
            assert data['error'] == 'not-authorized'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example 2
Project: calibre-web   Author: janeczku   File: web.py    License: GNU General Public License v3.0 6 votes vote down vote up
def send_to_kindle(book_id, book_format, convert):
    if not config.get_mail_server_configured():
        flash(_(u"Please configure the SMTP mail settings first..."), category="error")
    elif current_user.kindle_mail:
        result = send_mail(book_id, book_format, convert, current_user.kindle_mail, config.config_calibre_dir,
                           current_user.nickname)
        if result is None:
            flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=current_user.kindle_mail),
                  category="success")
            ub.update_download(book_id, int(current_user.id))
        else:
            flash(_(u"Oops! There was an error sending this book: %(res)s", res=result), category="error")
    else:
        flash(_(u"Please update your profile with a valid Send to Kindle E-mail Address."), category="error")
    if "HTTP_REFERER" in request.environ:
        return redirect(request.environ["HTTP_REFERER"])
    else:
        return redirect(url_for('web.index'))


# ################################### Login Logout ################################################################## 
Example 3
Project: rucio   Author: rucio   File: common.py    License: Apache License 2.0 6 votes vote down vote up
def before_request():
    if request.environ.get('REQUEST_METHOD') == 'OPTIONS':
        return '', 200

    auth_token = request.environ.get('HTTP_X_RUCIO_AUTH_TOKEN')

    try:
        auth = validate_auth_token(auth_token)
    except RucioException as error:
        return generate_http_error_flask(500, error.__class__.__name__, error.args[0])
    except Exception as error:
        print(format_exc())
        return error, 500

    if auth is None:
        return generate_http_error_flask(401, 'CannotAuthenticate', 'Cannot authenticate with given credentials')

    request.environ['issuer'] = auth.get('account')
    request.environ['identity'] = auth.get('identity')
    request.environ['request_id'] = generate_uuid()
    request.environ['start_time'] = time() 
Example 4
Project: rucio   Author: rucio   File: common.py    License: Apache License 2.0 6 votes vote down vote up
def check_accept_header_wrapper_flask(supported_content_types):
    """ Decorator to check if an endpoint supports the requested content type. """
    def wrapper(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            requested_content_type = request.environ.get('HTTP_ACCEPT')
            request_type_allowed = True
            if requested_content_type:
                if ',' in requested_content_type:
                    for content_type in requested_content_type.replace(' ', '').split(','):
                        if content_type in supported_content_types or '*/*' in content_type:
                            request_type_allowed = True
                            break
                        else:
                            request_type_allowed = False
                else:
                    if requested_content_type not in supported_content_types and '*/*' not in requested_content_type:
                        request_type_allowed = False

            if not request_type_allowed:
                return generate_http_error_flask(406, 'UnsupportedRequestedContentType', 'The requested content type %s is not supported. Use %s.' % (requested_content_type, ','.join(supported_content_types)))
            return f(*args, **kwargs)
        return decorated
    return wrapper 
Example 5
Project: cascade-server   Author: mitre   File: ws.py    License: Apache License 2.0 6 votes vote down vote up
def session_stream(session_id):
    """
    Session specific notification stream
    :param session_id: the id of the current session
    """
    current_session = Session.objects.get(id=session_id)
    if isinstance(current_session, Session):
        # Open a new socket to stream messages to the server
        if request.method == 'GET':
            if request.environ.get(WSGI_WEBSOCKET):
                ws = request.environ[WSGI_WEBSOCKET]
                for message in current_session.queue.stream():
                    ws.send(message)

        # Add a new message to the stream
        elif request.method == 'POST':
            if isinstance(request.json, dict):
                current_session.queue.add(request.json)

    return "" 
Example 6
Project: openprocurement.auction   Author: openprocurement   File: auctions_server.py    License: Apache License 2.0 6 votes vote down vote up
def log():

    try:
        data = loads(request.data)
        if 'MESSAGE' in data:
            msg = data.get('MESSAGE')
            del data['MESSAGE']
        else:
            msg = ''
        data['REMOTE_ADDR'] = ','.join(
            [ip
             for ip in request.environ.get('HTTP_X_FORWARDED_FOR', '').split(',')
             if not ip.startswith('172.')]
        )
        if request.environ.get('REMOTE_ADDR', '') and data['REMOTE_ADDR'] == '':
            data['REMOTE_ADDR'] += request.environ.get('REMOTE_ADDR', '')
        data['SYSLOG_IDENTIFIER'] = 'AUCTION_CLIENT'
        send(msg, **data)
        return Response('ok')
    except:
        return Response('error') 
Example 7
Project: TurtleFaucet   Author: krruzic   File: faucet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_shells():
    form = FaucetForm()
    addrs = check_address()
    for ban in addrs:
        if form.address.data==ban[0] or request.environ['REMOTE_ADDR']==ban[1] or form.address==TWELVEPROBLEMS: # user shadowbanned, pretend to give turtles.
            app.logger.info("USER BANNED!")
            return json.dumps({'status':'OK'}),200
    if form.fingerprint.data=='':
        return json.dumps({'status':'Fail',
            'reason':'Fingerprint not detected...'}),400
    if form.address.data==ADDRESS:
        return json.dumps({'status':'Fail',
            'reason':'The faucet cannot send to itself'}),403
    if form.validate_on_submit():
        resp = do_send(form.address.data,request,100)
        if "reason" in json.loads(resp):
            return resp,500
        return json.dumps({'status':'OK'}),200
    return json.dumps({'status':'Fail',
            'reason':'Make sure the captcha and address fields are filled'}),400 
Example 8
Project: TurtleFaucet   Author: krruzic   File: ratelimit.py    License: GNU General Public License v3.0 6 votes vote down vote up
def ratelimit(limit, per=300, send_x_headers=True,
              over_limit=on_over_limit,
              fp_func=lambda: request.form.get('fingerprint'),
              ip_func=lambda: request.environ['REMOTE_ADDR'],
              key_func=lambda: request.endpoint):
    def decorator(f):
        def rate_limited(*args, **kwargs):
            ip_key = 'ip-limit/%s/%s/' % (key_func(), ip_func())
            fp_key = 'fp-limit/%s/%s/' % (key_func(), fp_func())
            rlimit = RateLimit(ip_key, fp_key, limit, per, send_x_headers)
            g._view_rate_limit = rlimit

            # check if IP has been used LIMIT times
            if rlimit.over_ip_limit:
                return over_limit(rlimit)

            # IP is good, check fingerprint now
            if not rlimit.over_ip_limit:
                if rlimit.over_fp_limit:
                    return over_limit(rlimit)

            return f(*args, **kwargs)
        return update_wrapper(rate_limited, f)
    return decorator 
Example 9
Project: maple-blog   Author: honmaple   File: alias.py    License: GNU General Public License v3.0 6 votes vote down vote up
def init_app(app):
    app.add_url_rule(
        "/en",
        defaults={"uri": ""},
        view_func=redirect_en,
    )

    app.add_url_rule(
        "/en/<path:uri>",
        view_func=redirect_en,
    )
    # @app.before_request
    # def before_request():
    #     if request.path.startswith("/en/"):
    #         request.environ["HTTP_ACCEPT_LANGUAGE"] = "en-US,en;q=0.5"

    # url_map = list(app.url_map.iter_rules())
    # for rule in url_map:
    #     app.add_url_rule("/en" + rule.rule, rule.endpoint, alias=True) 
Example 10
Project: spendb   Author: openspending   File: error.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def handle_error(exc):
    status = 500
    title = exc.__class__.__name__
    message = unicode(exc)
    headers = {}
    if isinstance(exc, HTTPException):
        message = exc.get_description(request.environ)
        message = message.replace('<p>', '').replace('</p>', '')
        status = exc.code
        title = exc.name
        headers = exc.get_headers(request.environ)
    data = {
        'status': status,
        'title': title,
        'message': message
    }
    return jsonify(data, status=status, headers=headers) 
Example 11
Project: opentelemetry-python   Author: open-telemetry   File: test_programmatic.py    License: Apache License 2.0 6 votes vote down vote up
def test_only_strings_in_environ(self):
        """
        Some WSGI servers (such as Gunicorn) expect keys in the environ object
        to be strings

        OpenTelemetry should adhere to this convention.
        """
        nonstring_keys = set()

        def assert_environ():
            for key in request.environ:
                if not isinstance(key, str):
                    nonstring_keys.add(key)
            return "hi"

        self.app.route("/assert_environ")(assert_environ)
        self.client.get("/assert_environ")
        self.assertEqual(nonstring_keys, set()) 
Example 12
Project: W.I.L.L   Author: ironman5366   File: web.py    License: MIT License 6 votes vote down vote up
def get_updates(data):
    """
    :param data: socket.io data about the update thread:
    Authenticate and start the update thread
    :return:
    """
    log.info(":SOCKET:get_updates")
    session_id = data["session_id"]
    if session_id:
        if session_id in core.sessions.keys():
            #If the session id is valid
            log.debug("{1}:Subscribing client {0} to updates for session_id".format(
                request.environ["REMOTE_ADDR"], session_id
            ))
            #Keep running this loop while the session is active
            log.info(":{0}:Starting update loop".format(session_id))
            update_thread = threading.Thread(target=update_loop, args=(session_id, request.sid))
            update_thread.start()
        else:
            log.debug("Session id {0} is invalid".format(session_id))
            socketio.emit("update", {"value": "Error, invalid session id"})
    else:
        socketio.emit("update", {"value": "Error, couldn't find session id in update request"}) 
Example 13
Project: marvin   Author: sdss   File: index.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def logout(self):
        ''' logout from the system
        '''

        result = {'logout': 'success'}

        if 'loginready' in current_session:
            ready = current_session.pop('loginready')

        if 'name' in current_session:
            name = current_session.pop('name')

        request.environ['REMOTE_USER'] = None
        config.access = 'public'
        set_session_versions(config.release)
        setGlobalSession()
        logout_user()

        return redirect(url_for('index_page.Marvin:index')) 
Example 14
Project: schedula   Author: vinci1it2000   File: __init__.py    License: European Union Public License 1.1 6 votes vote down vote up
def run(self, **options):
        self.shutdown()
        import threading
        options = combine_dicts(self.run_options, options)
        memo = os.environ.get("WERKZEUG_RUN_MAIN")
        try:
            os.environ["WERKZEUG_RUN_MAIN"] = "true"
            threading.Thread(
                target=run_server,
                args=(self.app(), self.get_port(**options))
            ).start()
            # noinspection PyArgumentList
            self.shutdown = weakref.finalize(self, self.shutdown_site, self.url)
            self.wait_server()
        finally:
            if memo is None:
                os.environ.pop("WERKZEUG_RUN_MAIN")
            else:
                os.environ["WERKZEUG_RUN_MAIN"] = memo

        return self 
Example 15
Project: ok   Author: okpy   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def init_app(app):
    if app.debug:
        return

    if __name__ != '__main__':
        gunicorn_logger = logging.getLogger('gunicorn.error')
        app.logger.handlers = gunicorn_logger.handlers
        app.logger.setLevel(gunicorn_logger.level)

    root_logger = logging.getLogger()
    root_logger.setLevel(app.config['LOG_LEVEL'])
    root_logger.addHandler(RequestLogHandler())
    app.logger.propagate = True

    @app.before_request
    def start_request_log():
        request.environ[REQUEST_LOG_VARIABLE] = RequestLog() 
Example 16
Project: geofront   Author: spoqa   File: server_test.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_identity_404(fx_app, fx_token_id):
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 404
            data = json.loads(response.get_data())
            assert data['error'] == 'token-not-found'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example 17
Project: geofront   Author: spoqa   File: server_test.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_identity_412(fx_app, fx_token_store, fx_token_id):
    fx_token_store.set(fx_token_id, 'nonce')
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 412
            data = json.loads(response.get_data())
            assert data['error'] == 'unfinished-authentication'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example 18
Project: geofront   Author: spoqa   File: server_test.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_public_key_404(fx_app, fx_key_store,
                            fx_authorized_identity,
                            fx_token_id):
    with fx_app.test_request_context():
        try:
            result = get_public_key(fx_token_id, os.urandom(16))
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 404
            assert response.mimetype == 'application/json'
            error = json.loads(response.get_data(as_text=True))
            assert error['error'] == 'not-found'
        else:
            fail('get_public_key() does not raise HTTPException, '
                 'but returns ' + repr(result)) 
Example 19
Project: recruit   Author: Frank-qlu   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def get_env():
    """Get the environment the app is running in, indicated by the
    :envvar:`FLASK_ENV` environment variable. The default is
    ``'production'``.
    """
    return os.environ.get('FLASK_ENV') or 'production' 
Example 20
Project: recruit   Author: Frank-qlu   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def get_debug_flag():
    """Get whether debug mode should be enabled for the app, indicated
    by the :envvar:`FLASK_DEBUG` environment variable. The default is
    ``True`` if :func:`.get_env` returns ``'development'``, or ``False``
    otherwise.
    """
    val = os.environ.get('FLASK_DEBUG')

    if not val:
        return get_env() == 'development'

    return val.lower() not in ('0', 'false', 'no') 
Example 21
Project: recruit   Author: Frank-qlu   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def get_load_dotenv(default=True):
    """Get whether the user has disabled loading dotenv files by setting
    :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the
    files.

    :param default: What to return if the env var isn't set.
    """
    val = os.environ.get('FLASK_SKIP_DOTENV')

    if not val:
        return default

    return val.lower() in ('0', 'false', 'no') 
Example 22
Project: jbox   Author: jpush   File: helpers.py    License: MIT License 5 votes vote down vote up
def get_debug_flag(default=None):
    val = os.environ.get('FLASK_DEBUG')
    if not val:
        return default
    return val not in ('0', 'false', 'no') 
Example 23
Project: rucio   Author: rucio   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def after_request(response):
    response.headers['Access-Control-Allow-Origin'] = request.environ.get('HTTP_ORIGIN')
    response.headers['Access-Control-Allow-Headers'] = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Credentials'] = 'true'

    if request.environ.get('REQUEST_METHOD') == 'GET':
        response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'
        response.headers['Cache-Control'] = 'post-check=0, pre-check=0'
        response.headers['Pragma'] = 'no-cache'

    return response 
Example 24
Project: SempoBlockchain   Author: teamsempo   File: auth_api.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self):

        print("process started")

        challenges = [
            ('Why don’t they play poker in the jungle?', 'Too many cheetahs.'),
            ('What did the Buddhist say to the hot dog vendor?', 'Make me one with everything.'),
            ('What does a zombie vegetarian eat?', 'Graaaaaaaains!'),
            ('My new thesaurus is terrible.', 'Not only that, but it’s also terrible.'),
            ('Why didn’t the astronaut come home to his wife?', 'He needed his space.'),
            ('I got fired from my job at the bank today.',
             'An old lady came in and asked me to check her balance, so I pushed her over.'),
            ('I like to spend every day as if it’s my last',
             'Staying in bed and calling for a nurse to bring me more pudding.')
        ]

        challenge = random.choice(challenges)

        # time.sleep(int(request.args.get('delay', 0)))
        # from functools import reduce
        # reduce(lambda x, y: x + y, range(0, int(request.args.get('count', 1))))

        # memory_to_consume = int(request.args.get('MB', 0)) * 1000000
        # bytearray(memory_to_consume)

        ip_address = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        user_agent = request.environ["HTTP_USER_AGENT"]
        ip = request.environ["REMOTE_ADDR"]
        # proxies = request.headers.getlist("X-Forwarded-For")
        # http://esd.io/blog/flask-apps-heroku-real-ip-spoofing.html

        response_object = {
            'status': 'success',
            'who_allows_a_get_request_to_their_auth_endpoint': 'We do.',
            challenge[0]: challenge[1],
            # 'metadata': {'user_agent': user_agent, 'ip': ip_address, 'otherip': ip, 'proxies': proxies},
        }
        return make_response(jsonify(response_object)), 200 
Example 25
Project: RSSNewsGAE   Author: liantian-cn   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def get_debug_flag(default=None):
    val = os.environ.get('FLASK_DEBUG')
    if not val:
        return default
    return val not in ('0', 'false', 'no') 
Example 26
Project: openprocurement.auction   Author: openprocurement   File: auctions_server.py    License: Apache License 2.0 5 votes vote down vote up
def auctions_proxy(auction_doc_id, path):
    auctions_server.logger.debug('Auction_doc_id: {}'.format(auction_doc_id))
    proxy_path = auctions_server.proxy_mappings.get(
        str(auction_doc_id),
        get_mapping,
        (auctions_server.config['REDIS'], str(auction_doc_id), False), max_age=60
    )
    auctions_server.logger.debug('Proxy path: {}'.format(proxy_path))
    if proxy_path:
        request.environ['PATH_INFO'] = '/' + path
        auctions_server.logger.debug('Start proxy to path: {}'.format(path))
        return StreamProxy(
            proxy_path,
            auction_doc_id=str(auction_doc_id),
            event_sources_pool=auctions_server.event_sources_pool,
            event_source_connection_limit=auctions_server.config['event_source_connection_limit'],
            pool=auctions_server.proxy_connection_pool,
            backend='gevent'
        )
    elif path == 'login' and auction_doc_id in auctions_server.db:
        if 'X-Forwarded-For' in request.headers:
            url = urlunparse(
                urlparse(request.url)._replace(netloc=request.headers['Host'])
            ).replace('/login', '')
            auctions_server.logger.info('Redirecting loging path to {}'.format(url))
            return redirect(url)
    elif path == 'event_source':
        events_close = PySse()
        events_close.add_message('Close', 'Disable')
        return Response(
            events_close,
            mimetype='text/event-stream',
            content_type='text/event-stream'
        )
    return abort(404) 
Example 27
Project: chainerui   Author: chainer   File: test_client.py    License: MIT License 5 votes vote down vote up
def _shutdown(self):
        from flask import request
        if 'werkzeug.server.shutdown' not in request.environ:
            return 'Server has already shut down'

        request.environ['werkzeug.server.shutdown']()
        return 'Server is shutting down...' 
Example 28
Project: maple-blog   Author: honmaple   File: alias.py    License: GNU General Public License v3.0 5 votes vote down vote up
def redirect_en(uri):
    view_function = get_view_function(
        "/" + uri,
        request.method,
    )
    if view_function is None:
        abort(404)
    request.environ["HTTP_ACCEPT_LANGUAGE"] = "en-US,en;q=0.5"
    return view_function[0](**view_function[1]) 
Example 29
Project: yabgp   Author: smartbgp   File: utils.py    License: 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 30
Project: Building-Recommendation-Systems-with-Python   Author: PacktPublishing   File: helpers.py    License: MIT License 5 votes vote down vote up
def get_env():
    """Get the environment the app is running in, indicated by the
    :envvar:`FLASK_ENV` environment variable. The default is
    ``'production'``.
    """
    return os.environ.get('FLASK_ENV') or 'production'