Python flask.request.remote_addr() Examples

The following are 30 code examples of flask.request.remote_addr(). 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: validators.py    From jbox with MIT License 8 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #2
Source File: endpoints.py    From mini-key-server with MIT License 7 votes vote down vote up
def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("token", required=True)
        parser.add_argument("machine", required=True)
        parser.add_argument("user", required=True)
        parser.add_argument("hwid", required=True)
        parser.add_argument("app_id", required=True, type=int)

        args = parser.parse_args()

        origin = Origin(request.remote_addr,
                        args.machine, args.user, args.hwid)

        if key_valid_const(args.app_id, args.token, origin):
            return {"result": "ok"}, 201

        return {"result": "failure", "error": "invalid key"}, 404 
Example #3
Source File: decorators.py    From api-pycon2014 with MIT License 7 votes vote down vote up
def rate_limit(limit, per, scope_func=lambda: request.remote_addr):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            if current_app.config['USE_RATE_LIMITS']:
                key = 'rate-limit/%s/%s/' % (f.__name__, scope_func())
                limiter = RateLimit(key, limit, per)
                if not limiter.over_limit:
                    rv = f(*args, **kwargs)
                else:
                    rv = too_many_requests('You have exceeded your request rate')
                #rv = make_response(rv)
                g.headers = {
                    'X-RateLimit-Remaining': str(limiter.remaining),
                    'X-RateLimit-Limit': str(limiter.limit),
                    'X-RateLimit-Reset': str(limiter.reset)
                }
                return rv
            else:
                return f(*args, **kwargs)
        return wrapped
    return decorator 
Example #4
Source File: validators.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #5
Source File: views.py    From social-relay with GNU Affero General Public License v3.0 6 votes vote down vote up
def receive_public():
    if not request.data:
        return abort(404)

    # Queue to rq for processing
    public_queue.enqueue("workers.receive.process", request.data, timeout=app.config.get("RELAY_WORKER_TIMEOUT"))

    # Log statistics
    log_receive_statistics(request.remote_addr)

    # return 200 whatever
    data = {
        'result': 'ok',
    }
    js = json.dumps(data)
    return Response(js, status=200, mimetype='application/json') 
Example #6
Source File: webhook.py    From Matrix-NEB with Apache License 2.0 6 votes vote down vote up
def do_POST(self, service=""):
        log.debug("NebHookServer: Plugin=%s : Incoming request from %s",
                  service, request.remote_addr)
        if service.split("/")[0] not in self.plugin_mappings:
            return ("", 404, {})

        plugin = self.plugin_mappings[service.split("/")[0]]

        try:
            # tuple (body, status_code, headers)
            response = plugin.on_receive_webhook(
                request.url,
                request.get_data(),
                request.remote_addr,
                request.headers
            )
            if response:
                return response
            return ("", 200, {})
        except Exception as e:
            log.exception(e)
            return ("", 500, {}) 
Example #7
Source File: dudulu.py    From dudulu with MIT License 6 votes vote down vote up
def mood():
    """
    情绪分析
    :return:
    """
    ip = request.remote_addr
    sentence = request.args.get("sentence")
    if not sentence:
        return Response(FAILED, None, info="Miss Params").to_json()
    if len(sentence) > MAX_WORD or len(sentence) < MIN_WORD:
        return Response(FAILED, None, info="The Sentence "
                                           "is too long.It should be %s to %s." % (MIN_WORD, MAX_WORD)).to_json()
    result = get_mood(sentence, key_word=KEY_WORD, model_name=MODEL_NAME)
    print("ip: %s | sentence: %s | positive: %s | negative: %s | neutral: %s" % (ip, sentence,
                                                                                 result["positive"], result["negative"],
                                                                                 result["neutral"]), file=SENTENCE_FILE)
    SENTENCE_FILE.flush()
    return Response(SUCCEED, result).to_json() 
