flask.request.get_json

Here are the examples of the python api flask.request.get_json taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1511 Examples 7

3 Source : slApi.py
with GNU General Public License v3.0
from aau-zid

    def post(self):
        args = request.get_json()
        errors = sl.server_schema.validate(args)
        if errors:
            abort(400, str(errors))
        sl.r.sadd('servers', args['id'])
        sl.r.set('server:{}'.format(args['id']), json.dumps(args))
        return {"message": "server added", "data": args}, 201

class server(Resource):

3 Source : slApi.py
with GNU General Public License v3.0
from aau-zid

    def put(self, id):
        args = request.get_json()
        errors = sl.server_schema.validate(args)
        if errors:
            abort(400, str(errors))
        server = get_server_by_id(id)
        if server:
            sl.r.set('server:{}'.format(id), json.dumps(args))
            return { 'message': 'updated server', 'data': args}, 201
        else:
            return { 'message': 'no server with this id'}, 404

    def delete(self, id):

3 Source : slApi.py
with GNU General Public License v3.0
from aau-zid

    def post(self):
        args = request.get_json()
        errors = sl.meeting_schema.validate(args)
        if errors:
            abort(400, str(errors))
        sl.r.sadd('meetings', args['id'])
        sl.r.set('meeting:{}'.format(args['id']), json.dumps(args))
        return {"message": "meeting added", "data": args}, 201

class meeting(Resource):

3 Source : slApi.py
with GNU General Public License v3.0
from aau-zid

    def put(self, id):
        args = request.get_json()
        errors = sl.meeting_schema.validate(args)
        if errors:
            abort(400, str(errors))
        meeting = get_meeting_by_id(id)
        if meeting:
            sl.r.set('meeting:{}'.format(id), json.dumps(args))
            return { 'message': 'updated meeting', 'data': args}, 201
        else:
            return { 'message': 'no meeting with this id'}, 404

    def delete(self, id):

3 Source : slApi.py
with GNU General Public License v3.0
from aau-zid

    def put(self, id, status_base):
        args = request.get_json()
        args_json = json.dumps(args)
        if 'status_code' not in args or 'status_message' not in args:
            abort(400, 'Please provide status_code and status_message: {}'.format(args_json))
        meeting = get_meeting_by_id(id)
        if meeting:
            if sl.set_status(id, status_base.split('_'), args['status_code'], args['status_message']):
                return { 'message': 'set status', 'data': args_json}, 201
            else:
                return { 'message': 'could not set status', 'data': args_json}, 400
        else:
            return { 'message': 'no meeting with this id'}, 404

    def delete(self, id, status_base):

3 Source : slApi.py
with GNU General Public License v3.0
from aau-zid

    def post(self):
        args = request.get_json()
        errors = sl.command_schema.validate(args)
        if errors:
            abort(400, str(errors))
        try:
            sl.r.xadd('commandStream', { args['command']: json.dumps(args) })
            return {"message": "command queued successfully", "data": args}, 201
        except Exception as ERR:
            abort(400, str(ERR))

app = Flask(__name__)

3 Source : app.py
with GNU Affero General Public License v3.0
from AgnostiqHQ

def handle_result_update():
    result_update = request.get_json(force=True)
    socketio.emit("result-update", result_update)
    return jsonify({"ok": True})


@app.route("/api/draw", methods=["POST"])

3 Source : app.py
with GNU Affero General Public License v3.0
from AgnostiqHQ

def handle_draw_request():
    draw_request = request.get_json(force=True)

    socketio.emit("draw-request", draw_request)
    return jsonify({"ok": True})


@app.route("/api/results")

3 Source : api.py
with MIT License
from aimakerspace

def predict():
    req_body = request.get_json()
    text = req_body["text"]

    batch_source_ids, batch_context_ids = preprocessor([text])
    predicted_ids = model.decode(batch_source_ids, batch_context_ids)
    predicted_texts = postprocessor(predicted_ids)

    output = {
        "original_text": text,
        "corrected_text": predicted_texts[0]
    }

    return output


if __name__ == "__main__":

3 Source : api.py
with MIT License
from aimakerspace

def predict():
    req_body = request.get_json()
    tensor_dict = preprocessor([req_body])
    output = model(**tensor_dict)
    return {"probability": output["label_probs"].item()}


if __name__ == '__main__':

3 Source : api.py
with MIT License
from aimakerspace

