Example #1
0
File: manage.py Project: dag/stutuz
def shell():
    """Interactive stutuz console."""
    from inspect import cleandoc
    from stutuz import db, models

    banner = '''\
        Interactive stutuz console.

        Useful names:

          app     Flask application for stutuz
          db      The database instance
          models  Namespace for all models
        '''

    banner = cleandoc(banner)
    try:
        current_app.preprocess_request()
        context = dict(app=current_app, db=db, models=models)

        try:
            import bpython
        except ImportError:
            import code
            code.interact(banner, local=context)
        else:
            bpython.embed(context, ['-i'], banner)
    finally:
        current_app.process_response(current_app.response_class())
Example #2
0
def batch():
    """
    Execute multiple requests, submitted as a batch.

    :statuscode 207: Multi status
    """

    # TODO: we could probably turn off csrf protection for each requests
    # and only use the CSRF in the header of the parent request
    requests, err = RequestSchema().load(request.get_json(), many=True)
    responses = []
    status_code = 207
    for req in requests:
        method = req['method']
        url = req['url']
        body = req.get('body', None)
        headers = req.get('headers', {})

        with current_app.app_context():
            headers.setdefault('accept', 'application/json')
            with current_app.test_request_context(url, method=method, data=body,
                                                  headers=headers):
                try:
                    # Can modify flask.g here without affecting
                    # flask.g of the root request for the batch

                    # Pre process Request
                    rv = current_app.preprocess_request()

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

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

                response = current_app.make_response(rv)

                # Post process Request
                response = current_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_code": response.status_code,
            "body": response.data.decode('utf-8'),
            "headers": [{'name': k, 'value': v} for k, v in response.headers.items()]
        })

        # if error response
        if (response.status_code % 400 < 100) or (response.status_code % 400 < 100):
            status_code = response.status_code
            break

    return json.dumps(responses), status_code
def batch():
    """
    Execute multiple requests, submitted as a batch.
    :status code 207: Multi status
    :response body: Individual request status code
    Batch Request data Example:
    [
        {
            "method": "PATCH",
            "path": "/party-api/v1/respondents/email",
            "body": respondent_email_3,
            "headers": <headers>
        },
        {
            "method": "PATCH",
            "path": "/party-api/v1/respondents/email",
            "body": respondent_email_0,
            "headers": <headers>
        },
    ]
    """
    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)
        headers = req.get('headers', None)

        with current_app.app_context():
            with current_app.test_request_context(path,
                                                  method=method,
                                                  json=body,
                                                  headers=headers):
                try:
                    rv = current_app.preprocess_request()
                    if rv is None:
                        rv = current_app.dispatch_request()
                except Exception as e:
                    rv = current_app.handle_user_exception(e)
                response = current_app.make_response(rv)
                response = current_app.process_response(response)
        responses.append({
            "status": response.status_code,
        })

    return make_response(json.dumps(responses), 207)
Example #4
0
def end_request(ctx, response=None):
    """
    End a request context with a response.
    """
    current_app.process_response(response or current_app.response_class())
    ctx.pop()