Example #8
Source File: zmirror.py    From zmirror with MIT License 6 votes vote down vote up
def zmirror_status():
    """返回服务器的一些状态信息"""
    if request.remote_addr and request.remote_addr != '127.0.0.1':
        return generate_simple_resp_page(b'Only 127.0.0.1 are allowed', 403)
    output = ""
    output += strx('extract_real_url_from_embedded_url', extract_real_url_from_embedded_url.cache_info())
    output += strx('\nis_content_type_streamed', is_mime_streamed.cache_info())
    output += strx('\nembed_real_url_to_embedded_url', embed_real_url_to_embedded_url.cache_info())
    output += strx('\ncheck_global_ua_pass', check_global_ua_pass.cache_info())
    output += strx('\nextract_mime_from_content_type', extract_mime_from_content_type.cache_info())
    output += strx('\nis_content_type_using_cdn', is_content_type_using_cdn.cache_info())
    output += strx('\nis_ua_in_whitelist', is_content_type_using_cdn.cache_info())
    output += strx('\nis_mime_represents_text', is_mime_represents_text.cache_info())
    output += strx('\nis_domain_match_glob_whitelist', is_domain_match_glob_whitelist.cache_info())
    output += strx('\nverify_ip_hash_cookie', verify_ip_hash_cookie.cache_info())
    output += strx('\nis_denied_because_of_spider', is_denied_because_of_spider.cache_info())
    output += strx('\nis_ip_not_in_allow_range', is_ip_not_in_allow_range.cache_info())
    output += strx('\n\ncurrent_threads_number', threading.active_count())
    # output += strx('\nclient_requests_text_rewrite', client_requests_text_rewrite.cache_info())
    # output += strx('\nextract_url_path_and_query', extract_url_path_and_query.cache_info())

    output += strx('\n----------------\n')
    output += strx('\ndomain_alias_to_target_set', domain_alias_to_target_set)

    return "<pre>" + output + "</pre>\n" 
Example #9
Source File: user.py    From picoCTF with MIT License 6 votes vote down vote up
def _validate_captcha(data):
    """
    Validate a captcha with google's reCAPTCHA.

    Args:
        data: the posted form data
    """
    settings = api.config.get_settings()["captcha"]

    post_data = urllib.parse.urlencode(
        {
            "secret": settings["reCAPTCHA_private_key"],
            "response": data["g-recaptcha-response"],
            "remoteip": flask.request.remote_addr,
        }
    ).encode("utf-8")

    request = urllib.request.Request(settings["captcha_url"], post_data, method="POST")
    response = urllib.request.urlopen(request).read().decode("utf-8")
    parsed_response = json.loads(response)
    return parsed_response["success"] is True 
Example #10
Source File: access.py    From pscheduler with Apache License 2.0 6 votes vote down vote up
def access_write_task(original_requester, key=None):
    """
    Determine whether a requester can write to a task or its runs.
    """

    requester = request.remote_addr

    # Local interfaces are always okay.
    if requester in local_ips:
        return True

    # Tasks without keys are limited to the original requester only
    if key is None:
        return requester == original_requester

    # Beyond here, the task has a key.  

    request_key = arg_string("key")

    return (request_key is not None) and (request_key == key) 
Example #11
Source File: __init__.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
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 #12
Source File: autoapp.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: job_app.py    From FATE with Apache License 2.0 6 votes vote down vote up
def submit_job():
    work_mode = request.json.get('job_runtime_conf', {}).get('job_parameters', {}).get('work_mode', None)
    detect_utils.check_config({'work_mode': work_mode}, required_arguments=[('work_mode', (WorkMode.CLUSTER, WorkMode.STANDALONE))])
    if work_mode == RuntimeConfig.WORK_MODE:
        job_id, job_dsl_path, job_runtime_conf_path, logs_directory, model_info, board_url = JobController.submit_job(request.json)
        return get_json_result(retcode=0, retmsg='success',
                               job_id=job_id,
                               data={'job_dsl_path': job_dsl_path,
                                     'job_runtime_conf_path': job_runtime_conf_path,
                                     'model_info': model_info,
                                     'board_url': board_url,
                                     'logs_directory': logs_directory
                                     })
    else:
        if RuntimeConfig.WORK_MODE == WorkMode.CLUSTER and work_mode == WorkMode.STANDALONE:
            # use cluster standalone job server to execute standalone job
            return request_execute_server(request=request, execute_host='{}:{}'.format(request.remote_addr, CLUSTER_STANDALONE_JOB_SERVER_PORT))
        else:
            raise Exception('server run on standalone can not support cluster mode job') 
Example #14
Source File: rate_limit.py    From Flask-PostgreSQL-API-Seed with MIT License 6 votes vote down vote up
def rate_limit(limit=100, window=60):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            key = "{0}: {1}".format(request.remote_addr, request.path)

            try:
                remaining = limit - int(redis.get(key))
            except (ValueError, TypeError):
                remaining = limit
                redis.set(key, 0)

            expires_in = redis.ttl(key)
            if not expires_in:
                redis.expire(key, window)
                expires_in = window

            g.rate_limits = (limit, remaining-1, time()+expires_in)

            if remaining > 0:
                redis.incr(key, 1)
                return func(*args, **kwargs)
            return TOO_MANY_REQUESTS
        return wrapper
    return decorator 
