本文整理匯總了Python中flask.request.headers方法的典型用法代碼示例。如果您正苦於以下問題:Python request.headers方法的具體用法?Python request.headers怎麽用?Python request.headers使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.request
的用法示例。
在下文中一共展示了request.headers方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: request_remote_site
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def request_remote_site():
"""
請求遠程服務器(high-level), 並在返回404/500時進行 domain_guess 嘗試
"""
# 請求被鏡像的網站
# 注意: 在zmirror內部不會處理重定向, 重定向響應會原樣返回給瀏覽器
parse.remote_response = send_request(
parse.remote_url,
method=request.method,
headers=parse.client_header,
data=parse.request_data_encoded,
)
if parse.remote_response.url != parse.remote_url:
warnprint("requests's remote url", parse.remote_response.url,
'does no equals our rewrited url', parse.remote_url)
if 400 <= parse.remote_response.status_code <= 599:
# 猜測url所對應的正確域名
dbgprint("Domain guessing for", request.url)
result = guess_correct_domain()
if result is not None:
parse.remote_response = result
示例2: zmirror_enter
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def zmirror_enter(input_path='/'):
"""入口函數的殼, 隻是包了一層異常處理, 實際是 main_function() """
try:
resp = main_function(input_path=input_path)
# 加入額外的響應頭
for name, value in parse.extra_resp_headers.items():
resp.headers.set(name, value)
# 加入額外的cookies
for name, cookie_string in parse.extra_cookies.items():
resp.headers.add("Set-Cookie", cookie_string)
except: # coverage: exclude
return generate_error_page(is_traceback=True)
else:
return resp
# noinspection PyUnusedLocal
示例3: query
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
"""Execute SPARQL query for a specific grlc-generated API endpoint"""
glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
glogger.debug("Request accept header: " + request.headers["Accept"])
requestArgs = request.args
acceptHeader = request.headers['Accept']
requestUrl = request.url
formData = request.form
query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
sha=sha, content=content, requestArgs=requestArgs,
acceptHeader=acceptHeader,
requestUrl=requestUrl, formData=formData)
if isinstance(query_response, list):
query_response = jsonify(query_response)
return make_response(query_response, status, headers)
### Server routes ###
示例4: messages
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def messages():
# Main bot message handler.
if "application/json" in request.headers["Content-Type"]:
body = request.json
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)
async def aux_func(turn_context):
await BOT.on_turn(turn_context)
try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, aux_func)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
示例5: messages
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def messages():
"""Main bot message handler."""
if "application/json" in request.headers["Content-Type"]:
body = request.json
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)
async def aux_func(turn_context):
await BOT.on_turn(turn_context)
try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, aux_func)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
示例6: messages
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def messages():
# Main bot message handler.
if "application/json" in request.headers["Content-Type"]:
body = request.json
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)
try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
示例7: do_POST
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [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, {})
示例8: user_info
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def user_info():
"""
Call by client to get user information
Usually bearer token is used.
"""
if "AUTHORIZATION" in request.headers:
access_token = request.headers["AUTHORIZATION"].replace("Bearer ", "")
else:
access_token = request.args.get("access_token")
oauth_token: OauthToken = OauthToken.get_by(access_token=access_token)
if not oauth_token:
return jsonify(error="Invalid access token"), 400
elif oauth_token.is_expired():
LOG.d("delete oauth token %s", oauth_token)
OauthToken.delete(oauth_token.id)
db.session.commit()
return jsonify(error="Expired access token"), 400
client_user = ClientUser.get_or_create(
client_id=oauth_token.client_id, user_id=oauth_token.user_id
)
return jsonify(client_user.get_user_info())
示例9: score
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def score():
if request.headers['Content-Type'] != 'application/json':
resp = Response('Unssuported content type, expected application/json', status=500);
return resp
if (not request.json.has_key('text')):
resp = Response('Bad request: missing "text" field in JSON body', status=500);
return resp
if (not request.json.has_key('entities')):
resp = Response('Bad request: missing "entities" field in JSON body', status=500);
return resp
text = request.json['text']
entities = request.json['entities']
try:
scorerResult = scorer.evaluate_score(text, entities)
resp = jsonify(scorer_result_to_response_format(scorerResult))
resp.status_code = 200
return resp
except Exception as e:
resp = Response("Internal Server Error: %s"%e, status = 500)
return resp
示例10: update_model
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def update_model():
if request.headers['Content-Type'] != 'application/json':
resp = Response('Unssuported content type, expected application/json', status=500);
return resp
if (not request.json.has_key('path')):
resp = Response('Bad request: missing "path" field in JSON body', status=500);
return resp
path = request.json['path']
try:
scorer.load_model_from_url(path)
resp = Response("", status=200);
return resp
except Exception as e:
resp = Response("Internal Server Error: %s"%e, status = 500)
return resp
示例11: slack_app
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def slack_app():
if not signature_verifier.is_valid_request(request.get_data(), request.headers):
return make_response("invalid request", 403)
if "command" in request.form \
and request.form["command"] == "/view":
trigger_id = request.form["trigger_id"]
return open_modal(trigger_id)
elif "payload" in request.form:
payload = json.loads(request.form["payload"])
if payload["type"] == "view_submission" \
and payload["view"]["callback_id"] == "modal-id":
submitted_data = payload["view"]["state"]["values"]
print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
return make_response("", 200)
if payload["type"] == "shortcut" \
and payload["callback_id"] == "view-test":
return open_modal(payload["trigger_id"])
return make_response("", 404)
示例12: redirect_file
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def redirect_file(user,fileid):
filename=GetName(fileid)
downloadUrl,play_url=GetDownloadUrl(fileid,user)
req = browser.get(play_url, stream = True)
headers = dict([(name, value) for (name, value) in req.raw.headers.items()])
cache_root=os.path.join(GetConfig('config_dir'),'cache')
if not os.path.exists(cache_root):
os.mkdir(cache_root)
filepath=os.path.join(cache_root,filename)
if not os.path.exists(filepath):
with open(filepath,'wb') as f:
for chunk in req.iter_content(1024):
if chunk:
f.write(chunk)
f.flush()
resp=send_file(filepath,conditional=True)
return resp
示例13: login_required
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def login_required(f):
'''
This decorator checks the header to ensure a valid token is set
'''
@wraps(f)
def func(*args, **kwargs):
try:
if 'authorization' not in request.headers:
abort(404, message="You need to be logged in to access this resource")
token = request.headers.get('authorization')
payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
user_id = payload['id']
g.user = User.find(user_id)
if g.user is None:
abort(404, message="The user id is invalid")
return f(*args, **kwargs)
except JWTError as e:
abort(400, message="There was a problem while trying to parse your token -> {}".format(e.message))
return func
示例14: verify_slack_requests
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def verify_slack_requests(f=None):
"""
Verify the request signature of the request sent from Slack
Generate a new hash using the app's signing secret and request data
"""
@wraps(f)
def wrapper(*args, **kwargs):
signature = request.headers['X-Slack-Signature']
timestamp = request.headers['X-Slack-Request-Timestamp']
data = request.data.decode('utf-8')
# data = urllib.parse.urlencode(urllib.parse.unquote(raw_string))
format_req = str.encode(f"v0:{timestamp}:{data}")
encoded_secret = str.encode(config.SLACK_SECRET)
request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
calculated_signature = f"v0={request_hash}"
if hmac.compare_digest(calculated_signature, signature):
return f(*args, **kwargs)
return make_response(jsonify({'message': 'Invalid auth'})), 401
return wrapper
示例15: after_request_stuff
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import headers [as 別名]
def after_request_stuff(resp):
#support CORS
resp.headers['Access-Control-Allow-Origin'] = "*"
resp.headers['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS, PUT, DELETE, PATCH"
resp.headers['Access-Control-Allow-Headers'] = "origin, content-type, accept, x-requested-with"
# remove session
db.session.remove()
# without this jason's heroku local buffers forever
sys.stdout.flush()
# log request for analytics
log_request(resp)
return resp