本文整理匯總了Python中flask.request.content_type方法的典型用法代碼示例。如果您正苦於以下問題:Python request.content_type方法的具體用法?Python request.content_type怎麽用?Python request.content_type使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.request
的用法示例。
在下文中一共展示了request.content_type方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _decode_jwt_from_json
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def _decode_jwt_from_json(request_type):
if request.content_type != 'application/json':
raise NoAuthorizationError('Invalid content-type. Must be application/json.')
if request_type == 'access':
token_key = config.json_key
else:
token_key = config.refresh_json_key
try:
encoded_token = request.json.get(token_key, None)
if not encoded_token:
raise BadRequest()
except BadRequest:
raise NoAuthorizationError('Missing "{}" key in json data.'.format(token_key))
return encoded_token, None
示例2: log_request
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [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
示例3: feedback_view_func
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def feedback_view_func(bento_service):
"""
User send feedback along with the request Id. It will be stored and
ready for further process.
"""
if request.content_type != "application/json":
return Response(
response="Incorrect content format, require JSON", status=400
)
data = json.loads(request.get_data().decode("utf-8"))
if "request_id" not in data.keys():
return Response(response="Missing request id", status=400)
if len(data.keys()) <= 1:
return Response(response="Missing feedback data", status=400)
data["service_name"] = bento_service.name
data["service_version"] = bento_service.version
feedback_logger.info(data)
return Response(response="success", status=200)
示例4: getPostData
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def getPostData():
#print(request.content_type)
data = {}
if (request.content_type.startswith('application/json')):
data = request.get_data()
return json.loads(data.decode("utf-8"))
elif(request.content_type.startswith("application/x-www-form-urlencoded")):
#print(1)
#print(urllib.parse.parse_qs(request.get_data().decode("utf-8")))
return parse_qs_plus(urllib.parse.parse_qs(request.get_data().decode("utf-8")))
else:
for key, value in request.form.items():
if key.endswith('[]'):
data[key[:-2]] = request.form.getlist(key)
else:
data[key] = value
return data
示例5: require_verified_emails
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def require_verified_emails(f):
"""
Decorator to restrict an endpoint to users with confirmed active email addresses
:param f:
:return:
"""
@functools.wraps(f)
def _require_verified_emails(*args, **kwargs):
if get_config("verify_emails"):
if current_user.authed():
if (
current_user.is_admin() is False
and current_user.is_verified() is False
): # User is not confirmed
if request.content_type == "application/json":
abort(403)
else:
return redirect(url_for("auth.confirm"))
return f(*args, **kwargs)
return _require_verified_emails
示例6: authed_only
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def authed_only(f):
"""
Decorator that requires the user to be authenticated
:param f:
:return:
"""
@functools.wraps(f)
def authed_only_wrapper(*args, **kwargs):
if authed():
return f(*args, **kwargs)
else:
if (
request.content_type == "application/json"
or request.accept_mimetypes.best == "text/event-stream"
):
abort(403)
else:
return redirect(url_for("auth.login", next=request.full_path))
return authed_only_wrapper
示例7: admins_only
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def admins_only(f):
"""
Decorator that requires the user to be authenticated and an admin
:param f:
:return:
"""
@functools.wraps(f)
def admins_only_wrapper(*args, **kwargs):
if is_admin():
return f(*args, **kwargs)
else:
if request.content_type == "application/json":
abort(403)
else:
return redirect(url_for("auth.login", next=request.full_path))
return admins_only_wrapper
示例8: check_account_visibility
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def check_account_visibility(f):
@functools.wraps(f)
def _check_account_visibility(*args, **kwargs):
v = get_config(ConfigTypes.ACCOUNT_VISIBILITY)
if v == AccountVisibilityTypes.PUBLIC:
return f(*args, **kwargs)
elif v == AccountVisibilityTypes.PRIVATE:
if authed():
return f(*args, **kwargs)
else:
if request.content_type == "application/json":
abort(403)
else:
return redirect(url_for("auth.login", next=request.full_path))
elif v == AccountVisibilityTypes.ADMINS:
if is_admin():
return f(*args, **kwargs)
else:
abort(404)
return _check_account_visibility
示例9: get_current_user
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def get_current_user():
if authed():
user = Users.query.filter_by(id=session["id"]).first()
# Check if the session is still valid
session_hash = session.get("hash")
if session_hash:
if session_hash != hmac(user.password):
logout_user()
if request.content_type == "application/json":
error = 401
else:
error = redirect(url_for("auth.login", next=request.full_path))
abort(error)
return user
else:
return None
示例10: create_binary
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def create_binary():
print(request.args)
print(request.data)
print(request.files)
print(request.headers)
if request.content_type == "application/octet-stream":
data = request.get_data()
print(len(data))
print(data[:20])
return jsonify({
'msg': 'success',
'request.content_type': request.content_type,
'request.content_length': request.content_length,
'len': len(data),
'first': data[:20].decode('unicode_escape'), # convert bytes to string which can be send in JSON
})
else:
return jsonify({
'msg': '415 Unsupported Media Type ;)',
'request.content_type': request.content_type,
})
示例11: get_json_and_verify_params
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def get_json_and_verify_params(params=None):
params = params or []
if request.content_type != 'application/json':
raise manager_exceptions.UnsupportedContentTypeError(
'Content type must be application/json')
request_dict = request.json
is_params_dict = isinstance(params, dict)
def is_optional(param_name):
return is_params_dict and params[param_name].get('optional', False)
def check_type(param_name):
return is_params_dict and params[param_name].get('type', None)
for param in params:
if param not in request_dict:
if is_optional(param):
continue
raise manager_exceptions.BadParametersError(
'Missing {0} in json request body'.format(param))
param_type = check_type(param)
if param_type and not isinstance(request_dict[param], param_type):
raise manager_exceptions.BadParametersError(
'{0} parameter is expected to be of type {1} but is of type '
'{2}'.format(param,
param_type.__name__,
type(request_dict[param]).__name__))
return request_dict
示例12: api_call
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def api_call():
data = {}
try:
if request.content_type == 'application/json':
data = request.get_json(silent=True)
elif request.method == 'POST':
data = request.form.to_dict()
else:
data = request.args.to_dict()
# verify cmd was supplied
if 'cmd' not in data:
logger.error("Unknown %s API call from %r", request.method, request.remote_addr)
return jsonify({'error': 'No cmd parameter was supplied'})
else:
logger.info("Client %s API call from %r, type: %s", request.method, request.remote_addr, data['cmd'])
# process cmds
cmd = data['cmd'].lower()
if cmd == 'queue_count':
# queue count
if not conf.configs['SERVER_USE_SQLITE']:
# return error if SQLITE db is not enabled
return jsonify({'error': 'SERVER_USE_SQLITE must be enabled'})
return jsonify({'queue_count': db.get_queue_count()})
else:
# unknown cmd
return jsonify({'error': 'Unknown cmd: %s' % cmd})
except Exception:
logger.exception("Exception parsing %s API call from %r: ", request.method, request.remote_addr)
return jsonify({'error': 'Unexpected error occurred, check logs...'})
示例13: create_executor_function
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def create_executor_function(interface: Interface, method: str):
"""
Creates a view function for specific interface method
:param interface: :class:`.Interface` instance
:param method: method name
:return: callable view function
"""
from flask import g, jsonify, request, send_file
def ef():
try:
if request.content_type == 'application/json':
request_data = BaseHTTPServer._deserialize_json(interface, method, request.json)
else:
request_data = dict(itertools.chain(request.form.items(), request.files.items()))
result = BaseHTTPServer._execute_method(interface, method, request_data, g.ebonite_id)
if isinstance(result, bytes):
return send_file(BytesIO(result), mimetype='image/png')
return jsonify(result)
except MalformedHTTPRequestException as e:
return jsonify(e.response_body()), e.code()
ef.__name__ = method
return ef
示例14: _request_to_json
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def _request_to_json(req):
"""
Return request data for log prediction
"""
if req.content_type == "application/json":
return req.get_json()
return {}
示例15: log_image
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import content_type [as 別名]
def log_image(req, request_id):
if not config('logging').getboolean('log_request_image_files'):
return []
img_prefix = 'image/'
log_folder = config('logging').get('base_log_dir')
all_paths = []
if req.content_type and req.content_type.startswith(img_prefix):
filename = '{timestamp}-{request_id}.{ext}'.format(
timestamp=int(time.time()),
request_id=request_id,
ext=req.content_type[len(img_prefix) :],
)
path = os.path.join(log_folder, filename)
all_paths.append(path)
with open(path, 'wb') as f:
f.write(req.get_data())
for name in req.files:
file = req.files[name]
if file and file.filename:
orig_filename = secure_filename(file.filename)
filename = '{timestamp}-{request_id}-{orig_filename}'.format(
timestamp=int(time.time()),
request_id=request_id,
orig_filename=orig_filename,
)
path = os.path.join(log_folder, filename)
all_paths.append(path)
file.save(path)
file.stream.seek(0)
return all_paths