本文整理汇总了Python中flask.request.headers方法的典型用法代码示例。如果您正苦于以下问题:Python request.headers方法的具体用法?Python request.headers怎么用?Python request.headers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块flask.request的用法示例。
在下文中一共展示了request.headers方法的25个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: request_remote_site
点赞 6
# 需要导入模块: 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
开发者ID:aploium,项目名称:zmirror,代码行数:26,
示例2: zmirror_enter
点赞 6
# 需要导入模块: 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
开发者ID:aploium,项目名称:zmirror,代码行数:22,
示例3: query
点赞 6
# 需要导入模块: 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 ###
开发者ID:CLARIAH,项目名称:grlc,代码行数:22,
示例4: messages
点赞 6
# 需要导入模块: 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
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:25,
示例5: messages
点赞 6
# 需要导入模块: 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
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:26,
示例6: messages
点赞 6
# 需要导入模块: 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
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:22,
示例7: do_POST
点赞 6
# 需要导入模块: 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, {})
开发者ID:matrix-org,项目名称:Matrix-NEB,代码行数:24,
示例8: user_info
点赞 6
# 需要导入模块: 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())
开发者ID:simple-login,项目名称:app,代码行数:26,
示例9: score
点赞 6
# 需要导入模块: 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
开发者ID:CatalystCode,项目名称:corpus-to-graph-ml,代码行数:23,
示例10: update_model
点赞 6
# 需要导入模块: 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
开发者ID:CatalystCode,项目名称:corpus-to-graph-ml,代码行数:18,
示例11: slack_app
点赞 6
# 需要导入模块: 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)
开发者ID:slackapi,项目名称:python-slackclient,代码行数:23,
示例12: redirect_file
点赞 6
# 需要导入模块: 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
开发者ID:abbeyokgo,项目名称:PyOne,代码行数:19,
示例13: login_required
点赞 6
# 需要导入模块: 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
开发者ID:afropolymath,项目名称:papers,代码行数:21,
示例14: verify_slack_requests
点赞 6
# 需要导入模块: 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
开发者ID:teamsempo,项目名称:SempoBlockchain,代码行数:23,
示例15: after_request_stuff
点赞 6
# 需要导入模块: 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
开发者ID:ourresearch,项目名称:oadoi,代码行数:19,
示例16: recognize_batch
点赞 6
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def recognize_batch():
data = {
"model": request.args.get("lang", "en-GB"),
"lm": request.args.get("lm", "default"),
"wav": request.data
}
def generate(response):
for result in response:
yield json.dumps(result)
try:
worker = create_frontend_worker(os.environ['MASTER_ADDR'])
response = worker.recognize_batch(data, request.headers)
worker.close()
return Response(stream_with_context(generate(response)))
except MissingHeaderError:
return jsonify({"status": "error", "message": "Missing header Content-Type"}), 400
except NoWorkerAvailableError:
return jsonify({"status": "error", "message": "No worker available"}), 503
finally:
worker.close()
开发者ID:UFAL-DSG,项目名称:cloud-asr,代码行数:25,
示例17: taxii_poll_service
点赞 6
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def taxii_poll_service():
taxiict = request.headers['X-TAXII-Content-Type']
if taxiict == 'urn:taxii.mitre.org:message:xml:1.1':
tm = libtaxii.messages_11.get_message_from_xml(request.data)
if tm.message_type != libtaxii.constants.MSG_POLL_REQUEST:
return 'Invalid message', 400
cname = tm.collection_name
excbegtime = tm.exclusive_begin_timestamp_label
incendtime = tm.inclusive_end_timestamp_label
if not current_user.check_feed(cname):
return 'Unauthorized', 401
return data_feed_11(tm.message_id, cname, excbegtime, incendtime)
elif taxiict == 'urn:taxii.mitre.org:message:xml:1.0':
# old TAXII 1.0 not supported yet
return 'Invalid message', 400
else:
return 'Invalid message', 400
开发者ID:PaloAltoNetworks,项目名称:minemeld-core,代码行数:24,
示例18: generate_304_response
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def generate_304_response(_content_type=None):
""":rtype Response"""
r = Response(content_type=_content_type, status=304)
r.headers.add('X-Cache', 'FileHit-304')
return r
开发者ID:aploium,项目名称:zmirror,代码行数:7,
示例19: put_response_to_local_cache
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def put_response_to_local_cache(url, _our_resp, without_content=False):
"""
put our response object(headers included) to local cache
:param without_content: for stream mode use
:param url: client request url
:param _our_resp: our response(flask response object) to client, would be storge
:type url: str
:type _our_resp: Response
:type without_content: bool
"""
# Only cache GET method, and only when remote returns 200(OK) status
if parse.method != 'GET' or _our_resp.status_code != 200:
return
dbgprint('PuttingCache:', url, "without_content:", without_content)
if without_content:
our_resp = copy.copy(_our_resp)
our_resp.response = None # delete iterator
obj_size = 0
else:
our_resp = _our_resp
obj_size = len(parse.remote_response.content)
# requests' header are CaseInsensitive
last_modified = parse.remote_response.headers.get('Last-Modified', None)
cache.put_obj(
url,
our_resp,
expires=get_expire_from_mime(parse.mime),
obj_size=obj_size,
last_modified=last_modified,
info_dict={'without_content': without_content,
'last_modified': last_modified,
},
)
开发者ID:aploium,项目名称:zmirror,代码行数:39,
示例20: response_cookies_deep_copy
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def response_cookies_deep_copy():
"""
It's a BAD hack to get RAW cookies headers, but so far, we don't have better way.
We'd go DEEP inside the urllib's private method to get raw headers
raw_headers example:
[('Cache-Control', 'private'),
('Content-Length', '48234'),
('Content-Type', 'text/html; Charset=utf-8'),
('Server', 'Microsoft-IIS/8.5'),
('Set-Cookie','BoardList=BoardID=Show; expires=Mon, 02-May-2016 16:00:00 GMT; path=/'),
('Set-Cookie','aspsky=abcefgh; expires=Sun, 24-Apr-2016 16:00:00 GMT; path=/; HttpOnly'),
('Set-Cookie', 'ASPSESSIONIDSCSSDSSQ=OGKMLAHDHBFDJCDMGBOAGOMJ; path=/'),
('X-Powered-By', 'ASP.NET'),
('Date', 'Tue, 26 Apr 2016 12:32:40 GMT')]
"""
raw_headers = parse.remote_response.raw._original_response.headers._headers
header_cookies_string_list = []
for name, value in raw_headers:
if name.lower() == 'set-cookie':
if my_host_scheme == 'http://':
value = value.replace('Secure;', '')
value = value.replace(';Secure', ';')
value = value.replace('; Secure', ';')
if 'httponly' in value.lower():
if enable_aggressive_cookies_path_rewrite:
# 暴力cookie path重写, 把所有path都重写为 /
value = regex_cookie_path_rewriter.sub('path=/;', value)
elif enable_aggressive_cookies_path_rewrite is not None:
# 重写HttpOnly Cookies的path到当前url下
# eg(/extdomains/a.foobar.com): path=/verify; -> path=/extdomains/a.foobar.com/verify
if parse.remote_domain not in domain_alias_to_target_set: # do not rewrite main domains
value = regex_cookie_path_rewriter.sub(
'\g=/extdomains/' + parse.remote_domain + '\g', value)
header_cookies_string_list.append(value)
return header_cookies_string_list
开发者ID:aploium,项目名称:zmirror,代码行数:41,
示例21: crossdomain_xml
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def crossdomain_xml():
return Response("""<?xml version="1.0"?>
""", content_type='text/x-cross-domain-policy')
开发者ID:aploium,项目名称:zmirror,代码行数:10,
示例22: swagger_spec
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def swagger_spec(user, repo, subdir=None, spec_url=None, sha=None, content=None):
""" Generate swagger specification """
glogger.info("-----> Generating swagger spec for /{}/{}, subdir {}, params {}, on commit {}".format(user, repo, subdir, spec_url, sha))
swag = utils.build_swagger_spec(user, repo, subdir, spec_url, sha, static.SERVER_NAME)
resp_spec = make_response(jsonify(swag))
resp_spec.headers['Content-Type'] = 'application/json'
resp_spec.headers['Cache-Control'] = static.CACHE_CONTROL_POLICY # Caching JSON specs for 15 minutes
glogger.info("-----> API spec generation for /{}/{}, subdir {}, params {}, on commit {} complete".format(user, repo, subdir, spec_url, sha))
return resp_spec
开发者ID:CLARIAH,项目名称:grlc,代码行数:15,
示例23: messages
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def messages(self) -> Response:
"""Main bot message handler that listens for incoming requests."""
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 self.bot.on_turn(turn_context)
try:
task = self.loop.create_task(
self.adapter.process_activity(activity, auth_header, aux_func)
)
self.loop.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:28,
示例24: answer
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def answer(topic = None):
"""
Main rendering function, it processes incoming weather queries.
Depending on user agent it returns output in HTML or ANSI format.
Incoming data:
request.args
request.headers
request.remote_addr
request.referrer
request.query_string
"""
user_agent = request.headers.get('User-Agent', '').lower()
html_needed = is_html_needed(user_agent)
options = parse_query(request.args)
hostname = request.headers['Host']
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
if ip.startswith('::ffff:'):
ip = ip[7:]
else:
ip = request.remote_addr
if topic is None:
topic = ":firstpage"
answer = cmd_wrapper(topic, hostname=hostname, request_options=options, html=is_html_needed(user_agent))
if ip not in SKIP_LOGGING_FOR_THIS_IPS:
log_query(ip, hostname, topic, user_agent)
return answer
开发者ID:chubin,项目名称:rate.sx,代码行数:35,
示例25: request_validation
点赞 5
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import headers [as 别名]
def request_validation(self, request, query, json, headers, cookies):
req_query = request.args or {}
req_json = request.get_json() or {}
req_headers = request.headers or {}
req_cookies = request.cookies or {}
request.context = Context(
query.parse_obj(req_query) if query else None,
json.parse_obj(req_json) if json else None,
headers.parse_obj(req_headers) if headers else None,
cookies.parse_obj(req_cookies) if cookies else None,
)
开发者ID:0b01001001,项目名称:spectree,代码行数:13,
注:本文中的flask.request.headers方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。