Beispiel #1
0
def _api_convert_output(status_code, return_value, response=None):
    if not response:
        response = Response()
        response.status_code = status_code
    """ Convert the output to what the client asks """
    content_type = flask.request.environ.get('CONTENT_TYPE', 'text/json')

    if "text/json" in content_type:
        response.content_type = 'text/json; charset=utf-8'
        response.response = [json.dumps(return_value)]
        return response
    if "text/html" in content_type:
        response.content_type = 'text/html; charset=utf-8'
        dump = yaml.dump(return_value)
        response.response = ["<pre>" + dump + "</pre>"]
        return response
    if "text/yaml" in content_type or \
                    "text/x-yaml" in content_type or \
                    "application/yaml" in content_type or \
                    "application/x-yaml" in content_type:
        response.content_type = 'text/yaml; charset=utf-8'
        response.response = [yaml.dump(return_value)]
        return response
    response.content_type = 'text/json; charset=utf-8'
    response.response = [json.dumps(return_value)]
    return response
Beispiel #2
0
def make_response(data, output='json'):
    resp = Response()

    if output == 'json':
        resp.data = json.dumps(data, indent=2)
        resp.content_type = 'application/json; charset="UTF-8"'
    elif output == 'yaml':
        resp.data = yaml.safe_dump(data, default_flow_style=False, indent=2)
        resp.content_type = 'application/yaml; charset="UTF-8"'

    return resp
Beispiel #3
0
    def buildResponse(self, intStatus, dictResponse=None, dictHeaders=None):
        '''
        *Author: Iago Rocha*
        Create a Flask Response object with custom headers
        - Param 0: int | status code of response object
        - Param 1: dict | a dict that will be cast to a json string
        - Param 2: dict | dict within header and value. Ex.: {'IA-Cidada-API-Version' : '1.0.0'}
        - Return: object | a Flask Response object 
        '''
        # create a response object
        objResponse = Response()
        # set a response json
        objResponse.response = json.dumps(dictResponse, sort_keys=False)
        # config content type
        objResponse.content_type = 'application/json'
        # set headers response
        objResponse.headers['IA-Cidada-API-Version'] = '1.0.0'

        # verify if headers is a dict instance
        if isinstance(dictHeaders, dict):
            # loop to add headers
            for strKey, strValue in dictHeaders.iteritems():
                # add header and value to response object
                objResponse.headers[strKey] = strValue

        # set status return
        objResponse.status = str(intStatus)
        # return a Response object
        return objResponse
Beispiel #4
0
def post_message_to_entity(entity, request):
    res = Response()
    res.content_type = 'application/json'
    res.status_code = 200
    res.data = 'SUCCESS'
    error_msg = 'Please send user, message and owner either in query parameters or as json payload.'
    if request.is_json:
        payload = request.get_json()
        user = payload.get('user', None)
        if user and payload.get('message', None):
            db_id = add_to_db(payload, ADDING_TO_REDIS_QUEUE, entity)
            executor.submit(publish_to_redis, payload, db_id, entity)
            res.data = str(db_id)
        else:
            res.data = error_msg
            res.status_code = 404
    else:
        user = request.args.get('user', None)
        message = request.args.get('message', None)
        if user and message:
            payload = {
                'user': user,
                'message': message,
            }
            db_id = add_to_db(payload, ADDING_TO_REDIS_QUEUE, entity)
            executor.submit(publish_to_redis, payload, db_id, entity)
            #publish_to_redis(payload,db_id,entity)
            res.data = str(db_id)

        else:
            res.data = error_msg
            res.status_code = 404

    return res
Beispiel #5
0
def stat1():
    pub_year = request.args.get('pub_year', None)
    pub_month = request.args.get('pub_month', None)
    labels = []
    data = []
    if pub_year or pub_month:
        conn = sqlite3.connect('stat.sqlite')
        cursor = conn.cursor()
        if pub_month:
            sql = 'SELECT pub_day, count FROM stat1 WHERE pub_month="{}"'.format(
                pub_month)
        elif pub_year:
            sql = 'SELECT pub_month, SUM(count) FROM stat1 WHERE pub_year="{}" GROUP BY pub_month'.format(
                pub_year)

        for row in cursor.execute(sql):
            label, count = row
            labels.append(label)
            data.append(count)
        cursor.close()
        conn.close()

    result = {'labels': labels, 'data': data}
    response = Response()
    response.data = json.dumps(result)
    response.content_type = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
