Python flask.request.is_json() Examples

The following are 30 code examples of flask.request.is_json(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: security_controller.py    From flask-unchained with MIT License 6 votes vote down vote up
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')) 
Example #2
Source File: api.py    From microblog.pub with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: sensor.py    From jardiniot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: bucket.py    From jardiniot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: bucket.py    From jardiniot with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: 5. JSON Payload - request.json.py    From --Awesome-Python-- with GNU General Public License v3.0 6 votes vote down vote up
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']) 
Example #7
Source File: security_controller.py    From flask-unchained with MIT License 6 votes vote down vote up
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')) 
Example #8
Source File: verify-signed-sms.py    From nexmo-python-code-snippets with MIT License 6 votes vote down vote up
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 
Example #9
Source File: security_controller.py    From flask-unchained with MIT License 6 votes vote down vote up
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')) 
Example #10
Source File: JWTEndpoint.py    From crypto-bot with Apache License 2.0 6 votes vote down vote up
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. 
Example #11
Source File: anonymous_user_required.py    From flask-unchained with MIT License 6 votes vote down vote up
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 
Example #12
Source File: resource_base.py    From actinia_core with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #13
Source File: simple.py    From flask-jwt-extended with MIT License 6 votes vote down vote up
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. 
Example #14
Source File: NMOSTesting.py    From nmos-testing with Apache License 2.0 6 votes vote down vote up
def config():
    if request.method == "GET":
        return jsonify(_export_config())
    elif request.method == "PATCH":
        try:
            if not request.is_json:
                return jsonify("Error: Request mimetype is not set to a JSON specific type with a valid JSON Body"), 400
            if not request.get_json(silent=True):
                return jsonify("Error: Ensure the body of the request is valid JSON and non-empty"), 400
            request_data = request.json
            if not isinstance(request_data, dict):
                return jsonify("Error: Body must be of type object/dict"), 400
            for config_param in request_data:
                setattr(CONFIG, config_param, request_data[config_param])
            return jsonify(_export_config()), 200
        except Exception:
            return jsonify("Error: Config Update Failed"), 400 
Example #15
Source File: webhooks.py    From ricloud with GNU Lesser General Public License v3.0 6 votes vote down vote up
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" 
Example #16
Source File: demo_jwt.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #17
Source File: simple.py    From flask-jwt-simple with MIT License 6 votes vote down vote up
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    username = params.get('username', None)
    password = params.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
    ret = {'jwt': create_jwt(identity=username)}
    return jsonify(ret), 200


# Protect a view with jwt_required, which requires a valid jwt
# to be present in the headers. 
Example #18
Source File: login.py    From flask-react-spa with MIT License 5 votes vote down vote up
def login():
    if request.is_json:
        form = _security.login_form(MultiDict(request.get_json()))
    else:
        form = _security.login_form(request.form)

    if form.validate_on_submit():
        login_user(form.user, remember=form.remember.data)
        after_this_request(_commit)

        if not request.is_json:
            return redirect(get_post_login_redirect(form.next.data))

    if not request.is_json:
        return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
                                         login_user_form=form,
                                         **_ctx('login'))

    # override error messages if necessary
    confirmation_required = get_message('CONFIRMATION_REQUIRED')[0]
    if confirmation_required in form.errors.get('email', []):
        return jsonify({
            'error': confirmation_required,
        }), HTTPStatus.UNAUTHORIZED
    elif form.errors:
        username_fields = config_value('USER_IDENTITY_ATTRIBUTES')
        return jsonify({
            'error': f"Invalid {', '.join(username_fields)} and/or password."
        }), HTTPStatus.UNAUTHORIZED

    return jsonify({
        'user': form.user,
        'token': form.user.get_auth_token(),
    }) 
Example #19
Source File: app.py    From Synapse with GNU Affero General Public License v3.0 5 votes vote down vote up
def listenWebhook():
    if request.is_json:
         try:
            webhook = request.get_json()
            workflowReport = manageWebhook(webhook)
            if workflowReport['success']:
                return jsonify(workflowReport), 200
            else:
                return jsonify(workflowReport), 500
         except Exception as e:
             logger.error('Failed to listen or action webhook')
             return jsonify({'success':False}), 500
    else:
        return jsonify({'success':False, 'message':'Not JSON'}), 400 
