Python flask.request.environ() Examples

The following are 30 code examples of flask.request.environ(). 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: web.py    From W.I.L.L with 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 #2
Source File: faucet.py    From TurtleFaucet with 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 #3
Source File: auctions_server.py    From openprocurement.auction with 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 #4
Source File: __init__.py    From schedula with 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 #5
Source File: ratelimit.py    From TurtleFaucet with 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 #6
Source File: ws.py    From cascade-server with 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 #7
Source File: common.py    From rucio with 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 #8
Source File: test_programmatic.py    From opentelemetry-python with 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 #9
Source File: common.py    From rucio with 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 #10
Source File: alias.py    From maple-blog with 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 #11
Source File: web.py    From calibre-web with 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 #12
Source File: index.py    From marvin with 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 #13
Source File: server_test.py    From geofront with 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 #14
Source File: error.py    From spendb with 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 #15
Source File: __init__.py    From ok with 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
Source File: post.py    From maniwani with MIT License 5 votes vote down vote up
def get_ip_address() -> str:
    "Returns the current IP address of the user."

    if "X-Forwarded-For" in request.headers:
        return request.headers.getlist("X-Forwarded-For")[0].split()[-1]
    return request.environ["REMOTE_ADDR"] 
Example #17
Source File: userfiles.py    From quay with Apache License 2.0 5 votes vote down vote up
def put(self, file_id):
        input_stream = request.stream
        if request.headers.get("transfer-encoding") == "chunked":
            # Careful, might work only with WSGI servers supporting chunked
            # encoding (Gunicorn)
            input_stream = request.environ["wsgi.input"]

        c_type = request.headers.get("Content-Type", None)

        path = self._files.get_file_id_path(file_id)
        self._storage.stream_write(self._locations, path, input_stream, c_type)

        return make_response("Okay") 
Example #18
Source File: __init__.py    From Flask-MonitoringDashboard with MIT License 5 votes vote down vote up
def start_performance_thread(endpoint, duration, status_code):
    """
    Starts a thread that updates performance, utilization and last_requested in the database.
    :param endpoint: Endpoint object
    :param duration: duration of the request
    :param status_code: HTTP status code of the request
    """
    ip = request.environ['REMOTE_ADDR']
    group_by = get_group_by()
    PerformanceProfiler(endpoint, ip, duration, group_by, status_code).start() 
Example #19
Source File: server_instrumented.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def server_request():
    with tracer.start_as_current_span(
        "server_request",
        parent=propagators.extract(
            lambda dict_, key: dict_.get(key, []), request.headers
        )["current-span"],
        kind=trace.SpanKind.SERVER,
        attributes=collect_request_attributes(request.environ),
    ):
        print(request.args.get("param"))
        return "served" 
Example #20
Source File: __init__.py    From Flask-MonitoringDashboard with MIT License 5 votes vote down vote up
def start_outlier_thread(endpoint):
    """ Starts a thread that collects outliers."""
    current_thread = threading.current_thread().ident
    ip = request.environ['REMOTE_ADDR']
    group_by = get_group_by()
    thread = OutlierProfiler(current_thread, endpoint, ip, group_by)
    thread.start()
    return thread 
Example #21
Source File: locationscanningreceiver.py    From meraki-code with MIT License 5 votes vote down vote up
def get_locationJSON():
    global locationdata

    if not request.json or not "data" in request.json:
        return ("invalid data", 400)

    locationdata = request.json
    pprint(locationdata, indent=1)
    print("Received POST from ", request.environ["REMOTE_ADDR"])

    # Verify secret
    if locationdata["secret"] != secret:
        print("secret invalid:", locationdata["secret"])
        return ("invalid secret", 403)

    else:
        print("secret verified: ", locationdata["secret"])

    # Verify version
    if locationdata["version"] != version:
        print("invalid version")
        return ("invalid version", 400)

    else:
        print("version verified: ", locationdata["version"])

    # Determine device type
    if locationdata["type"] == "DevicesSeen":
        print("WiFi Devices Seen")
    elif locationdata["type"] == "BluetoothDevicesSeen":
        print("Bluetooth Devices Seen")
    else:
        print("Unknown Device 'type'")
        return ("invalid device type", 403)

    # Return success message
    return "Location Scanning POST Received" 
