예제 #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 on_get(self,
            req: falcon.Request,
            resp: falcon.Response,
            resource_id=None):
     resp.body = self.html
     resp.content_type = falcon.MEDIA_HTML
     resp.status = falcon.HTTP_200
    def on_get(self, req: Request, resp: Response, name: str, number: str):
        check_folio_scope(req.context.user, name)
        file = self._finder.find_folio(Folio(name, number))

        resp.content_type = file.content_type
        resp.content_length = file.length
        resp.stream = file
예제 #4
0
    def __get_item(self, req: Request, resp: Response, obj_id):
        resp.content_type = MEDIA_JSON

        try:
            nid = int(obj_id)
        except (TypeError, ValueError):
            resp.status = HTTP_BAD_REQUEST
            resp.body = '{"message": "Invalid id"}'
            return

        schema_class = self.__get_schema_class('get')

        with scoped_session() as session:
            query = self._apply_permissions(req, {'method': 'get'},
                                            self.get_base_query(session))
            qf = [
                self.model_class.id == nid,
            ]
            if issubclass(self.model_class, SoftDelete):
                qf.append(self.model_class.deleted == false())
            q = query.filter(*qf)
            q = self._apply_permissions(req, {'method': 'get'}, q)
            instance = q.first()
            if instance is None:
                resp.status = HTTP_NOT_FOUND
                return
            item, _ = schema_class().dump(instance)
        resp.status = HTTP_OK
        resp.body = json.dumps(item)
예제 #5
0
    def write_response(req: Request, res: Response) -> None:
        res.content_type = 'application/cbor'
        res.set_header('Access-Control-Allow-Origin', '*')

        if req.path.endswith('/_entry-names'):
            path = root_dir / req.path[1:-len('/_entry-names')]
            if path.is_file(): raise HTTPStatus(HTTP_404)
            res.data = cbor2.dumps(dict(
                type='plain-object',
                content=sorted([
                    re.sub(r'\.h5$', '', p.name) + ('/' if p.is_dir() else '')
                    for p in path.glob('[!_]*')
                ])
            ))

        elif req.path.endswith('/_meta'):
            key = req.path[1:-len('/_meta')]
            res.data = cbor2.dumps(_read_meta(root_dir, key))

        else:
            t_last = float(req.get_param('t_last') or 0) / 1000
            entry = _read(root_dir, req.path[1:], t_last)
            if entry['type'] == 'file':
                res.data = (root_dir / entry['content']).read_bytes()
            else:
                res.data = cbor2.dumps(entry)

        res.status = HTTP_200
예제 #6
0
def image_response(image: Image.Image, resp: falcon.Response) -> None:
    resp.content_type = "image/jpeg"
    fp = io.BytesIO()
    image.save(fp, "JPEG")
    resp.stream_len = fp.tell()
    fp.seek(0)
    resp.stream = fp
예제 #7
0
파일: views.py 프로젝트: RusJr/kiwi_com
    def on_get(self, req: Request, resp: Response):
        calendars = REDIS.list_all_calendars()
        calendars = [c.to_dict() for c in calendars]

        content = TABLE_TEMPLATE.render(calendars=calendars)
        resp.body = content
        resp.content_type = 'text/html'
예제 #8
0
파일: beta.py 프로젝트: MujiP/DarkThunder
 def on_get(self, req: falcon.Request, resp: falcon.Response):
     resp.status = falcon.HTTP_302
     resp.content_type = 'text'
     beta_link = r'https://testflight.apple.com/join/e05hgsxP?fbclid=IwAR2Trl0qZ9pFvEaKjQq2aVvAwJC8IwjPUaEGrJJWls1HiER2MgjE-wCw0MM'
     resp.location = beta_link
     resp.body = r'Please follow this link to access the beta: {}'.format(
         beta_link)