Beispiel #6
0
    def inner(*args, **kwargs):
        response = Response()
        response.content_type = 'application/json'
        try:
            result = f(*args, **kwargs)
            result = {
                'status': SUCCESS,
                'data': result,
            }
            response.status_code = 200
        except APINotFoundException as e:
            result = {
                'status': FAIL,
                'message': str(e)
            }
            response.status_code = 404
        except APIFailureException as e:
            result = {
                'status': FAIL,
                'message': str(e),
            }
            response.status_code = 500
        except HTTPException:
            raise # This causes issues
        except Exception as e:
            result = {
                'status': ERROR,
                'message': str(e),
            }
            response.status_code = 500

        response.data = json.dumps(result)
        return response
Beispiel #7
0
    def get(self):
        self.reqparse.add_argument('page', type=int, default=1)
        self.reqparse.add_argument('count',
                                   type=int,
                                   default=100,
                                   choices=[25, 50, 100])
        self.reqparse.add_argument('numInstances', type=int, default=None)
        self.reqparse.add_argument('fileFormat',
                                   type=str,
                                   default='json',
                                   choices=['json', 'xlsx'])

        args = self.reqparse.parse_args()
        query = {'limit': 99999, 'page': 1, 'properties': {}}

        total, elbs = ELB.search(**query)
        elbs = [x.to_json() for x in elbs]
        elb_count = len(elbs)

        output = {'message': None, 'elbCount': total, 'elbs': elbs}

        response = Response(response=b64encode(
            bytes(json.dumps(output, indent=4, cls=InquisitorJSONEncoder),
                  'utf-8')))
        response.content_type = 'application/octet-stream'
        response.status_code = HTTP.OK
        return response
Beispiel #8
0
def generate_offers_xls():
    import urlparse, StringIO
    from modules.catalog.models import Offer
    from xlwt import Workbook

    wb = Workbook()
    ws = wb.add_sheet('Offers')
    url_root = request.url_root

    for line, offer in enumerate(Offer.objects()):
        ws.write(line, 0, offer.name)
        ws.write(
            line, 1,
            urlparse.urljoin(url_root,
                             url_for('site.dispatcher', path=offer.path)))

    output = StringIO.StringIO()
    wb.save(output)

    response = Response()
    response.status_code = 200
    response.data = output.getvalue()

    response.content_type = u'application/vnd.ms-excel'
    response.headers["Content-Disposition"] = "attachment; filename=offers.xls"

    return response
Beispiel #9
0
def handle_error(error):
    logging.error('An exception has occured: %s', str(error))
    response = Response()
    response.data = json.dumps({'error': str(error)})
    response.content_type = 'application/json'
    response.status_code = 400
    return response
Beispiel #10
0
 def driveQuery(self, context) -> Any:
     self._checkDriveHeaders(context)
     query: str = context.args().get("q", "")
     fields = self.parseFields(context.args().get('fields', 'id'))
     if mimeTypeQueryPattern.match(query):
         ret = []
         mimeType = query[len("mimeType='"):-1]
         for item in self.items.values():
             if item.get('mimeType', '') == mimeType:
                 ret.append(self.filter_fields(item, fields))
         return {'files': ret}
     elif parentsQueryPattern.match(query):
         ret = []
         parent = query[1:-len("' in parents")]
         if parent not in self.items:
             return HTTP_404_NOT_FOUND
         if parent in self.lostPermission:
             resp = Response()
             resp.status_code = HTTP_403_FORBIDDEN
             resp.content_type = "application/json"
             resp.set_data(
                 '{"error": {"errors": [{"reason": "forbidden"}]}}')
             return resp
         for item in self.items.values():
             if parent in item.get('parents', []):
                 ret.append(self.filter_fields(item, fields))
         return {'files': ret}
     elif len(query) == 0:
         ret = []
         for item in self.items.values():
             ret.append(self.filter_fields(item, fields))
         return {'files': ret}
     else:
         return HTTP_400_BAD_REQUEST