Example #15
Source File: rate_limit_quotas.py    From api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_client_ipaddr(self) -> IpAddress:
        # https://github.com/alisaifee/flask-limiter/issues/41
        for m in self._limiter._ipaddr_extraction_methods:
            if m == "X-Forwarded-For":
                raise NotImplementedError("X-Forwarded-For ")

            elif m == "X-Real-Ip":
                ipaddr = request.headers.get("X-Real-Ip", None)
                if ipaddr:
                    return ipaddress.ip_address(ipaddr)

            elif m == "socket":
                return ipaddress.ip_address(request.remote_addr)

            else:
                raise NotImplementedError(f"IP address method {m} is unknown")

        methods = ",".join(self._limiter._ipaddr_extraction_methods)
        raise Exception(f"Unable to detect IP address using {methods}") 
Example #16
Source File: keymanager.py    From mini-key-server with MIT License 6 votes vote down vote up
def cut_key_unsafe(activations: int, app_id: int,
                   active: bool = True, memo: str = "") -> str:
    """
    Cuts a new key and returns the activation token.

    Cuts a new key with # `activations` allowed activations. -1 is considered
    unlimited activations.
    """
    token = generate_token_unsafe()
    key = Key(token, activations, app_id, active, memo)
    key.cutdate = datetime.utcnow()

    db.session.add(key)
    db.session.commit()

    current_app.logger.info(
        f"cut new key {key} with {activations} activation(s), memo: {memo}")
    AuditLog.from_key(key,
                      f"new key cut by {current_user.username} "
                      f"({request.remote_addr})",
                      Event.KeyCreated)

    return token 
Example #17
Source File: main.py    From IncetOps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def before_request():
    g.signin = verify_sessionId(request.cookies.get("sessionId"))
    g.sid, g.uid = analysis_sessionId(request.cookies.get("sessionId"), "tuple") if g.signin else (None, None)
    # 用户信息
    g.userinfo = get_userinfo(g.uid)
    app.logger.debug(g.userinfo)
    # 客户端IP地址
    g.ip = request.headers.get('X-Real-Ip', request.remote_addr)
    # 仅是重定向页面快捷定义
    g.redirect_uri = get_redirect_url() 
Example #18
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 #19
Source File: matcher_view.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def announce_matcher_progress(place):
    ''' Send mail to announce when somebody runs the matcher. '''
    if current_app.env == 'development':
        return
    if g.user.is_authenticated:
        user = g.user.username
        subject = 'matcher: {} (user: {})'.format(place.name, user)
    elif utils.is_bot():
        return  # don't announce bots
    else:
        user = 'not authenticated'
        subject = 'matcher: {} (no auth)'.format(place.name)

    user_agent = request.headers.get('User-Agent', '[header missing]')
    template = '''
user: {}
IP: {}
agent: {}
name: {}
page: {}
area: {}
'''

    body = template.format(user,
                           request.remote_addr,
                           user_agent,
                           place.display_name,
                           place.candidates_url(_external=True),
                           mail.get_area(place))
    mail.send_mail(subject, body) 
Example #20
Source File: utils.py    From ansible-runner-service with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: test_app.py    From airflow with Apache License 2.0 5 votes vote down vote up
def test_should_respect_base_url_when_proxy_fix_and_base_url_is_set_up_but_headers_missing(self):
        app = application.cached_app(testing=True)
        app.url_map.add(Rule("/debug", endpoint="debug"))

        def debug_view():
            from flask import request

            # Should use original REMOTE_ADDR
            self.assertEqual(request.remote_addr, '192.168.0.1')
            # Should respect base_url
            self.assertEqual(request.url, "http://invalid:9000/internal-client/debug")

            return Response("success")

        app.view_functions['debug'] = debug_view

        new_environ = {
            "PATH_INFO": "/internal-client/debug",
            "REMOTE_ADDR": "192.168.0.1",
            "HTTP_HOST": "invalid:9000",
        }
        environ = create_environ(environ_overrides=new_environ)

        response = Response.from_app(app, environ)

        self.assertEqual(b"success", response.get_data())
        self.assertEqual(response.status_code, 200) 
Example #22
Source File: test_app.py    From airflow with Apache License 2.0 5 votes vote down vote up
def test_should_respect_base_url_ignore_proxy_headers(self):
        app = application.cached_app(testing=True)
        app.url_map.add(Rule("/debug", endpoint="debug"))

        def debug_view():
            from flask import request

            # Should ignore HTTP_X_FORWARDED_FOR
            self.assertEqual(request.remote_addr, '192.168.0.2')
            # Should ignore HTTP_X_FORWARDED_PROTO, HTTP_X_FORWARDED_HOST, HTTP_X_FORWARDED_PORT,
            # HTTP_X_FORWARDED_PREFIX
            self.assertEqual(request.url, 'http://invalid:9000/internal-client/debug')

            return Response("success")

        app.view_functions['debug'] = debug_view

        new_environ = {
            "PATH_INFO": "/internal-client/debug",
            "REMOTE_ADDR": "192.168.0.2",
            "HTTP_HOST": "invalid:9000",
            "HTTP_X_FORWARDED_FOR": "192.168.0.1",
            "HTTP_X_FORWARDED_PROTO": "https",
            "HTTP_X_FORWARDED_HOST": "valid",
            "HTTP_X_FORWARDED_PORT": "445",
            "HTTP_X_FORWARDED_PREFIX": "/proxy-prefix",
        }
        environ = create_environ(environ_overrides=new_environ)

        response = Response.from_app(app, environ)

        self.assertEqual(b"success", response.get_data())
        self.assertEqual(response.status_code, 200) 
