本文整理匯總了Python中flask.request.is_json方法的典型用法代碼示例。如果您正苦於以下問題:Python request.is_json方法的具體用法?Python request.is_json怎麽用?Python request.is_json使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.request
的用法示例。
在下文中一共展示了request.is_json方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: login
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def login():
if not request.is_json:
return jsonify({"msg": "Missing JSON in request"}), 400
username = request.json.get('username', None)
password = request.json.get('password', None)
if not username:
return jsonify({"msg": "Missing username parameter"}), 400
if not password:
return jsonify({"msg": "Missing password parameter"}), 400
if username != 'test' or password != 'test':
return jsonify({"msg": "Bad username or password"}), 401
# Identity can be any data that is json serializable
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
示例2: login
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def login():
if not request.is_json:
return jsonify({"msg": "Missing JSON in request"}), 400
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username:
return jsonify({"msg": "Missing username parameter"}), 400
if not password:
return jsonify({"msg": "Missing password parameter"}), 400
if username != "test" or password != "test":
return jsonify({"msg": "Bad username or password"}), 401
# Identity can be any data that is json serializable
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
示例3: check_for_json
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def check_for_json(self):
"""Check if the Payload is a JSON document
Return: bool:
True in case of success, False otherwise
"""
# First check for the data field and create JSON from it
if hasattr(request, "data") is True:
try:
self.request_data = json_loads(request.data)
except Exception as e:
self.create_error_response(message="No JSON data in request: Exception: %s" % str(e))
return False
if request.is_json is False:
self.create_error_response(message="No JSON data in request")
return False
self.request_data = request.get_json()
return True
示例4: anonymous_user_required
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
"""
Decorator requiring that there is no user currently logged in.
Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
"""
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kwargs):
if current_user.is_authenticated:
if request.is_json:
abort(HTTPStatus.FORBIDDEN)
else:
if msg:
flash(msg, category)
return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
override=redirect_url)
return fn(*args, **kwargs)
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapper(decorator_args[0])
return wrapper
示例5: register
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def register(self):
"""
View function to register user. Supports html and json requests.
"""
form = self._get_form('SECURITY_REGISTER_FORM')
if form.validate_on_submit():
user = self.security_service.user_manager.create(**form.to_dict())
self.security_service.register_user(user)
if request.is_json:
return '', HTTPStatus.NO_CONTENT
return self.redirect('SECURITY_POST_REGISTER_REDIRECT_ENDPOINT')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('register',
register_user_form=form,
**self.security.run_ctx_processor('register'))
示例6: send_confirmation_email
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def send_confirmation_email(self):
"""
View function which sends confirmation token and instructions to a user.
"""
form = self._get_form('SECURITY_SEND_CONFIRMATION_FORM')
if form.validate_on_submit():
self.security_service.send_email_confirmation_instructions(form.user)
self.flash(_('flask_unchained.bundles.security:flash.confirmation_request',
email=form.user.email), category='info')
if request.is_json:
return '', HTTPStatus.NO_CONTENT
return self.redirect('send_confirmation_email')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('send_confirmation_email',
send_confirmation_form=form,
**self.security.run_ctx_processor('send_confirmation_email'))
示例7: change_password
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def change_password(self):
"""
View function for a user to change their password.
Supports html and json requests.
"""
form = self._get_form('SECURITY_CHANGE_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.change_password(
current_user._get_current_object(),
form.new_password.data)
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.password_change'),
category='success')
if request.is_json:
return self.jsonify({'token': current_user.get_auth_token()})
return self.redirect('SECURITY_POST_CHANGE_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('change_password',
change_password_form=form,
**self.security.run_ctx_processor('change_password'))
示例8: json
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def json():
# 요청의 Content-Type이 application/json이고, 직렬화된 JSON 문자열이 들어온다면(RFC 표준에 잘 맞는 JSON request라면)
# request의 json property나 get_json() 메소드를 이용하면 된다
req = request.json
# Flask 0.12.3까지 deprecated되어 있었으나, Flask 1.0에선 다시 deprecated가 제거됨
req = request.get_json()
# Flask 0.10에서 추가된 메소드
# 요청의 Content-Type이 application/json이 아니라면 None이 반환되며
# Content-Type은 application/json으로 설정되었으나 아무 데이터도 전달되지 않으면 status code '400 Bad Request'를 지동으로 리턴한다
# 요청의 타입이 json인지 확인해 주는 메소드도 있다
if not request.is_json:
return 'Please set your content type "application/json"!', 400
print(type(req))
# json 프로퍼티는 요청 데이터에 따라 파이썬 고유의 dict 또는 list 타입으로 처리된다
return str(req['test_key'])
示例9: create
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def create():
"""
POST => /buckets
Recoit les informations pour enregistrer un nouveau bucket
"""
print("Acces a /bucket avec POST")
try:
if request.headers['Content-Type'] != 'application/json':
response = {
"error": 1,
"message": "Content-Type is not application/json"
}
return (response, 400)
elif request.is_json:
return BucketController.create(request)
else:
raise Exception()
except Exception as e:
print("ERROR: Request is not JSON or has missing fields.")
print(e)
response = {
"error": 1,
"message": "Missing fields in JSON"
}
return (response, 404)
示例10: update
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def update(id):
"""
POST => /buckets/id
Met a jours les informations d'un bucket
"""
print("Acces a /bucket/id avec POST")
try:
if request.headers['Content-Type'] != 'application/json':
response = {
"error": 1,
"message": "Content-Type is not application/json"
}
return (response, 400)
elif request.is_json:
return BucketController.update(request)
else:
raise Exception()
except Exception as e:
print("ERROR: Request is not JSON or has missing fields.")
response = {
"error": 1,
"message": "Missing fields in JSON"
}
print(response)
return (response, 404)
示例11: update_fans
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def update_fans():
"""
UPDATE FANS et GET FANS
POST: C'est la requête à faire pour modifier la vitesse d'un ventilateur
Le POST peut être testé avec ce JSON:
{"fanl": 255, "fanh": 255}
"""
if request.headers['Content-Type'] != 'application/json':
print("ERROR: Content type is not JSON in HTTP header.")
elif request.is_json:
return SensorController.update_fans(request)
else:
print("ERROR: Request is not JSON.")
return ('', 204)
示例12: _user_api_arg
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def _user_api_arg(key: str, **kwargs) -> Any:
"""Try to get the given key from the requests, try JSON body, form data and query arg."""
if request.is_json:
oid = request.json.get(key)
else:
oid = request.args.get(key) or request.form.get(key)
if not oid:
if "default" in kwargs:
app.logger.info(f'{key}={kwargs.get("default")}')
return kwargs.get("default")
raise ValueError(f"missing {key}")
app.logger.info(f"{key}={oid}")
return oid
示例13: inbound
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def inbound():
#Get the params
if request.is_json:
params = request.get_json()
else:
params = request.args or request.form
if "sig" in params:
#Init the client, just when needed
client = nexmo.Client(
key = os.getenv('NEXMO_API_KEY'),
secret = os.getenv('NEXMO_API_SECRET'),
signature_secret = os.getenv('NEXMO_SIGNATURE_SECRET'),
signature_method = 'md5'
)
#Check signature from params
if client.check_signature(params):
print("Valid signature")
else:
print("Invalid signature")
else:
print("Signature not detected in params, Nothing to compare")
return "All OK.", 200
示例14: post
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def post(self):
if not request.is_json:
return APIResult.ErrorResult(100, msg="Missing JSON in request"), 400
params = request.get_json()
username = params.get('username', None)
password = params.get('password', None)
if not username:
return APIResult.ErrorResult(status=101, msg="Missing username parameter"), 400
if not password:
return APIResult.ErrorResult(status=101, msg="Missing password parameter"), 400
if username != JWTEndpoint.user or password != JWTEndpoint.pwd:
return APIResult.ErrorResult(status=101, msg="Bad username or password"), 401
# Identity can be any data that is json serializable
ret = {'jwt': create_jwt(identity=username),
'exp': timegm((flask.current_app.config['JWT_EXPIRES'] + datetime.now()).utctimetuple())}
return ret, 200
# Protect a view with jwt_required, which requires a valid jwt
# to be present in the headers.
示例15: webhooks
# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import is_json [as 別名]
def webhooks(event_id):
if not request.is_json:
abort(400)
webhook_secret = app.config.get("WEBHOOK_SECRET")
webhook_delta = app.config.get("WEBHOOK_DELTA")
if webhook_secret and not verify_request(
request, webhook_secret, delta=webhook_delta
):
abort(400)
only = app.config.get("EVENTS_ONLY")
exclude = app.config.get("EVENTS_EXCLUDE")
try:
handle_event(request.json, only=only, exclude=exclude)
except Exception as exc:
print("Exception occurred during event handling:", str(exc))
abort(400)
return "OK"