Beispiel #11
0
def random_bytes(n):
    """Returns n random bytes generated with given seed
    ---
    tags:
      - Dynamic data
    parameters:
      - in: path
        name: n
        type: int
    produces:
      - application/octet-stream
    responses:
      200:
        description: Bytes.
    """

    if n <= 0 or n > (100 * 1024):
        response = Response(headers={
            "ETag": "range%d" % n,
            "Accept-Ranges": "bytes"
        })
        response.status_code = 404
        response.data = "number of bytes must be in the range (0, 102400]"
        return response

    params = CaseInsensitiveDict(request.args.items())
    if "seed" in params:
        random.seed(int(params["seed"]))

    response = make_response()

    # Note: can't just use os.urandom here because it ignores the seed
    response.data = bytearray(random.randint(0, 255) for i in range(n))
    response.content_type = "application/octet-stream"
    return response
    def handle_exception(e):
        """Return JSON instead of HTML for errors"""

        if (isinstance(e, HTTPException)):
            # start with the correct headers and status code from the error
            response = e.get_response()
            # replace the body with JSON
            response.data = json.dumps({
                "code": e.code,
                "name": e.name,
                "description": e.description,
            })
            response.content_type = "application/json"
        else:
            traceback.print_exc()
            # start with empty response object
            response = Response(status=500)
            # add a JSON body
            response.data = json.dumps({
                "code": 500,
                "name": 'Internal Server Error',
                "description": 'Something Went Wrong',
            })
            response.content_type = "application/json"

        return response
 def request_finished_handler(self, sender, response: Response, **extra):
     if 200 >= response.status_code < 300 and response.content_type == 'application/json':
         data = response.get_data(as_text=True)
         jwe = JWE(data, alg='A256KW', enc='A256CBC-HS512', cty='application/json')
         encrypted = jwe.encrypt(self._keys, kid=self._keys[0].kid)
         response.content_type = 'application/jose'
         response.data = encrypted
Beispiel #14
0
def phone():

    current_app.logger.info(str(request.form.to_dict()))
    response = Response()
    response.data= 'OK'
    response.content_type="text/plain; charset=utf-8"
    return response, 200 
Beispiel #15
0
def stat2():
    kota = request.args.get('kota', None)
    pub_year = request.args.get('pub_year', None)
    pub_month = request.args.get('pub_month', None)
    labels = []
    data = []

    if pub_year or pub_month:
        conn = sqlite3.connect('stat.sqlite')
        cursor = conn.cursor()
        if pub_month:
            sql = 'SELECT pub_day, new_case, recovered, death FROM stat2 WHERE pub_month="{}" AND kota="{}"'.format(
                pub_month, kota)
        elif pub_year:
            sql = 'SELECT pub_month, SUM(new_case), SUM(recovered), SUM(death) FROM stat2 WHERE pub_year="{}" AND kota="{}" GROUP BY pub_month'.format(
                pub_year, kota)

        for row in cursor.execute(sql):
            label, new_case, recovered, death = row
            labels.append(label)
            data.append({
                'new_case': new_case,
                'recovered': recovered,
                'death': death
            })
        cursor.close()
        conn.close()

    result = {'labels': labels, 'data': data}
    response = Response()
    response.data = json.dumps(result)
    response.content_type = 'application/json'
    #     response.headers['Access-Control-Allow-Origin'] = '*'
    return response
Beispiel #16
0
def build_file_response(file: typing.Union[Image, Video]):
    response = Response(file.content)
    response.headers[
        'Content-Disposition'] = f'attachment; filename={file.filename}'
    response.content_type = file.mimetype

    return response