예제 #9
0
    def on_post(self, req: falcon.Request, resp: falcon.Response,
                event_id: str, person_id: str):
        '''
        Add a person to an event.

        HTTP response codes:
        200 if successful
        404 if event doesn't exist
        403 if event is at its max occupancy
        '''
        event_data = get_event_data(event_id)
        if event_data == {}:
            resp.status = falcon.HTTP_404
        elif 'maxOccupancy' in event_data and (len(
                get_people(event_id)) >= int(event_data['maxOccupancy'])):
            resp.status = falcon.HTTP_403
            resp.content_type = 'text/html'
            resp.body = '''
                <html>
                    <head>
                        <title>Forbidden</title>
                    </head>
                    <body>
                        <h1><p>The requested event has reached its maximum occupancy.</p></h1>
                        
                    </body>
                </html>
                '''

        else:
            conn.sadd(event_id + ':people', person_id)
            conn.sadd('person:' + person_id, event_id)
            resp.status = falcon.HTTP_200
예제 #10
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)
예제 #11
0
 def on_get(self, _: Request, resp: Response) -> None:
     """GET / simple page."""
     resp.status = falcon.HTTP_200
     resp.content_type = falcon.MEDIA_HTML
     resp.body = (
         "<!DOCTYPE html><html><body><h1>Number Game</h1>"
         "<p>Welcome to Number game</p></body></html>"
     )
예제 #12
0
 def on_get(self, req: Request, resp: Response):
     try:
         resp.media = prepare_list_to_json(
             self._resource_use_cases.get_all())
         resp.content_type = falcon.MEDIA_JSON
         resp.status = falcon.HTTP_OK
     except Exception as ex:
         raise falcon.HTTPError(str(ex))
예제 #13
0
def respond_with_remplate(template_name, resp: Response):
    """Load a template using jinja2 and fill out the falcon response with
    said template (including the expected content type"""
    template = load_template(template_name)
    resp.status = falcon.HTTP_200
    resp.content_type = "text/html"
    resp.body = template.render()
    return resp
예제 #14
0
    def on_get(self, req: Request, resp: Response, primary_key: int):
        found_entity = self._resource_use_cases.find(primary_key=primary_key)

        if found_entity == None:
            raise falcon.HTTPNotFound()

        resp.media = found_entity.to_dict()
        resp.content_type = falcon.MEDIA_JSON
        resp.status = falcon.HTTP_OK
예제 #15
0
 def create_response(data,
                     status_code=200,
                     content_type='application/json'):
     options = ResponseOptions()
     resp = Response(options)
     resp.body = data
     resp.content_type = content_type
     resp.status = HTTP_200
     return resp
예제 #16
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')
예제 #17
0
 def handle(ex: HTTPErrorDetail, req: falcon.Request, resp: falcon.Response, params):
     resp.status = ex.status
     resp.content_type = 'application/problem+json'
     if not ex.error_detail.instance:
         ex.error_detail.instance = req.uri
     resp.body = json.dumps(ex.to_dict())
     if ex.extra_headers:
         for key, value in ex.extra_headers.items():
             resp.set_header(key, value)
 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')
예제 #19
0
    def on_get_download(self, req, resp: falcon.Response, app_name):
        app = self.repo.get_app(app_name)
        if not app:
            raise falcon.HTTPNotFound()

        resp.content_type = 'application/zip'
        with open(app.archive_path, 'rb') as fd:
            resp.body = fd.read()

        resp.downloadable_as = app.archive_path.split('/')[-1]
예제 #20
0
    def on_get(self, req: Request, resp: Response):
        consent = MessageApiCall.consent(req)

        self.req_to_message(req, resp, consent=consent)

        self.set_retargeting_segment(req, resp, consent=consent)

        resp.content_type = falcon.MEDIA_GIF
        resp.content_length = self.pixel_size
        resp.data = self.pixel_bytes
        resp.status = falcon.HTTP_200