def predict():
    """POST method to run inference against NEA model.

    Returns:
        JSON: return the friendly score for prompt_id 1.
    """
    req = request.get_json()
    text = req['essay']
    tokens = nea_preprocessor([text])
    score = nea_model(**tokens)
    friendly_score = int(convert_to_dataset_friendly_scores(score.logits.detach().numpy(), 1))
    return jsonify({"predictions": [friendly_score]})


if __name__ == "__main__":

3 Source : base.py
with MIT License
from alexandermendes

    def _get_validated_data(self, model_cls):
        data = request.get_json()
        try:
            self._validate_data(data, model_cls)
        except ValidationError as err:
            abort(400, err)
        return data

    def _validate_data(self, obj, model_cls):

3 Source : server.py
with MIT License
from alexmojaki

def body_hashes_present(session):
    hashes = request.get_json()
    query = (session.query(Function.body_hash, sqlalchemy.func.count(Call.id))
             .outerjoin(Call)
             .filter(Function.body_hash.in_(hashes))
             .group_by(Function.body_hash))
    return DecentJSONEncoder().encode([
        dict(hash=h, count=count)
        for h, count in query
    ])


def main(argv=sys.argv[1:]):

3 Source : simple_blockchain.py
with Apache License 2.0
from aliya-rahmani

def new_trx():
    '''will add a new trx by getting sender, recipient, amount'''
    values = request.get_json()
    this_block = blockchain.new_trx(values['sender'], values['recipient'], values['amount'])
    res = {'message': f'will be added to block {this_block}'}
    return jsonify(res), 201

    return "a new trx added"

@app.route('/chain')

3 Source : simple_blockchain.py
with Apache License 2.0
from aliya-rahmani

def register_node():
    '''added nodes'''
    values = request.get_json()

    nodes = values.get('nodes')
    for node in nodes:
        blockchain.register_node(node)

    res = {
        'message': 'nodes added',
        'total_nodes': list(blockchain.nodes)
    } 

    return jsonify(res), 201

@app.route('/nodes/resolve')

3 Source : utils.py
with MIT License
from Allen7D

def get_request_args(as_dict: bool = False):
    '''获取请求中的query和body中的所有参数
       并将数据集转为 字典类型 或者 namedtuple类型
    :param as_dict: 是否转为字典类型
    :return:
    '''
    data, args = request.get_json(silent=True), request.args.to_dict()
    args_json = dict(data, **args) if data is not None else args
    data = {
        key: value for key, value in args_json.items() if value is not None
    }
    return data if as_dict else as_namedtuple(data)

3 Source : validator.py
with MIT License
from Allen7D

    def __init__(self):
        data = request.get_json(silent=True)  # body中
        # view_args = _request_ctx_stack.top.request.view_args  # path中,获取view中(path路径里)的args
        args = request.args.to_dict()  # query中
        super(BaseValidator, self).__init__(data=data, **args)

    def validate_for_api(self):

3 Source : flask_app.py
with MIT License
from Anku5hk

def summarize():
    print('Generating SUmmary.....')
    req = request.get_json()
    summary = get_summary(req['input_text'])
    res = make_response(jsonify({"my_summary": capitilize_text(summary)}), 200)
    return res

@app.route("/generate/thequestions", methods=["POST"])

3 Source : flask_app.py
with MIT License
from Anku5hk

def thequestions():
    global org_answers
    questions = []
    req = request.get_json()
    print('Generating SUmmary.....')
    text = get_summary(req['input_text'])
    print('Generating questions.....')
    question_answers = get_questions(text)
    print(question_answers)
    for a in question_answers:
        if len(a['question'])   <   70:
            questions.append(a['question'])
            org_answers.append(a['answer'][6:])
    res = make_response(jsonify({"my_questions": questions}), 200)
    return res

@app.route('/verifyquestions/verifcation', methods=["POST"])

3 Source : flask_app.py
with MIT License
from Anku5hk

def verifcation():
    global org_answers
    print('Verifying answers.......')
    pred_answers = request.get_json()
    correct_ans = comapare_answers(pred_answers['predicted_answers'])
    print('Answers verified.......')
    correct_ans = 'You answered {} questions correctly!!'.format(correct_ans)
    org_answers = []
    my_response = make_response(jsonify({"num_of_correct": correct_ans}), 200)
    return my_response

@app.route('/favicon.ico') 

3 Source : server.py
with Apache License 2.0
from anuragmishra1

def train():
    return jsonify(train_n_load(request.get_json()))


# Parsing Api
@application.route('/parse', methods=['POST'])

3 Source : CoreService.py
with Apache License 2.0
from arakat-community

