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