Beispiel #17
0
def exception_handler(exc):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    status = 500
    message = "Unhandled exception occured."
    data = {
        "message": message,
        "debug_message": str(exc),
        "code": None,
    }

    if isinstance(exc, HTTPException):
        status = exc.code
        message = exc.name
        data = {
            "code": None,
            "message": exc.name,
            "debug_message": exc.description,
        }

    if isinstance(exc, HttpException):
        data = exc.marshal()
        status = exc.status

    if status >= 500:
        logger.exception(message)

    response = Response(status=status)

    response.data = json.dumps(data)
    response.content_type = "application/json"
    return response
Beispiel #18
0
def stat2_pie():
    kota = request.args.get('kota', None)
    pub_year = request.args.get('pub_year', None)
    pub_month = request.args.get('pub_month', None)
    labels = ['New Case, Recovered, Death']
    data = {}

    if pub_year or pub_month:
        conn = sqlite3.connect('stat.sqlite')
        cursor = conn.cursor()
        if pub_month:
            sql = 'SELECT SUM(new_case), SUM(recovered), SUM(death) FROM stat2 WHERE pub_month="{}" AND kota="{}"'.format(
                pub_month, kota)
        elif pub_year:
            sql = 'SELECT SUM(new_case), SUM(recovered), SUM(death) FROM stat2 WHERE pub_year="{}" AND kota="{}"'.format(
                pub_year, kota)

        cursor.execute(sql)
        row = cursor.fetchone()
        print(row)

        new_case, recovered, death = row
        data = {'new_case': new_case, 'recovered': recovered, 'death': death}

        cursor.close()
        conn.close()

    result = {'labels': labels, 'data': data}
    response = Response()
    response.data = json.dumps(result)
    response.content_type = 'application/json'
    #     response.headers['Access-Control-Allow-Origin'] = '*'
    return response
Beispiel #19
0
def export_csv():
    survey = request.args.get('survey')
    yesterday = date.today() - timedelta(days=1)
    start = yesterday.strftime('%Y-%m-%d 00:00:00')
    start_dt = datetime.strptime(start,
                                 '%Y-%m-%d %H:%M:%S').replace(tzinfo=server_tz)
    end = yesterday.strftime('%Y-%m-%d 23:59:59')
    end_dt = datetime.strptime(end,
                               '%Y-%m-%d %H:%M:%S').replace(tzinfo=server_tz)

    summary = database.survey_admin.generate_summary(survey_name=survey,
                                                     start=start_dt,
                                                     end=end_dt)

    summary_rows = [[survey.encode('utf-8')], [yesterday.strftime('%d-%m-%Y')],
                    [], ['New users', 'Active users', 'Points', 'Prompts'],
                    [
                        summary['new_users'], summary['active_users'],
                        summary['num_points'], summary['num_prompts']
                    ]]

    filestream = io.BytesIO()
    filestream.write(codecs.BOM_UTF8)
    writer = csv.writer(filestream)
    writer.writerows(summary_rows)
    csv_data = filestream.getvalue().strip('\r\n')

    csv_fn = '{survey}-{date}.csv'.format(survey=survey.encode('utf-8'),
                                          date=yesterday)
    headers = {
        'Content-disposition': 'attachment; filename={fn}'.format(fn=csv_fn)
    }
    response = Response(csv_data, mimetype='text/csv', headers=headers)
    response.content_type = 'text/csv'
    return response
Beispiel #20
0
def factquery():

    current_app.logger.info(str(request.form.to_dict()))
    response = Response()
    response.data= 'OK'
    response.content_type="text/plain; charset=utf-8"
    time.sleep( 20)
    return response, 200 
Beispiel #21
0
def respond(data, code):
    output = request.args.get('output', default='json')

    response = Response(status=code)
    if output == 'pretty':
        response.content_type = 'text/plain; charset=utf-8'
        response.data = json.dumps(data,
                                   ensure_ascii=False,
                                   indent=4,
                                   separators=(',', ': '),
                                   cls=APIJSONEncoder)
    else:
        response.content_type = 'application/json; charset=utf-8'
        response.data = json.dumps(data,
                                   ensure_ascii=False,
                                   cls=APIJSONEncoder)

    return response
Beispiel #22
0
def generateResponse(status="200 OK",
                     content_type="application/json",
                     cache_control="no-cache",
                     message=""):
    response = Response()
    response.status = status
    response.content_type = content_type
    # response.cache_control = cache_control
    response.response = message
    return response
