Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Handling multiple sub-requests in a single Flask request

Posted by Rajiv Mayani on 2015-05-01 @ 18:56 and filed in Utilities

Batch Request

[
    {
        "method": "GET",
        "path": "/user?pretty-print=True",
    },
    {
        "method": "POST",
        "path": "/user",
        "body": {
            "user": "user-a", "name": "User Alpha"
        }
    }
]

Batch Response

[
    {
        "status": 200,
        "response": [
            {
                "user": "user-a"
            },
            {
                "user": "user-b"
            }
        ]
    },
    {
        "status": "400",
        "response": {
            "code": "INVALID_USER",
            "message": "Username contains an invalid character '-'",
        }
    }
]

Code

@app.route('/batch', methods=['POST'])
def batch(username):
    """
    Execute multiple requests, submitted as a batch.

    :statuscode 207: Multi status
    """
    try:
        requests = json.loads(request.data)
    except ValueError as e:
        abort(400)

    responses = []

    for index, req in enumerate(requests):
        method = req['method']
        path = req['path']
        body = req.get('body', None)

        with app.app_context():
            with app.test_request_context(path, 
                                          method=method, 
                                          data=body):
                try:
                    # Can modify flask.g here without affecting 
                    # flask.g of the root request for the batch

                    # Pre process Request
                    rv = app.preprocess_request()

                    if rv is None:
                        # Main Dispatch
                        rv = app.dispatch_request()

                except Exception as e:
                    rv = app.handle_user_exception(e)

                response = app.make_response(rv)

                # Post process Request
                response = app.process_response(response)

        # Response is a Flask response object.
        # _read_response(response) reads response.response 
        # and returns a string. If your endpoints return JSON object,
        # this string would be the response as a JSON string.
        responses.append({
            "status": response.status_code,
            "response": _read_response(response)
        })

    return make_response(json.dumps(responses), 207, HEADERS)

This snippet by Rajiv Mayani can be used freely for anything you like. Consider it public domain.