예제 #21
0
    def on_get(self, req: Request, resp: Response):
        if req.params.get("tr"):
            user_uuid = self.req_to_message(req, resp)
        else:
            user_uuid = self.assign_uuid(req, resp)

        var_name = req.params.get("vn", "thcObj")
        key_name = req.params.get("kn", "technic")
        resp.body = f"""var {var_name} = {{"{key_name}": "{user_uuid}"}};"""
        resp.content_type = falcon.MEDIA_JS
        resp.status = falcon.HTTP_200
예제 #22
0
 def create_response(data,
                     status_code=200,
                     headers=None,
                     content_type="application/json"):
     options = ResponseOptions()
     resp = Response(options)
     resp.body = data
     resp.content_type = content_type
     resp.status = HTTP_200
     resp.set_headers(headers or {})
     return resp
예제 #23
0
 def on_get(self, _req: Request, resp: Response, *, paper_id: str):
     session = Session(bind=SQL_ENGINE)
     paper = self.tkb.get_paper(session, paper_id)
     session.close()
     try:
         pdf = open(paper.pdf_path, "rb")
         resp.stream = pdf
         resp.content_length = os.path.getsize(paper.pdf_path)
         resp.content_type = "application/pdf"
     except Exception as e:
         resp.media = str(e)
         resp.status = "400"
예제 #24
0
    def on_post(self, req: Request, resp: Response, *, eid: int = 0) -> None:
        if not eid == 0:
            raise ValueError()
        e = Estimator(self._lm)
        eid = id(e)
        self._estimators[eid] = e

        resp.data = json.dumps(
            {'eid': eid}
        ).encode('utf-8')
        resp.content_type = MEDIA_JSON
        resp.status = HTTP_201
        return
예제 #25
0
 def on_post(self, req: Request, resp: Response):
     """Unprotected user login endpoint.
     ---
     post:
         description: Logs an existing user returning valid tokens
         consumes: ["json"]
         parameters:
         -   in: body
             name: credentials
             description: The username and password chosen during the registration
             schema: {}
             required: true
         responses:
             200:
                 description: Tokens needed for authorization and refresh token
                 schema: TokenPayloadSchema
             401:
                 description: Submitted invalid credentials
     """
     resp.content_type = MEDIA_JSON
     try:
         params = json.loads(req.stream.read(req.content_length or 0))
         username = params['username']
         password = params['password']
     except (KeyError, TypeError, ValueError):
         resp.body = '{"message": "Please provide username and password"}'
         resp.status = HTTP_BAD_REQUEST
         return
     user = authenticate_user(username, password)
     if user is None:
         resp.body = '{"message": "Invalid credentials"}'
         resp.status = HTTP_BAD_REQUEST
         return
     payload = TokenPayloadSchema().dump(user)
     payload['token'] = auth_backend.get_auth_token(payload)
     with scoped_session() as session:
         rt = session.query(RefreshToken).filter(
             RefreshToken.user_id == payload['user_id']
         ).first()
         if rt is None:
             rt = RefreshToken(user_id=payload['user_id'])
             session.add(rt)
             session.commit()
         refresh_token = rt.token
         user_instance = session.query(User).filter(User.id == user.id).first()
         payload['user'] = UserSchema().dump(user_instance)
     payload['refresh_token'] = refresh_token
     resp.body = json.dumps(payload)
     resp.status = HTTP_OK
예제 #26
0
    def on_get(self, req: Request, resp: Response, *, eid: int) -> None:
        self._root[eid].finish()

        words = self._root[eid].result

        if words is None:
            raise Exception()

        resp.data = json.dumps({
            'id': eid,
            'result': Word.to_str(words)
        }).encode('utf-8')

        resp.content_type = MEDIA_JSON
        resp.status = HTTP_200
    def on_put(self, req: Request, resp: Response, primary_key: int):
        found_entity = self._resource_use_cases.find(primary_key=primary_key)
        if found_entity == None:
            raise falcon.HTTPNotFound()

        found_entity.fill(region=req.media.get('region'))

        try:
            entity_updated = self._resource_use_cases.update(found_entity)
            resp.media = entity_updated.to_dict()
            resp.content_type = falcon.MEDIA_JSON
            resp.status = falcon.HTTP_OK
        except Exception as ex:
            print(ex)
            raise falcon.HTTPError(falcon.HTTP_500, str(ex))