Beispiel #23
0
def catch_http_exception(e):
    response = Response()
    response.data = json.dumps({
        'status': 'failure',
        'message': e.description,
        'code': e.code
    })
    response.content_type = 'application/json'

    return response, e.code
Beispiel #24
0
def catch_exception(e):
    response = Response()
    response.data = json.dumps({
        'status': 'failure',
        'message': str(e),
        'code': 500
    })
    response.content_type = 'application/json'

    return response, 500
Beispiel #25
0
def get_imp(optimal_ct, xmin, ymin, xmax, ymax):
    """
    The client doesn't know which imp to use. It can call this function.
    """
    env = Envelope(*map(float, [xmin, ymin, xmax, ymax]), srid=3857)
    imp = map_bbox_imp(env, optimal_ct, DATASET)
    imp = dumps({"imp": imp})
    res = Response(imp)
    res.content_type = 'application/x-javascript'
    return res
def handle_schema_validation_error(error_messages):

    field_error_msgs = []
    for k in error_messages:
        print(k + ", " + str(error_messages[k]))
        field_error_msgs.append({k: error_messages[k]})
    r = Response()
    r.status_code = 400
    r.content_type = 'application/json'
    r.data = json.dumps(generate_response_wrapper(None, field_error_msgs=field_error_msgs))
    return r
Beispiel #27
0
def view_file(uuid):
    try:
        file = File.get(File.uuid == uuid)
    except File.DoesNotExist:
        return abort(404)
    if not file.encrypted:
        print(request.headers.get('if-none-match'), file.hash,
              request.headers.get('if-none-match') == file.hash)
        if request.headers.get('if-none-match') == f'"{file.hash}"':
            resp = Response('')
            resp.status_code = 304
            resp.set_etag(file.hash, False)
            resp.cache_control.max_age = 5
            resp.cache_control.public = True
            return resp
        resp = Response(file.content)
        resp.content_type = file.mimetype
        resp.headers.set('Content-Disposition',
                         'attachment',
                         filename=file.filename)
        resp.cache_control.max_age = 5
        resp.cache_control.public = True
        resp.set_etag(file.hash, False)
        return resp
    else:
        if request.method == 'GET':
            return render_template('unlock-file.html', file=file), 401
        elif request.method == 'POST':
            try:
                content = file.decrypt(request.form['password'])
            except ValueError:
                return render_template('unlock-file.html',
                                       file=file,
                                       error=True)
            resp = Response(content)
            resp.content_type = file.mimetype
            resp.headers.set('Content-Disposition',
                             'attachment',
                             filename=file.filename)
            # not setting cache-control or etag because this is in response to a POST
            return resp
Beispiel #28
0
def generate_png(story_id):
    story = Story.query.get_or_404(story_id)
    res = Response()
    g = Digraph(story.name)
    for step in story.steps:
        if step.final:
            g.node('step_%d' % step.id, label=step.name, color="lightblue2", style="filled")
        else:
            g.node('step_%d' % step.id, label=step.name)
        if step.first_choice_step_id:
            g.edge('step_%d' % step.id, 'step_%d' % step.first_choice_step_id, label = step.first_choice)
        if step.second_choice_step_id:
            g.edge('step_%d' % step.id, 'step_%d' % step.second_choice_step_id, label = step.second_choice)
    if str(request.url_rule).endswith('dot'):
        res.content_type = "text/plain"
        res.data = g.source
    elif str(request.url_rule).endswith('png'):
        g.format = 'png'
        res.content_type = 'image/png'
        res.data = g.pipe()
    return res
Beispiel #29
0
def response(message):
    """! Wrapper for HTTP responses.

    @param message  The content of the successful (200) HTTP response.

    @return  Flask HTTP response object with content of message from the
    argument and status code 200.
    """
    res = Response(json.dumps(message))
    res.status_code = 200
    res.content_type = "application/json"
    return res
