예제 #1
0
    def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
        """
        Falcon GET handler.
        """
        feeds, n, full = parse_qs(req)
        summ = not full
        fm = FeedMixer(feeds=feeds, num_keep=n, prefer_summary=summ,
                       title=self.title, desc=self.desc, link=req.uri,
                       cache=self.cache)

        # dynamically find and call appropriate method based on ftype:
        method_name = "{}_feed".format(self.ftype)
        method = getattr(fm, method_name)
        resp.body = method()

        if fm.error_urls:
            # There were errors; report them in the 'X-fm-errors' http header as
            # a url-encoded JSON hash
            error_dict = {}
            for url, e in fm.error_urls.items():
                err_str = str(e)
                if hasattr(e, 'status'):
                    err_str += " ({})".format(e.status)
                error_dict[url] = err_str
            json_err = urllib.parse.quote(json.dumps(error_dict))
            resp.append_header('X-fm-errors', json_err)

        if self.ftype == 'json':
            # special case content_type for JSON
            resp.content_type = "application/json"
        else:
            resp.content_type = "application/{}+xml".format(self.ftype)
        resp.status = falcon.HTTP_200
예제 #2
0
def json_error_serializer(req: falcon.Request, resp: falcon.Response,
                          exception: BaseApiException):
    # Serialize exception
    resp.body = exception.to_json()

    # Set content type
    resp.content_type = "application/json"
    resp.append_header("Vary", "Accept")
    resp.status = exception.status

    # Setup CORS
    origin = req.headers.get("HTTP_ORIGIN")
    origin2 = req.headers.get("ORIGIN")
    origin = origin2 or origin
    headers = {}

    if settings.get("AWOKADO_DEBUG") or (origin
                                         and origin in settings.ORIGIN_HOSTS):
        headers["Access-Control-Allow-Origin"] = origin

    headers_to_set = settings.get("AWOKADO_ACCESS_CONTROL_HEADERS",
                                  DEFAULT_ACCESS_CONTROL_HEADERS)
    for k, v in headers_to_set:
        headers[k] = v

    resp.set_headers(headers)
예제 #3
0
def json_error_serializer(req: falcon.Request, resp: falcon.Response,
                          exception: falcon.HTTPError):
    resp.body = json.dumps({
        'error': True,
        'message': exception.title,
        'reason': exception.status
    })
    resp.content_type = 'application/json'
    resp.append_header('Vary', 'Accept')
 def on_get(self, req: falcon.Request, resp: falcon.Response):
     url_prepend = req.relative_uri.replace('api.wsgi/', '')
     resp.body = json.dumps({
         'error':
         False,
         'routes':
         [os.path.join(url_prepend, k.lstrip('/')) for k in self._keys]
     })
     resp.content_type = 'application/json'
     resp.append_header('Vary', 'Accept')
예제 #5
0
    def on_post(self, req: Request, resp: Response, obj_id=None):
        """Generic POST endpoint.
        ---
        post:
            description: Adds an object
            consumes: ["json"]
            parameters:
            -   in: body
                name: object
                description: The object being added
                required: true
            responses:
                200:
                    description: Returns created object
                    schema: {}
                400:
                    description: Denies empty payload requests
                401:
                    description: Denies unauthorized requests
        """
        if obj_id is not None:
            resp.status = HTTP_METHOD_NOT_ALLOWED
            return

        schema_class = self.__get_schema_class('post')

        # try:
        with scoped_session() as session:
            input_data = json.loads(req.stream.read(req.content_length or 0))
            if not self._can_create(req, {'method': 'create'}, input_data):
                resp.status = HTTP_METHOD_NOT_ALLOWED
                return
            self._process_create_data(input_data)

            item, errors = schema_class().load(input_data, session=session)
            if errors is not None:
                errors_num = len(errors)
                if errors_num > 0:
                    resp.status = HTTP_BAD_REQUEST
                    resp.body = json.dumps({'errors': errors})
                    return
            session.add(item)
            session.commit()

            self._post_create(session, item)

            itm_id = item.id
            item_dump, _ = schema_class().dump(item)

        resp.status = HTTP_CREATED
        resp.append_header('Location', self.__get_item_url(req, itm_id))
        resp.body = json.dumps(item_dump)
예제 #6
0
파일: admin.py 프로젝트: xianhuawei/utils
    def json_response(self, filename='export.json'):
        serializer = Serializer()
        prepared_query = self.prepare_query()
        field_dict = {}
        for field in prepared_query._select:
            field_dict.setdefault(field.model_class, [])
            field_dict[field.model_class].append(field.name)

        def generate():
            i = prepared_query.count()
            yield '[\n'
            for obj in prepared_query:
                i -= 1
                yield json.dumps(serializer.serialize_object(obj, field_dict))
                if i > 0:
                    yield ',\n'
            yield '\n]'
        Response.append_header('Content-Type', 'application/javascript')
        Response.append_header('Content-Disposition', 'attachment; filename=%s' % filename)
        Response.body = generate();
예제 #7
0
 def on_post(self, req: falcon.Request, resp: falcon.Response):
     auth_data = req.get_header('Authorization')
     try:
         id_info = IdInfo(
             id_token.verify_oauth2_token(auth_data, requests.Request(),
                                          self._client_id))
         user, _ = self.process_id_info(id_info)
         resp.append_header('Authorization',
                            crypto.generate_jwt(user, self._client_id))
     except ValueError as error:
         self._logger.debug('Failed to validate an id token: %s', error)
         resp.status = falcon.HTTP_UNAUTHORIZED
     except AuthProviderMissingUserException as error:
         self._logger.debug(error.message)
         resp.status = falcon.HTTP_INTERNAL_SERVER_ERROR
     except Exception as error:
         self._logger.debug(
             'Something went wrong while processing the session post request: %s',
             error)
         resp.status = falcon.HTTP_INTERNAL_SERVER_ERROR
         raise error
예제 #8
0
def falcon_set_cookie(response: Response,
                      name: str,
                      value: str,
                      same_site: Union[None, str] = '',
                      path: str = None,
                      secure: bool = True,
                      http_only: bool = False,
                      domain: str = settings.SESSION_COOKIE_DOMAIN):
    cookie = SimpleCookie()
    cookie[name] = value
    if same_site is None or same_site:
        cookie[name]['samesite'] = str(same_site)

    if path:
        cookie[name]['path'] = path

    cookie[name]['secure'] = secure
    cookie[name]['httponly'] = http_only
    cookie[name]['domain'] = domain

    response.append_header('Set-Cookie', cookie[name].output(header=''))