Example #23
Source File: listen_server.py    From macro_pack with Apache License 2.0 5 votes vote down vote up
def hello():
    """ called by client when signalling itself"""
    # Add bot to network if necessary
    clientId = request.form['id']
    ip = request.remote_addr
    logging.info("   [-] Hello from %s. - IP: %s" % (clientId, ip))
    return make_response("OK") 
Example #24
Source File: test_app.py    From airflow with Apache License 2.0 5 votes vote down vote up
def test_should_respect_base_url_and_proxy_when_proxy_fix_and_base_url_is_set_up(self):
        app = application.cached_app(testing=True)
        app.url_map.add(Rule("/debug", endpoint="debug"))

        def debug_view():
            from flask import request

            # Should respect HTTP_X_FORWARDED_FOR
            self.assertEqual(request.remote_addr, '192.168.0.1')
            # Should respect HTTP_X_FORWARDED_PROTO, HTTP_X_FORWARDED_HOST, HTTP_X_FORWARDED_PORT,
            # HTTP_X_FORWARDED_PREFIX and use base_url
            self.assertEqual(request.url, "https://valid:445/proxy-prefix/internal-client/debug")

            return Response("success")

        app.view_functions['debug'] = debug_view

        new_environ = {
            "PATH_INFO": "/internal-client/debug",
            "REMOTE_ADDR": "192.168.0.2",
            "HTTP_HOST": "invalid:9000",
            "HTTP_X_FORWARDED_FOR": "192.168.0.1",
            "HTTP_X_FORWARDED_PROTO": "https",
            "HTTP_X_FORWARDED_HOST": "valid",
            "HTTP_X_FORWARDED_PORT": "445",
            "HTTP_X_FORWARDED_PREFIX": "/proxy-prefix",
        }
        environ = create_environ(environ_overrides=new_environ)

        response = Response.from_app(app, environ)

        self.assertEqual(b"success", response.get_data())
        self.assertEqual(response.status_code, 200) 
Example #25
Source File: server.py    From minimal-docker-python-setup with MIT License 5 votes vote down vote up
def index():
    addr = request.remote_addr
    redis_store.incr(addr)
    visits = redis_store.get(addr)

    return jsonify({
        'ip': addr,
        'visits': visits,
    }) 
Example #26
Source File: count.py    From maple-blog with GNU General Public License v3.0 5 votes vote down vote up
def set(cls, key, user_key=lambda: 'user:%s', timeout=300):
        if callable(user_key):
            user_key = user_key()
        if '%s' in user_key:
            user_key = user_key % request.remote_addr
        user_key = '%s:%s' % (user_key, key)
        if not redis.exists(user_key):
            redis.set(user_key, 1)
            redis.expire(user_key, timeout)
            redis.zincrby('count:article:visited', key, 1) 
Example #27
Source File: validators.py    From jbox with MIT License 5 votes vote down vote up
def _validate_recaptcha(self, response, remote_addr):
        """Performs the actual validation."""
        try:
            private_key = current_app.config['RECAPTCHA_PRIVATE_KEY']
        except KeyError:
            raise RuntimeError("No RECAPTCHA_PRIVATE_KEY config set")

        data = url_encode({
            'secret':     private_key,
            'remoteip':   remote_addr,
            'response':   response
        })

        http_response = http.urlopen(RECAPTCHA_VERIFY_SERVER, to_bytes(data))

        if http_response.code != 200:
            return False

        json_resp = json.loads(to_unicode(http_response.read()))

        if json_resp["success"]:
            return True

        for error in json_resp.get("error-codes", []):
            if error in RECAPTCHA_ERROR_CODES:
                raise ValidationError(RECAPTCHA_ERROR_CODES[error])

        return False 
Example #28
Source File: response.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def forbidden(message="Forbidden."):
    log.debug("Response 403: %s", message)
    log.info("Forbade %s %s %s: %s", request.remote_addr, request.method, request.base_url, message)
    return Response(message + "\n", status=403, mimetype="text/plain") 
Example #29
Source File: response.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def not_allowed():
    log.debug("Response 405: %s not allowed.", request.method)
    log.info("Disallowed %s %s %s", request.remote_addr, request.method, request.base_url)
    return Response("%s not allowed on this resource\n" % (request.method),
                    status=405, mimetype="text/plain") 
Example #30
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