def interpret_graph():
   json_data = request.get_json(force=True)
   json_data = convert(json_data)
   print(json_data)
   print(type(json_data))
   graph = json_data['graph']
   print(graph)
   print("------------")
   dag_properties = json_data['dag_properties']
   print(dag_properties)
   print("------------")
   code_info, success, errors, additional_info = PipelineGenerator.generate_pipeline(graph, dag_properties)
   result={"codes": code_info, "result_code": success, "errors": errors, "additional_info": additional_info}
   json_string = json.dumps(result)
   return json_string

def convert(data):

3 Source : app.py
with MIT License
from ArjanCodes

def graphql_server():
    # GraphQL queries are always sent as POST
    data = request.get_json()

    # Note: Passing the request to the context is optional.
    # In Flask, the current request is always accessible as flask.request
    schema = create_schema()
    success, result = graphql_sync(schema, data, context_value=request, debug=app.debug)

    status_code = 200 if success else 400
    return jsonify(result), status_code


if __name__ == "__main__":

3 Source : app.py
with MIT License
from ArjanCodes

def route_update_blog(id: str):
    data = request.get_json()
    return jsonify(update_blog(int(id), data))


@app.route("/authors")

3 Source : views.py
with Apache License 2.0
from arkhn

def get_owners():
    credentials = request.get_json()

    try:
        explorer = DatabaseExplorer(credentials)
        db_owners = explorer.get_owners()
        return jsonify(db_owners)
    except OperationalError as e:
        if "could not connect to server" in str(e):
            raise OperationOutcome(f"Could not connect to the database: {e}")
        else:
            raise OperationOutcome(e)
    except Exception as e:
        raise OperationOutcome(e)


@api.route("/get_owner_schema/  <  owner>", methods=["POST"])

3 Source : views.py
with Apache License 2.0
from arkhn

def get_owner_schema(owner):
    credentials = request.get_json()

    try:
        explorer = DatabaseExplorer(credentials)
        db_schema = explorer.get_owner_schema(owner)
        return jsonify(db_schema)
    except OperationalError as e:
        if "could not connect to server" in str(e):
            raise OperationOutcome(f"Could not connect to the database: {e}")
        else:
            raise OperationOutcome(e)
    except Exception as e:
        raise OperationOutcome(e)


@api.errorhandler(OperationOutcome)

3 Source : api.py
with Apache License 2.0
from arkhn

def update(resource_type, id):
    if resource_type not in resources_models:
        raise OperationOutcome(f"Unknown resource type: {resource_type}")

    resource_data = request.get_json(force=True)
    model = resources_models[resource_type](id=id)
    return model.update(resource_data).json()


@api.route("/  <  resource_type>/ < id>", methods=["PATCH"])

3 Source : api.py
with Apache License 2.0
from arkhn

def patch(resource_type, id):
    if resource_type not in resources_models:
        raise OperationOutcome(f"Unknown resource type: {resource_type}")

    patch_data = request.get_json(force=True)
    model = resources_models[resource_type](id=id)
    return model.patch(patch_data).json()


@api.route("/  <  resource_type>", methods=["POST"])

3 Source : api.py
with Apache License 2.0
from arkhn

def create(resource_type):
    if resource_type not in resources_models:
        raise OperationOutcome(f"Unknown resource type: {resource_type}")

    resource_data = request.get_json(force=True)

    model = resources_models[resource_type](resource=resource_data)
    return model.create().json()


@api.route("/  <  resource_type>/ < id>", methods=["DELETE"])

3 Source : api.py
with Apache License 2.0
from arkhn

def upload_bundle():
    # TODO methodology to avoid/process huge bundles
    bundle_data = request.get_json(force=True)

    if "resourceType" not in bundle_data or bundle_data["resourceType"] != "Bundle":
        raise OperationOutcome("input must be a FHIR Bundle resource")

    store = get_store()
    try:
        store.upload_bundle(bundle_data)
    except Exception as e:
        logging.error(f"Error while uploading bundle: {e}")
        return jsonify(success=False)

    return jsonify(success=True)


@api.route("/metadata", methods=["GET"])

3 Source : app.py
with MIT License
from arxanas

def detect() -> Response:
    model = get_model()
    query = request.get_json(force=True)
    assert query is not None
    subject = query.get("subject", "")
    body = query.get("body", "")
    result = classify(model, text=subject + " " + body, num_top_keywords=5)
    return jsonify(
        {
            "prediction": result.prediction,
            "probability": result.probability,
            "top_keywords": result.top_keywords,
        }
    )


@app.route("/reply", methods=["POST"])

