summaryrefslogtreecommitdiff
path: root/src/server/rz_req_handling.py
blob: 9d3e0b44d4ccc5e459d80ab8d2cfef7ba53b47ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from flask import jsonify
from flask import make_response
import json

def make_response__json(status=200, data={}):
    """
    Construct a json response with proper content-type header

    @param data: must be serializable via json.dumps
    """
    data_str = json.dumps(data)
    resp = make_response(data_str)
    resp.headers['Content-Type'] = "application/json"
    resp.status = str(status)
    return resp

def make_response__http__empty(status=200):
    """
    Construct an empty HTTP response
    """
    resp = make_response()
    resp.status = str(status)
    return resp

def make_response__json__html(status=200, html_str=''):
    """
    Construct a json response with HTML payload
    """
    return make_response__json(data={'response__html': html_str })

def make_response__json__redirect(redirect_url, status=303, html_str=''):
    """
    Construct a json response with redirect payload
    """
    return make_response__json(data={'response__html': html_str,
                                    'redirect_url': redirect_url })

def common_resp_handle(data=None, error=None):
    """
    common response handling:
       - add common response headers
       - serialize response
    
    @data must be json serializable
    @error will be serialized with str()
    """

    def __response_wrap(data=None, error=None):
        """
        wrap response data/errors as dict - this should always be used when returning
        data to allow easy return of list objects, assist in error case distinction, etc. 
        """
        return dict(data=data, error=error)

    if error is None:
        error_str = ""
    else:
        error_str = str(error)  # convert any Exception objects to serializable form

    ret_data = __response_wrap(data, error_str)
    resp = jsonify(ret_data)  # this will create a Flask Response object

    resp.headers['Access-Control-Allow-Origin'] = '*'

    # more response processing

    return resp