Beispiel #30
0
    def __metrics(self):
        start_time = time.time()

        @after_this_request
        def to_do_after_this_request(response):
            record_log(request, response, logger=self.__http_logger)
            self.__record_metrics(start_time, request, response)
            return response

        resp = Response()
        try:
            resp.status_code = HTTPStatus.OK
            resp.content_type = CONTENT_TYPE_LATEST
            resp.data = generate_latest(self.__metrics_registry)
        except Exception as ex:
            resp.status_code = HTTPStatus.INTERNAL_SERVER_ERROR
            resp.content_type = 'text/plain; charset="UTF-8"'
            resp.data = '{0}\n{1}'.format(resp.status_code.phrase, resp.status_code.description)
            self.__logger.error(ex)

        return resp
Beispiel #31
0
def search():
    print "data:", request.data
    data = json.loads(request.data)
    
    images = []
    
    for color in data["colors"]:
        for image_name in image_index.search(color[0], color[1], color[2], data.get("count", 10)):
            images.append("/static/data/i/product/100/0/%s" % image_name)
    
    response = Response(json.dumps({"images":images}))
    response.content_type = "application/json"
    return response
Beispiel #32
0
    def __root(self):
        start_time = time.time()

        @after_this_request
        def to_do_after_this_request(response):
            record_log(request, response, logger=self.__http_logger)
            self.__record_metrics(start_time, request, response)
            return response

        resp = Response()

        try:
            resp.status_code = HTTPStatus.OK
            resp.content_type = 'text/plain; charset="UTF-8"'
            resp.data = NAME + ' ' + VERSION + ' is running.\n'
        except Exception as ex:
            resp.status_code = HTTPStatus.INTERNAL_SERVER_ERROR
            resp.content_type = 'text/plain; charset="UTF-8"'
            resp.data = '{0}\n{1}'.format(resp.status_code.phrase, resp.status_code.description)
            self.__logger.error(ex)

        return resp
Beispiel #33
0
def api_task(task_id=0):
    response = Response()
    response.content_type = 'application/json;charset=UTF-8'
    if request.method == 'DELETE':
        Task.delete(id_=task_id)
        response.response = json.dumps({'error': False, 'deleted': True, 'id_': task_id})
    elif request.method == 'GET':
        response.response = json.dumps(
            Task.list(column=request.args.get('column', 'A'))
        )
    else:
        task = Task(request.data)
        task.save()
        json_response = dict()
        json_response['error'] = False
        json_response['data'] = task.to_dict
        response.response = json.dumps(json_response)
    return response