Example #20
Source File: NMOSTesting.py    From nmos-testing with Apache License 2.0 5 votes vote down vote up
def api():
    if request.method == "GET":
        example_dict = {}
        example_dict["description"] = "An example of the body to POST to this endpoint might include:"
        example_dict["suite"] = "IS-04-01"
        example_dict["host"] = ["127.0.0.1"]
        example_dict["port"] = [80]
        example_dict["version"] = ["v1.2"]
        example_dict["selector"] = [None]
        example_dict["output"] = "xml"
        example_dict["ignore"] = ["test_23"]
        return jsonify(example_dict), 200
    elif core_app.config['TEST_ACTIVE'] is not False:
        return jsonify("""Error: A test is currently in progress.
                        Please wait until it has completed or restart the testing tool."""), 400
    if not request.is_json:
        return jsonify("Error: Request mimetype is not set to a JSON specific type with a valid JSON Body"), 400
    if not request.get_json(silent=True):
        return jsonify("Error: Ensure the body of the request is valid JSON and non-empty"), 400
    request_data = dict(DEFAULT_ARGS, **request.json)
    request_args = SimpleNamespace(**request_data)
    return_message, return_type = validate_args(request_args, access_type="http")
    if return_message:
        if return_type == ExitCodes.OK:
            return jsonify(return_message.split('\n')), 200
        else:
            return jsonify(return_message), 400
    data_format = request_args.output if request_args.output is not None else "json"
    if "." in data_format:
        filename, data_format = data_format.split(".")
    try:
        results = run_api_tests(request_args, data_format)
        if data_format == "json":
            return jsonify(results), 200
        else:
            return results, 200, {"Content-Type": "text/xml; charset=utf-8"}
    except Exception as e:
        print(e)
        results = traceback.format_exc()
        return results, 400 
Example #21
Source File: flask_mock_service.py    From REST_API_Test_Framework_Python with MIT License 5 votes vote down vote up
def test_req_body_json():
    # get_json(force=False, silent=False, cache=True)
    # Note: return is actually a dict
    
    # Note: is_json is changed to a property than a method.
    if request.is_json:
        return 'Request body content as json:\n%s' % json.dumps(request.get_json(cache=False),indent=4)
    else:
        return r'Request has no header application/json.' 
Example #22
Source File: app.py    From Synapse with GNU Affero General Public License v3.0 5 votes vote down vote up
def QRadar2alert():
    if request.is_json:
        content = request.get_json()
        if 'timerange' in content:
            workflowReport = allOffense2Alert(content['timerange'])
            if workflowReport['success']:
                return jsonify(workflowReport), 200
            else:
                return jsonify(workflowReport), 500
        else:
            logger.error('Missing <timerange> key/value')
            return jsonify({'sucess':False, 'message':"timerange key missing in request"}), 500
    else:
        logger.error('Not json request')
        return jsonify({'sucess':False, 'message':"Request didn't contain valid JSON"}), 400 
Example #23
Source File: decorators.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def is_json(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if request.method in ['POST', 'PUT', 'PATCH']:
            if not request.is_json:
                raise RequestIsNotJSON()
        return f(*args, **kwargs)

    return decorated_function 
Example #24
Source File: api.py    From ExplainToMe with Apache License 2.0 5 votes vote down vote up
def summary():
    if request.is_json:
        data = request.get_json()
        url = data.get('url', 'https://www.wsj.com/articles/how-panera-solved-its-mosh-pit-problem-1496395801')
        max_sent = data.get('max_sent', 10)
    else:
        url = request.values.get('url', 'https://www.wsj.com/articles/how-panera-solved-its-mosh-pit-problem-1496395801')
        max_sent = request.values.get('max_sent', 10)
    language = 'english'
    session_data = get_summary(url, max_sent, language)
    return jsonify(**session_data) 
Example #25
Source File: logout.py    From flask-react-spa with MIT License 5 votes vote down vote up
def logout():
    if current_user.is_authenticated:
        logout_user()

    if not request.is_json:
        return redirect(url_for('admin.index'))

    return '', HTTPStatus.NO_CONTENT 
Example #26
Source File: __init__.py    From TagBot with MIT License 5 votes vote down vote up
def method_not_allowed(e: MethodNotAllowed) -> Union[HTML, JSON]:
    if request.is_json:
        resp: JSON = ({"error": "Method not allowed"}, 405)
        return resp
    return render_template("405.html"), 405 
Example #27
Source File: dlr-flask.py    From nexmo-python-code-snippets with MIT License 5 votes vote down vote up
def delivery_receipt():
    if request.is_json:
        pprint(request.get_json())
    else:
        data = dict(request.form) or dict(request.args)
        pprint(data)
        
    return ('', 204) 
Example #28
Source File: receive-flask.py    From nexmo-python-code-snippets with MIT License 5 votes vote down vote up
def inbound_sms():
    if request.is_json:
        pprint(request.get_json())
    else:
        data = dict(request.form) or dict(request.args)
        pprint(data)

    return ('', 204) 
Example #29
Source File: flask_mock_service.py    From REST_API_Test_Framework_Python with MIT License 5 votes vote down vote up
def test_req_body():
    # get_data(cache=True, as_text=False, parse_form_data=False)
    request_body = request.get_data()
    request_body = request_body.decode('utf-8') # decode if it is byte string b''
    return 'Request body content is\n%s' % request_body
    
    # Output for request with '{"key1":"value1","key2":2}':
    # Request body content is b'{"key1":"value1","key2":2}'

# Request body content as JSON    
# Parse and return the data as JSON. If the mimetype does not indicate JSON (application/json, see is_json), this returns None unless force is true. 
Example #30
Source File: decorators.py    From JusticeAI with MIT License 5 votes vote down vote up
def ensure_json(func):
    def wrapper(*args, **kwargs):
        if not request.is_json:
            return make_response(jsonify(message='Only application/json supported'), 415)
        return func(*args, **kwargs)

    wrapper.__name__ = func.__name__
    return wrapper