示例#1
0
文件: api.py 项目: OllieJC/cve-search
        def api_wrapper(*args, **kwargs):
            data = error = None
            # Get data (and possibly errors)
            try:
                data = funct(*args, **kwargs)
            except APIError as e:
                error = ({'status': 'error', 'reason': e.message}, e.status)
            except Exception as e:
                print(e)
                error = ({
                    'status': 'error',
                    'reason': 'Internal server error'
                }, 500)
            # Check if data should be returned as html or data
            try:
                returnType = 'application/json'
                if (request.url_rule.rule.lower().startswith("/api/")
                        or request.url_rule.rule.lower().endswith(".json")):
                    # Support JSONP
                    if request.args.get('callback', False):
                        data = "%s(%s)" % (request.args.get('callback'), data)

                    # Check API version for backwards compatibility. We'll call the old API v1.0
                    elif request.headers.get('Version') in ['1.1']:
                        # Get the requested return type
                        returnType = request.headers.get('Accept', '*/*')
                        # Default to JSON
                        if any(t in returnType for t in
                               ['json', 'application/*', 'text/*', '*/*']):
                            data = error if error else {
                                'status': 'success',
                                'data': data
                            }
                        elif 'plain' in returnType:
                            pass  # No need to do anything, but needs to be accepted
                        else:
                            data = ({
                                'status': 'error',
                                'reason': 'Unknown Content-type requested'
                            }, 415)
                            returnType = 'application/json'
                    if type(data) is not str:
                        if type(data) is tuple:
                            data = list(data)
                            data[0] = json.dumps(convertDatetime(dct=data[0]),
                                                 indent=4,
                                                 sort_keys=True,
                                                 default=json_util.default)
                        else:
                            data = (json.dumps(convertDatetime(dct=data),
                                               indent=4,
                                               sort_keys=True,
                                               default=json_util.default), 200)
                    cors = Configuration.getCORSSetting()
                    resp = Response(data[0], mimetype=returnType)
                    if cors != "-":
                        resp.headers['Access-Control-Allow-Origin'] = cors
                    return resp, data[1]
                    #return Response(data[0], mimetype=returnType), data[1]
            except Exception as e:
                print(e)
                pass
            if error and error[1] == 500: raise (APIError(error[0]['reason']))
            return data