Example #22
Source File: locationscanningreceiver.py    From meraki-code with MIT License 5 votes vote down vote up
def get_validator():
    print("validator sent to: ", request.environ["REMOTE_ADDR"])
    return validator


# Accept CMX JSON POST 
Example #23
Source File: controller.py    From ryu with Apache License 2.0 5 votes vote down vote up
def websocket():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        return _view('websocket', ws)
    abort(404) 
Example #24
Source File: helpers.py    From planespotter with 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 #25
Source File: flask_gopher.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def make_environ(self):
        environ = super().make_environ()
        if self.request_version == 'gopher':
            environ['wsgi.url_scheme'] = 'gopher'
            environ['SEARCH_TEXT'] = self.search_text
            environ['SECURE'] = isinstance(self.request, ssl.SSLSocket)

            # Flask has a sanity check where if app.config['SERVER_NAME'] is
            # defined, it has to match either the HTTP host header or the
            # WSGI server's environ['SERVER_NAME']. With the werkzeug WSGI
            # server, environ['SERVER_NAME'] is set to the bind address
            # (e.g. 127.0.0.1) and it can't be configured. This means that
            # if we want to set app.config['SERVER_NAME'] to an external IP
            # address or domain name, we need to spoof either the HTTP_HOST
            # header or the SERVER_NAME env variable to match it.
            # Go look at werkzeug.routing.Map.bind_to_environ()
            try:
                server_name = self.server.app.config.get('SERVER_NAME')
            except Exception:
                pass
            else:
                if server_name:
                    if ':' in server_name:
                        environ['SERVER_PORT'] = server_name.split(':')[1]
                    environ['SERVER_NAME'] = server_name.split(':')[0]
        return environ 
Example #26
Source File: run_server.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def demo_environ():
    environ_table = [('Field', 'Value')]
    for key, val in sorted(request.environ.items()):
        if not key.startswith(('werkzeug', 'wsgi')):
            environ_table.append((key, val))

    return gopher.render_menu_template('demo_environ.gopher', environ_table=environ_table) 
Example #27
Source File: run_server.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def demo_ssl():
    secure = request.environ['SECURE']
    return gopher.render_menu_template('demo_ssl.gopher', secure=secure) 
Example #28
Source File: run_server.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def demo_session(action):
    if action == 'create':
        session['id'] = request.environ['SEARCH_TEXT']
    elif action == 'delete':
        session.clear()
    return gopher.render_menu_template('demo_session.gopher', action=action) 
Example #29
Source File: run_server.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def figlet():
    """
    Render the search text using all possible figlet fonts.

    This loops through hundreds of fonts and may take a few seconds to return.
    """
    text = request.environ['SEARCH_TEXT']
    lines = []
    for font in sorted(FigletFont.getFonts()):
        lines.extend(gopher.formatter.figlet(text, font=font).splitlines())
        lines.append(font)
        lines.append('')
    return gopher.render_menu(*lines) 
Example #30
Source File: views.py    From honeybadger with GNU General Public License v3.0 5 votes vote down vote up
def api_beacon(target, agent):
    logger.info('{}'.format('='*50))
    data = {'target': target, 'agent': agent}
    logger.info('Target: {}'.format(target))
    logger.info('Agent: {}'.format(agent))
    # check if target is valid
    if target not in [x.guid for x in Target.query.all()]:
        logger.error('Invalid target GUID.')
        abort(404)
    # extract universal parameters
    comment = b64d(request.values.get('comment', '')) or None
    ip = request.environ['REMOTE_ADDR']
    port = request.environ['REMOTE_PORT']
    useragent = request.environ['HTTP_USER_AGENT']
    data.update({'comment': comment, 'ip': ip, 'port': port, 'useragent': useragent})
    logger.info('Connection from {} @ {}:{} via {}'.format(target, ip, port, agent))
    logger.info('Parameters: {}'.format(request.values.to_dict()))
    logger.info('User-Agent: {}'.format(useragent))
    logger.info('Comment: {}'.format(comment))
    data.update(request.values.to_dict())
    # process json payloads
    if request.json:
        if process_json(data, request.json):
            abort(404)
    # process known coordinates
    if all(k in data for k in ('lat', 'lng', 'acc')):
        if process_known_coords(data):
            abort(404)
    # process wireless survey
    elif all(k in data for k in ('os', 'data')):
        if process_wlan_survey(data):
            abort(404)
    # process ip geolocation (includes fallback)
    process_ip(data)
    abort(404)