Beispiel #34
0
def display_history_png(instance_id):
    instance = InstanceStory.query.get_or_404(instance_id)
    if not is_obj_of_current_user(instance):
        return abort(403)
    histories = instance.history.order_by(HistoryInstance.timestamp.asc()).all()
    res = Response()
    g = Digraph(instance.story.name)
    step_ids = []
    for history in histories:
        if history.from_step_id and not history.from_step_id in step_ids:
            step_ids.append(history.from_step_id)
        if history.to_step_id and not history.to_step_id in step_ids:
            step_ids.append(history.to_step_id)

    steps_tmp = Step.query.filter(Step.id.in_(step_ids))
    steps = {}
    for step in steps_tmp:
        steps[step.id] = step

    for history in histories:
        if history.from_step_id and not history.from_step_id in steps:
            step = Step.query.get(history.from_step_id)
            steps[history.from_step_id] = step
        if history.to_step_id and not history.to_step_id in steps:
            step = Step.query.get(history.to_step_id)
            steps[history.to_step_id] = step
    for step_id in steps:
        step = steps[step_id]
        if step.final:
            g.node('step_%d' % step.id, label=step.name, color="lightblue2", style="filled")
        else:
            g.node('step_%d' % step.id, label=step.name)

    index = 1
    for history in histories:
        if history.from_step_id:
            g.edge('step_%d' % history.from_step_id, 'step_%d' % history.to_step_id, label = "%d. %s" % (index, history.choice_text))
            index += 1

    g.format = 'png'
    res.content_type = "image/png"
    res.data = g.pipe()
    return res
    def do(self, action, options=None):
        """
        This method executes the defined action in the given event.

        :param action:
        :param options: Contains the flask parameters g, request, response
            and the handler_def configuration
        :type options: dict
        :return:
        """
        g = options.get("g")
        request = options.get("request")
        handler_def = options.get("handler_def")
        handler_options = handler_def.get("options", {})

        if action == ACTION_TYPE.FORWARD:
            server_def = handler_options.get("privacyIDEA")
            pi_server = get_privacyideaserver(server_def)

            # the new url is the configured server url and the original path
            url = pi_server.config.url + request.path
            # We use the original method
            method = request.method
            tls = pi_server.config.tls
            # We also transfer the original payload
            data = request.all_data
            if handler_options.get("forward_client_ip"):
                data["client"] = g.client_ip
            if handler_options.get("realm"):
                data["realm"] = handler_options.get("realm")
            if handler_options.get("resolver"):
                data["resolver"] = handler_options.get("resolver")

            log.info(u"Sending {0} request to {1!r}".format(method, url))
            requestor = None
            params = None
            headers = {}

            # We need to pass an authorization header if we forward administrative requests
            if handler_options.get("forward_authorization_token"):
                auth_token = request.headers.get('PI-Authorization')
                if not auth_token:
                    auth_token = request.headers.get('Authorization')
                headers["PI-Authorization"] = auth_token

            if method.upper() == "GET":
                params = data
                data = None
                requestor = requests.get
            elif method.upper() == "POST":
                requestor = requests.post
            elif method.upper() == "DELETE":
                requestor = requests.delete

            if requestor:
                r = requestor(url, params=params, data=data,
                              headers=headers, verify=tls)
                # convert requests Response to werkzeug Response
                response_dict = json.loads(r.text)
                if "detail" in response_dict:
                    if response_dict.get("detail") is None:
                        # In case of exceptions we may not have a detail
                        response_dict["detail"] = {"origin": url}
                    else:
                        response_dict.get("detail")["origin"] = url
                # We will modify the response!
                # We can not use flask.jsonify(response_dict) here, since we
                # would work outside of application context!
                options["response"] = Response()
                options["response"].status_code = r.status_code
                options["response"].content_type = "application/json"
                options["response"].data = json.dumps(response_dict)
            else:
                log.warning(u"Unsupported method: {0!r}".format(method))

        return True
Beispiel #36
0
def index(url):
    redata = {}
    format_request_headers = {}
    unfilter_headers = {}

    for i in request.headers:
        format_request_headers[str(i[0]).lower()] = i[1]

    status_code = format_request_headers.get('x-vs-ctrl-status-code', 200)
    content_type = format_request_headers.get('content-type')
    content_random = format_request_headers.get('x-vs-ctrl-body-content-israndom', 'false')
    length = format_request_headers.get('x-vs-ctrl-body-content-length', '-1')
    interval = format_request_headers.get('x-vs-ctrl-response-interval', '-1')
    isclean = format_request_headers.get('x-vs-ctrl-header-isclean', 'false')
    redata = str(request.get_data())

    try:
        if length[-1] == 'k':
            length = int(length[:-1]) * 1024
        elif length[-1] == 'm':
            length = int(length[:-1]) * 1024 * 1024
        else:
            length = int(length)
    except ValueError:
        length = -1

    try:
        interval = int(interval)
    except ValueError:
        interval = -1

    if content_random == "true":
        if length >= 0:
            redata = make_random_str(length)
        else:
            redata = make_random_str(128)
        content_type = "text/plain; charset=utf8"

    resp = Response(redata)

    if length >= 0:
        if length <= len(redata):
            resp.headers['Content-Length'] = length
        elif 0 < len(redata) < length:
            i = length / len(redata)
            j = length % len(redata)
            resp.data = redata * i + redata[:j]
        else:
            resp.headers['Content-Length'] = 0

    if isclean != "true":
        for i in format_request_headers:
            if 'x-vs-ctrl-' not in i and i not in FILTER_HEADERS:
                resp.headers[i] =  format_request_headers[i]

    try:
        resp.status_code = int(status_code)
    except ValueError:
        resp.status = status_code + " unknow"

    resp.content_type = content_type

    if interval >= 0:
        time.sleep(interval)
    return resp