예제 #28
0
    def process_response(self, req: Request, resp: Response,
                         resource: BaseResource, req_succeeded: bool):
        self.context.logger.debug(
            f'process_response: {resource} {req.method} {req.path}')

        # Default to 'application/json' if responding with an error message
        if req_succeeded and resp.body:
            # candidates should be sorted by increasing desirability
            preferred = req.client_prefers(
                ('application/json', 'application/scim+json'))
            self.context.logger.debug(
                f'Client prefers content-type {preferred}')
            if preferred is None:
                preferred = 'application/scim+json'
                self.context.logger.debug(
                    f'Default content-type {preferred} used')
            resp.content_type = preferred
예제 #29
0
파일: Views.py 프로젝트: hkarasek/iot-dash
    def on_get(self, req: falcon.Request, resp: falcon.Response):
        user_resp = req.get_param('g-recaptcha-response')
        resp.body = templates.get_template('register.html').render()
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'

        if user_resp and verify_recaptcha(user_resp, 'captcha_secret'):
            with db.transaction():
                dash = Dash()
                dash.api_key = hashlib.sha1(os.urandom(2 ** 13)).hexdigest()
                dash.dash_id = hashlib.sha1(os.urandom(2 ** 13)).hexdigest()
                dash.save()
            resp.status = falcon.HTTP_201
            resp.body = templates.get_template('register_after.html').render(api_key=dash.api_key, dash_id=dash.dash_id)
        elif user_resp:
            resp.status = falcon.HTTP_400
            resp.body = templates.get_template('register.html').render()
예제 #30
0
    def prepare_response(
        self,
        resp: falcon.Response,
        result: Dict,
        schema: Optional[marshmallow.Schema] = None,
    ):
        """ Encodes a `result` either via a `marshmallow` schema or standard
            JSON-encoding and adds it to the provided `falcon.Response` object.

        Args:
            resp (falcon.Response): The Falcon `Response` object.
            result (Dict): The result that will be encoded and added to the
                `falcon.Response` object.
            schema (Optional[marshmallow.Schema] = None): The marshmallow
                schema instance that will be used to encode the result.

        Returns:
            falcon.Response: The updated response object.
        """

        try:
            if schema:
                response_json = schema.dumps(result).data
            else:
                response_json = json.dumps(result)
        except marshmallow.ValidationError as exc:
            msg_fmt = "Response body violates schema."
            self.logger.exception(msg_fmt)
            raise falcon.HTTPError(
                status=falcon.HTTP_422,
                title="Schema violation.",
                description=msg_fmt + ". Exception: {0}".format(str(exc))
            )
        except Exception as exc:
            msg_fmt = "Could not encode results '{0}' into JSON".format(result)
            self.logger.exception(msg_fmt)
            raise falcon.HTTPError(
                status=falcon.HTTP_500,
                title="UnhandledError",
                description=msg_fmt + ". Exception: {0}".format(str(exc))
            )

        resp.content_type = "application/json"
        resp.body = response_json

        return resp
예제 #31
0
    def on_post(self, req: Request, resp: Response, *, eid: int) -> None:
        try:
            key_str = req.params['key']
        except Exception:
            raise Exception(req.params)

        klass = TagWord if TagWord.is_include(key_str) else int
        key: Key = Key([klass(key_str)])

        self._root[eid].add(key)
        words = self._root[eid].result

        resp.data = json.dumps({
            'eid': eid,
            'result': Word.to_str(words),
        }).encode('utf-8')
        resp.content_type = MEDIA_JSON
        resp.status = HTTP_200
예제 #32
0
파일: Views.py 프로젝트: hkarasek/iot-dash
 def on_get(self, req: falcon.Request, resp: falcon.Response, dash_id):
     resp.content_type = 'text/html'
     resp.body = templates.get_template('dash.html').render(dash_id=dash_id)