3 Source : app.py
with GNU General Public License v3.0
from asjacobs92

def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request: {}".format(json.dumps(req, indent=4)))
    try:
        res = actions[req.get("result").get("action")](req)
    except:
        res = {"message": "Action not mapped in webhook."}
    res = json.dumps(res, indent=4)
    print("Response: {}".format(json.dumps(res, indent=4)))

    r = make_response(res)
    r.headers["Content-Type"] = "application/json"
    return r


if __name__ == "__main__":

3 Source : upload.py
with GNU General Public License v3.0
from AUCR

def upload_file():
    """API Create new user."""
    data = request.get_json() or {}
    if 'file' not in data:
        return bad_request('must have file in fields')
    file_hash = create_upload_file(data.file, os.path.join(current_app.UPLOAD_FOLDER))
    file_upload = FileUpload
    file_upload.from_dict(data=data)
    response = jsonify(file_upload.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.upload_file', md5_hash=file_hash)
    return response

3 Source : groups.py
with GNU General Public License v3.0
from AUCR

def create_group() -> object:
    """API create new group call."""
    data = request.get_json() or {}
    if 'group_name' not in data:
        return bad_request('must include group_name field')
    if Groups.query.filter_by(name=data['group_name']).first():
        return bad_request('please use a different group_name')
    group = Groups(name=data['group_name'])
    group.from_dict(data)
    db.session.add(group)
    db.session.commit()
    response = jsonify(group.to_dict())
    response.status_code = 201
    return response


@api_page.route('/groups/  <  int:group_id>', methods=['PUT'])

3 Source : groups.py
with GNU General Public License v3.0
from AUCR

def update_group(group_id):
    """API update group call."""
    group = Groups.query.get_or_404(group_id)
    data = request.get_json() or {}
    if 'name' in data and data['name'] != group.name and \
            Groups.query.filter_by(name=data['name']).first():
        return bad_request('please use a different group_name')
    group.from_dict(data)
    db.session.commit()
    return jsonify(group.to_dict())

3 Source : users.py
with GNU General Public License v3.0
from AUCR

def update_user(id_):
    """API Update user account."""
    user = User.query.get_or_404(id_)
    data = request.get_json() or {}
    if 'username' in data and data['username'] != user.username and \
            User.query.filter_by(username=data['username']).first():
        return bad_request('please use a different username')
    if 'email' in data and data['email'] != user.email and User.query.filter_by(email=data['email']).first():
        return bad_request('please use a different email address')
    user.from_dict(data, new_user=False)
    db.session.commit()
    return jsonify(user.to_dict())

3 Source : browser_autocomplete_server.py
with MIT License
from Aunsiels

def add_new():
    data = request.get_json()
    for new_query in data["new_queries"]:
        query_queue.put(new_query)
    return "OK"


if __name__ == "__main__":

3 Source : index.py
with MIT License
from auth0-blog

def add_income():
    income = IncomeSchema().load(request.get_json())
    transactions.append(income.data)
    return "", 204


@app.route('/expenses')

3 Source : index.py
with MIT License
from auth0-blog

def add_expense():
    expense = ExpenseSchema().load(request.get_json())
    transactions.append(expense.data)
    return "", 204


if __name__ == "__main__":

3 Source : flask_server.py
with GNU General Public License v3.0
from avidale

    def facebook_response(self):
        output = request.get_json()
        logger.info('Got messages from Facebook: {}'.format(output))
        for event in output['entry']:
            messaging = event['messaging']
            for message in messaging:
                if message.get('message') or message.get('postback'):
                    recipient_id = message['sender']['id']
                    response = self.connector.respond(message, source=SOURCES.FACEBOOK)
                    logger.info('Sending message to Facebook: {}'.format(response))
                    self.facebook_bot.send_message(recipient_id, response)
        return "Message Processed"

    def run_server(self, host="0.0.0.0", port=None, use_ngrok=False, debug=False):

3 Source : core.py
with MIT License
from aviezab

def register():
  content = request.get_json(silent=True)
  if all(x in content.keys() for x in ["email","password"]):
    email = content["email"]
    password = content["password"]
    if not iotku.find_user(email=email):
      user = iotku.add_user(email=email,password=password)
      session['logged_in'] = True
      session['email'] = user.get('email')
      session['api_key'] = user.get('api_key')
      return jsonify({'result': True})
    else:
      return jsonify({'result': False,'reason':'An account with the same email exists'})
  else: 
    return jsonify({'result': False,'reason':'Invalid format'})

@api.route('/api/connect', methods=['POST'])

3 Source : FaucetController.py
with MIT License
from BananoCoin

def faucet_claim():
    json_data = request.get_json(silent=True)
    if json_data is None:
        abort(400, 'bad request')
    elif 'address' not in json_data:
        abort(400, 'bad request')
    elif 'hcaptchaResponse' not in json_data or json_data['hcaptchaResponse'] is None:
        return jsonify({"error": "Captcha verification failed"})
    if 'recaptchaToken' in json_data:
        abort(500, 'server error')
    if not Captcha.verify_hcaptcha(json_data['hcaptchaResponse'], request.remote_addr):
        return jsonify({"error": "Captcha verification failed"})
    with db.database.connection_context():
        payment, message = FaucetPayment.make_or_reject_payment(json_data['address'], request.remote_addr)
    if payment is None:
        return jsonify({"error": message})
    return jsonify({"success":message})

3 Source : bcol_profiles.py
with Apache License 2.0
from bcgov

    def post():
        """Return BC Online profile details."""
        request_json = request.get_json()

        try:
            bcol_response = Org.get_bcol_details(bcol_credential=request_json)
            response, status = bcol_response.json(), bcol_response.status_code
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status

3 Source : bulk_user.py
with Apache License 2.0
from bcgov

    def post():
        """Admin users can post multiple users to his org.Use it for anonymous purpose only."""
        try:
            request_json = request.get_json()
            valid_format, errors = schema_utils.validate(request_json, 'bulk_user')
            if not valid_format:
                return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST

            users = UserService.create_user_and_add_membership(request_json['users'], request_json['orgId'])
            is_any_error = any(user['http_status'] != 201 for user in users['users'])

            response, status = users, http_status.HTTP_207_MULTI_STATUS if is_any_error else http_status.HTTP_200_OK
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status

3 Source : org.py
with Apache License 2.0
from bcgov

    def post(org_id):
        """Create a new login type for the specified org."""
        request_json = request.get_json()
        login_option_val = request_json.get('loginOption')
        # TODO may be add validation here
        try:
            login_option = OrgService.add_login_option(org_id, login_option_val)
            response, status = jsonify({'login_option': login_option.login_source}), http_status.HTTP_201_CREATED
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status

    @staticmethod

3 Source : org.py
with Apache License 2.0
from bcgov

    def put(org_id):
        """Update a new login type for the specified org."""
        request_json = request.get_json()
        login_option_val = request_json.get('loginOption')
        # TODO may be add validation here
        try:
            login_option = OrgService.update_login_option(org_id, login_option_val)
            response, status = jsonify({'login_option': login_option.login_source}), http_status.HTTP_201_CREATED
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status


@cors_preflight('GET,DELETE,POST,PUT,OPTIONS')

3 Source : org.py
with Apache License 2.0
from bcgov

    def post(org_id):
        """Create a new contact for the specified org."""
        request_json = request.get_json()
        valid_format, errors = schema_utils.validate(request_json, 'contact')
        if not valid_format:
            return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST

        try:
            response, status = OrgService.add_contact(org_id, request_json).as_dict(), http_status.HTTP_201_CREATED
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status

    @staticmethod

3 Source : org.py
with Apache License 2.0
from bcgov

    def put(org_id):
        """Update an existing contact for the specified org."""
        request_json = request.get_json()
        valid_format, errors = schema_utils.validate(request_json, 'contact')
        if not valid_format:
            return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST
        try:
            response, status = OrgService.update_contact(org_id, request_json).as_dict(), http_status.HTTP_200_OK
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status

    @staticmethod

3 Source : org.py
with Apache License 2.0
from bcgov

    def delete(org_id, business_identifier):
        """Delete an affiliation between an org and an entity."""
        request_json = request.get_json(silent=True) or {}
        email_addresses = request_json.get('passcodeResetEmail')
        reset_passcode = request_json.get('resetPasscode', False)

        try:
            AffiliationService.delete_affiliation(org_id, business_identifier, email_addresses, reset_passcode)
            response, status = {}, http_status.HTTP_200_OK

        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code

        return response, status


@cors_preflight('GET,OPTIONS')

3 Source : org_api_keys.py
with Apache License 2.0
from bcgov

    def post(org_id):
        """Create new api key for the org."""
        request_json = request.get_json()
        valid_format, errors = schema_utils.validate(request_json, 'api_key')

        if not valid_format:
            return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST
        try:
            response, status = ApiGatewayService.create_key(org_id, request_json), http_status.HTTP_201_CREATED
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status


@cors_preflight('DELETE,OPTIONS')

See More Examples