本文整理匯總了Python中flask.request.remote_addr方法的典型用法代碼示例。如果您正苦於以下問題:Python request.remote_addr方法的具體用法?Python request.remote_addr怎麽用?Python request.remote_addr使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.request
的用法示例。
在下文中一共展示了request.remote_addr方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: receive_public
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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')
示例2: zmirror_status
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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"
示例3: do_POST
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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, {})
示例4: rate_limit
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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
示例5: mood
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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()
示例6: __call__
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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))
示例7: _validate_captcha
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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
示例8: log_request
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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
示例9: access_write_task
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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)
示例10: log_exception
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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)
示例11: log_request
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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)
示例12: submit_job
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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')
示例13: rate_limit
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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
示例14: _get_client_ipaddr
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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}")
示例15: cut_key_unsafe
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import remote_addr [as 別名]
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