本文整理汇总了Python中flask.request.method方法的典型用法代码示例。如果您正苦于以下问题:Python request.method方法的具体用法?Python request.method怎么用?Python request.method使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.request
的用法示例。
在下文中一共展示了request.method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wechat
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def wechat():
signature = request.args.get("msg_signature", "")
timestamp = request.args.get("timestamp", "")
nonce = request.args.get("nonce", "")
crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId)
if request.method == "GET":
echo_str = request.args.get("echostr", "")
try:
echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str)
except InvalidSignatureException:
abort(403)
return echo_str
else:
try:
msg = crypto.decrypt_message(request.data, signature, timestamp, nonce)
except (InvalidSignatureException, InvalidCorpIdException):
abort(403)
msg = parse_message(msg)
if msg.type == "text":
reply = create_reply(msg.content, msg).render()
else:
reply = create_reply("Can not handle this for now", msg).render()
res = crypto.encrypt_message(reply, nonce, timestamp)
return res
示例2: cron_update_remote_manifest
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def cron_update_remote_manifest():
"""更新数据最后更新时间"""
from everyclass.rpc.http import HttpRpc
# 获取安卓客户端下载链接
android_manifest = HttpRpc.call(method="GET",
url="https://everyclass.cdn.admirable.pro/android/manifest.json",
retry=True)
android_ver = android_manifest['latestVersions']['mainstream']['versionCode']
__app.config['ANDROID_CLIENT_URL'] = android_manifest['releases'][android_ver]['url']
# 更新数据最后更新时间
_api_server_status = HttpRpc.call(method="GET",
url=__app.config['ENTITY_BASE_URL'] + '/info/service',
retry=True,
headers={'X-Auth-Token': __app.config['ENTITY_TOKEN']})
__app.config['DATA_LAST_UPDATE_TIME'] = _api_server_status["data"]["data_time"]
示例3: update_content_in_local_cache
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def update_content_in_local_cache(url, content, method='GET'):
"""更新 local_cache 中缓存的资源, 追加content
在stream模式中使用"""
if local_cache_enable and method == 'GET' and cache.is_cached(url):
info_dict = cache.get_info(url)
resp = cache.get_obj(url)
resp.set_data(content)
# 当存储的资源没有完整的content时, without_content 被设置为true
# 此时该缓存不会生效, 只有当content被添加后, 缓存才会实际生效
# 在stream模式中, 因为是先接收http头, 然后再接收内容, 所以会出现只有头而没有内容的情况
# 此时程序会先将只有头部的响应添加到本地缓存, 在内容实际接收完成后再追加内容
info_dict['without_content'] = False
if verbose_level >= 4: dbgprint('LocalCache_UpdateCache', url, content[:30], len(content))
cache.put_obj(
url,
resp,
obj_size=len(content),
expires=get_expire_from_mime(parse.mime),
last_modified=info_dict.get('last_modified'),
info_dict=info_dict,
)
示例4: try_get_cached_response
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def try_get_cached_response(url, client_header=None):
"""
尝试从本地缓存中取出响应
:param url: real url with query string
:type client_header: dict
:rtype: Union[Response, None]
"""
# Only use cache when client use GET
if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
if client_header is not None and 'if-modified-since' in client_header and \
cache.is_unchanged(url, client_header.get('if-modified-since', None)):
dbgprint('FileCacheHit-304', url)
return generate_304_response()
else:
cached_info = cache.get_info(url)
if cached_info.get('without_content', True):
# 关于 without_content 的解释, 请看update_content_in_local_cache()函数
return None
# dbgprint('FileCacheHit-200')
resp = cache.get_obj(url)
assert isinstance(resp, Response)
parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
return resp
else:
return None
示例5: request_remote_site
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [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
示例6: check_token
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def check_token(self, token, allowed_roles, resource, method):
"""
This function is called when a token is sent throught the access_token
parameter or the Authorization header as specified in the oAuth 2 specification.
The provided token is validated with the JWT_SECRET defined in the Eve configuration.
The token issuer (iss claim) must be the one specified by JWT_ISSUER and the audience
(aud claim) must be one of the value(s) defined by the either the "audiences" resource
parameter or the global JWT_AUDIENCES configuration.
If JWT_ROLES_CLAIM is defined and a claim by that name is present in the token, roles
are checked using this claim.
If a JWT_SCOPE_CLAIM is defined and a claim by that name is present in the token, the
claim value is check, and if "viewer" is present, only GET and HEAD methods will be
allowed. The scope name is then added to the list of roles with the scope: prefix.
If the validation succeed, the claims are stored and accessible thru the
get_authen_claims() method.
"""
resource_conf = config.DOMAIN[resource]
audiences = resource_conf.get('audiences', config.JWT_AUDIENCES)
return self._perform_verification(token, audiences, allowed_roles)
示例7: requires_token
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def requires_token(self, audiences=None, allowed_roles=None):
"""
Decorator for functions that will be protected with token authentication.
Token must be provvided either through access_token parameter or Authorization
header.
See check_token() method for further details.
"""
def requires_token_wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
try:
token = request.args['access_token']
except KeyError:
token = request.headers.get('Authorization', '').partition(' ')[2]
if not self._perform_verification(token, audiences, allowed_roles):
abort(401)
return f(*args, **kwargs)
return decorated
return requires_token_wrapper
示例8: _perform_verification
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def _perform_verification(self, token, audiences, allowed_roles):
verified, payload, account_id, roles = verify_token(
token, self.secret, self.issuer, request.method, audiences, allowed_roles)
if not verified:
return False
# Save roles for later access
self.set_authen_roles(roles)
# Save claims for later access
self.set_authen_claims(payload)
# Limit access to the authen account
self.set_request_auth_value(account_id)
return True
示例9: v1CheckPassword
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def v1CheckPassword():
username = ''
password = ''
if request.method == 'GET':
username = request.args.get('u','')
password = request.args.get('p','')
reserve = True
elif request.method == 'POST':
username = request.form.get('u','')
password = request.form.get('p','')
reserve = False
(isGood,code,reason) = pwn.verifyPasswordGood(username,
password,
reserve=reserve,
always_true=cfg.yesman)
logStore.code = code
logStore.isValid = isGood
logStore.user = username
message = u','.join(map(str,[isGood,code,reason]))
return message
示例10: __init__
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def __init__(cls, name, bases, d):
# Prepare
methods = set(cls.methods or [])
methods_map = defaultdict(dict)
# Methods
for view_name, func in inspect.getmembers(cls):
# Collect methods decorated with methodview()
info = _MethodViewInfo.get_info(func)
if info is not None:
# @methodview-decorated view
for method in info.methods:
methods_map[method][view_name] = info
methods.add(method)
# Finish
cls.methods = tuple(sorted(methods_map.keys())) # ('GET', ... )
cls.methods_map = dict(methods_map) # { 'GET': {'get': _MethodViewInfo } }
super(MethodViewType, cls).__init__(name, bases, d)
示例11: _match_view
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def _match_view(self, method, route_params):
""" Detect a view matching the query
:param method: HTTP method
:param route_params: Route parameters dict
:return: Method
:rtype: Callable|None
"""
method = method.upper()
route_params = frozenset(k for k, v in route_params.items() if v is not None)
for view_name, info in self.methods_map[method].items():
if info.matches(method, route_params):
return getattr(self, view_name)
else:
return None
示例12: json_classify
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def json_classify():
if request.method == 'POST':
img = Image.open(request.files['file'])
#Format image to Numpy CHW and run inference, get the results of the single output node
results = engine.infer(image_to_np_CHW(img))[0]
#Retrive the results created by the post processor callback
top_class_label, top5 = results[0], results[1]
#Format data for JSON
top5_str = []
for t in top5:
top5_str.append((t[0], str(t[1])))
classification_data = {"top_class": top_class_label, "top5": top5_str}
return jsonify (
data = classification_data
)
else:
return jsonify (
error = "Invalid Request Type"
)
示例13: json_classify
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def json_classify():
if request.method == 'POST':
img = Image.open(request.files['file'])
#Format image to Numpy CHW and run inference, get the results of the single output node
results = engine.infer(image_to_np_CHW(img))[0]
#Retrive the results created by the post processor callback
top_class_label, top5 = results[0], results[1]
#Format data for JSON
top5_str = []
for t in top5:
top5_str.append((t[0], str(t[1])))
classification_data = {"top_class": top_class_label, "top5": top5_str}
return jsonify (
data = classification_data
)
else:
return jsonify (
error = "Invalid Request Type"
)
示例14: cryptolist
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def cryptolist():
getlist = listofcrypto.query.all()
if request.method == "GET":
check = request.args.get("json")
q = request.args.get("term")
if check == "true":
jsonlist = []
for item in getlist:
if (q.upper() in item.symbol) or (q in item.name):
tmp = {}
tmp["name"] = item.name
tmp["symbol"] = item.symbol
jsonlist.append(tmp)
return jsonify(jsonlist)
return render_template(
"cryptolist.html",
title="List of Crypto Currencies", listofcrypto=getlist
)
示例15: aclst
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import method [as 别名]
def aclst():
list = []
if request.method == "GET":
tradeaccounts = Trades.query.filter_by(
user_id=current_user.username).group_by(
Trades.trade_account)
accounts = AccountInfo.query.filter_by(
user_id=current_user.username).group_by(
AccountInfo.account_longname
)
q = request.args.get("term")
for item in tradeaccounts:
if q.upper() in item.trade_account.upper():
list.append(item.trade_account)
for item in accounts:
if q.upper() in item.account_longname.upper():
list.append(item.account_longname)
list = json.dumps(list)
return list