示例#1
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)
示例#2
0
    def on_get(self, req: Request, resp: Response) -> None:
        """GET /v1/solution get solution of specific level from json body."""

        try:
            data = json.loads(req.bounded_stream.read())
            user = self.session.query(User).filter(
                User.uuid == data["uuid"]).first()

            if not user:
                resp.status = falcon.HTTP_404
                return

            level_id = data["level"]

            level = self.session.query(Level).filter(
                Level.id == level_id).first()
            if level:
                resp.status = falcon.HTTP_200
                resp.body = level.json()
                return

            resp.status = falcon.HTTP_404

        except Exception:
            self.session.rollback()
            self.session.close()
            resp.status = falcon.HTTP_400
示例#3
0
    def on_put_user(self, req: falcon.Request, resp: falcon.Response,
                    user_id: str):
        # parse inputs - get data
        try:
            path_data = schema.UserPathParamSchema().load({"user_id": user_id})
        except marshmallow.ValidationError as err:
            resp.media = {"error": dict(err.messages)}
            resp.status = falcon.HTTP_400
            return

        # parse inputs - json data
        try:
            body_data = schema.UserSchema().load(req.params)
        except marshmallow.ValidationError as err:
            resp.media = {"error": dict(err.messages)}
            resp.status = falcon.HTTP_400
            return

        # do business logic
        try:
            output = self.controller.update_user(path_data, body_data)
        except errors.ErrorWithStatus as err:
            output = {"error": str(err)}
            resp.status_code = err.status_code

        # format and return output
        resp.media = output
示例#4
0
    def on_post(self, req: Request, resp: Response):
        try:
            params = json.loads(req.stream.read(req.content_length or 0))
        except (TypeError, ValueError):
            resp.status = HTTP_BAD_REQUEST
            return

        schema_class = self.get_list_schema_class()

        with scoped_session() as session:
            query = self._apply_permissions(req, {'method': 'list'},
                                            self.get_base_query(session))
            count = query.count()
            if issubclass(self.model_class, SoftDelete):
                query = query.filter(self.model_class.deleted == false())
            try:
                query = self.__apply_selector(query, params)
            except InvalidSelectorException as e:
                resp.status = HTTP_BAD_REQUEST
                resp.body = json.dumps({'error': e.message})
                return
            query = self._apply_sort(query, params)
            query = self._apply_limit(query, params)
            query = self._apply_offset(query, params)
            from sqlalchemy.dialects import postgresql
            print(str(query.statement.compile(dialect=postgresql.dialect())))
            items = schema_class().dump(query, many=True)
        resp.body = json.dumps({'count': count, 'results': items.data})
    def on_post(self, req: falcon.Request, res: falcon.Response) -> None:
        payload = json.loads(req.stream.read())

        if 'img' not in payload:
            res.status = falcon.HTTP_400
            res.body = json.dumps({"title": "Missing parameter", "description": "The \"img\" parameter is required."})
            return

        img = payload['img']
        try:
            mediatype, imgbytes = parse(img)
        except ValueError as e:
            res.status = falcon.HTTP_400
            res.body = json.dumps({"title": "Invalid \"img\" parameter", "description": str(e)})
            return

        started = time.time()
        result = self.infer_fn(imgbytes)
        elapsed = time.time() - started

        body = {
            'result': result,
            'infer_secs': elapsed
        }
        res.status = falcon.HTTP_200
        res.body = json.dumps(body, ensure_ascii=False)
示例#6
0
    def on_post(self, req: Request, res: Response):
        username = req.media.get("username")
        password = req.media.get("password")
        print(username, password)
        if username == None or password == None:
            res.status = HTTP_401
            res.body = json.dumps({
                "error":
                True,
                "message":
                "One or more required params were not provided!"
            })
            return

        username_is_available = self.__username_is_available(username)
        print(username_is_available)
        if username_is_available == False:
            res.status = HTTP_409
            res.body = json.dumps({
                "error": True,
                "message": "Username already in use!"
            })
            return

        self.__insert_user(username, password)

        res.status = HTTP_201
        res.body = json.dumps({"success": True})
示例#7
0
    def on_post(self, req: Request, resp: Response, *, paper_id: str,
                layer_id: str, bbx_id: str):
        session = Session(bind=SQL_ENGINE)
        paper = self.tkb.get_paper(session, paper_id)
        annot = paper.get_annotation_layer(layer_id)

        print("loaded layer")
        if bbx_id != "":
            resp.status = "405 Method Not Allowed"
            return
        params = json.load(req.stream)
        try:
            page = int(params["pageNum"])
            min_h = float(params["minH"])
            min_v = float(params["minV"])
            max_h = float(params["maxH"])
            max_v = float(params["maxV"])
            label = params["label"]
        except (KeyError, ValueError):
            resp.status = "400 Bad Request"
            return

        print("parsed params.")
        box = LabelledBBX(label, 0, page, min_h, min_v, max_h, max_v)
        id = annot.add_box(box)
        annot.save()
        resp.media = box.to_web(id, paper_id, layer_id)

        # refresh title.
        info = paper.get_annotation_info(layer_id)
        if info.class_ == "header":
            paper.title = "__undef__"

        session.commit()
        session.close()
示例#8
0
    def on_get(self, req: Request, resp: Response) -> None:
        """GET /v1/level request for all available levels."""

        try:
            data = json.loads(req.bounded_stream.read())
            user = self.session.query(User).filter(User.uuid == data["uuid"]).first()
            if not user:
                resp.status = falcon.HTTP_404
                return
            level_id = data["level"]

            if level_id == "-1":
                levels = self.session.query(Level.id).all()
                levels = [x[0] for x in levels]
                resp.status = falcon.HTTP_200
                resp.media = levels

            else:
                level = self.session.query(Level).filter(Level.id == level_id).first()
                level.solution = ""
                resp.status = falcon.HTTP_200
                resp.body = level.json()

        except Exception:
            self.session.rollback()
            self.session.close()
            resp.status = falcon.HTTP_400
示例#9
0
    def on_get_doc(self, resp: Response, obj_id=None):
        if obj_id is None:
            resp.status = HTTP_METHOD_NOT_ALLOWED
            return

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

        with scoped_session() as session:
            change = session.query(Change).filter(Change.id == cid).first()
            if change is None:
                resp.status = HTTP_NOT_FOUND
                return

            obj = self.__get_object_dump_by_change(session, change)

            if obj is None:
                resp.status = HTTP_NOT_FOUND
                return

        resp.status = HTTP_OK
        resp.body = json.dumps(obj)
示例#10
0
    def on_post(self, req: Request, resp: Response) -> None:
        """Post /v1/user register new user by only simple uuid"""

        try:
            data = json.loads(req.bounded_stream.read())
            user = self.session.query(User).filter(
                User.uuid == data["uuid"]).first()

            if user:
                resp.status = falcon.HTTP_200  # This is the default status
                resp.body = user.json()

            else:
                new_user = User()
                new_user.uuid = data["uuid"]
                self.session.add(new_user)
                self.session.commit()

                resp.status = falcon.HTTP_200  # This is the default status
                resp.body = new_user.json()

        except Exception as err:
            print(err)
            self.session.rollback()
            self.session.close()
            resp.status = falcon.HTTP_400
示例#11
0
    def on_put(self, req: falcon.Request, resp: falcon.Response, user_id: str,
               note_id: str):
        user: User = req.user
        if user_id != str(user.uuid):
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.body = 'Attempting to update another user\'s data'
            return

        try:
            payload = json_util.loads(req.bounded_stream.read())
            note_filter = {'_id': ObjectId(note_id), 'user': ObjectId(user_id)}
            data = {
                '$set': {
                    'text': payload.get('text', ''),
                    'dateModified': datetime.now()
                }
            }
        except json.JSONDecodeError:
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.body = 'Invalid payload provided'
            return

        try:
            self._notes.update_one(note_filter, data)
        except WriteError:
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.body = 'The provided payload failed to pass validation'
            return
示例#12
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
示例#13
0
    def authorize_request(self, request: falcon.Request,
                          response: falcon.Response):
        uri, http_method, body, headers = extract_params(request)
        scope = request.params.get('scope') or ''
        scopes = scope.split()
        credentials = dict(
            client_id=request.params.get('client_id'),
            redirect_uri=request.params.get('redirect_uri', None),
            response_type=request.params.get('response_type', None),
            state=request.params.get('state', None))
        log.debug('Fetched credentials from request %r.', credentials)

        try:
            headers, body, status = self._auth_endpoint.create_authorization_response(
                uri, http_method, body, headers, scopes, credentials)
            log.debug('Authorization successful.')
        except FatalClientError as e:
            log.debug('Fatal client error %r', e)
            response.status = falcon.HTTP_SEE_OTHER
            response.set_header('Location', e.in_uri(self.error_url))
        except OAuth2Error as e:
            log.debug('OAuth2Error: %r', e)
            response.status = falcon.HTTP_SEE_OTHER
            response.set_header('Location', e.in_uri(self.error_url))
        else:
            patch_response(response, headers, body, status)
示例#14
0
    def on_post(self, req: Request, resp: Response, *, paper_id: str,
                layer_id: str):

        if layer_id != "":
            resp.status = falcon.HTTP_BAD_REQUEST
            return

        try:
            session = Session(bind=SQL_ENGINE)
            paper = self.tkb.get_paper(session, paper_id)
            params = json.load(req.stream)

            if "extractor" in params:
                extractor_name = params["extractor"]
                extractor_id = params["class"] + "." + extractor_name
                extractor = self.tkb.extractors[extractor_id]
                new_layer = extractor.apply_and_save(paper,
                                                     params.get("reqs", []))

                if params["class"] == "header":
                    paper.title = "__undef__"
            else:
                new_layer = paper.add_annotation_layer(params["class"])

            session.commit()

            resp.media = new_layer.to_web()

            session.close()

        except ParentModelNotFoundException as e:
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.media = {"message": str(e)}
示例#15
0
    def on_get_changes(self, req: Request, resp: Response):
        since = req.get_param_as_int('since', required=False, default=0)
        batch_size = req.get_param_as_int('batch_size',
                                          required=False,
                                          default=50)

        i = 0
        end = False
        items = []
        with scoped_session() as session:
            while i < batch_size and not end:
                obj = session.query(Change).filter(Change.id > since).first()
                if obj is None:
                    end = True
                    break
                item, errors = ChangeSchema().dump(obj)

                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

                if self.__can_read_change(req, item):
                    items.append(item)

                since = since + 1
                i = i + 1

        resp.status = HTTP_OK
        resp.body = json.dumps(items)
示例#16
0
    def on_post_change(self, req: Request, resp: Response):
        try:
            input_data = json.loads(req.stream.read(req.content_length or 0))
        except (ValueError, KeyError):
            resp.status = HTTP_BAD_REQUEST
            return

        changes, errors = UpwardChangeSchema().load(input_data, many=True)
        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

        results = []
        for change in changes:
            try:
                res, conflict = self.__process_upward_change(change)
            except (exc.FixedModel, exc.InvalidSyncEntry,
                    exc.InvalidSyncEntryType, exc.InvalidSyncModel,
                    exc.ModelNotFound):
                resp.status = HTTP_BAD_REQUEST
                resp.body = json.dumps({'errors': errors})
                return

            results.append(res)
            if conflict:
                resp.status = HTTP_CONFLICT
                resp.body = json.dumps(results)

        resp.status = HTTP_OK
        resp.body = json.dumps(results)
示例#17
0
    def on_post_docs(self, req: Request, resp: Response):
        try:
            input_data = json.loads(req.stream.read(req.content_length or 0))
            changes_ids = [int(c) for c in input_data['changes']]
        except (ValueError, KeyError):
            resp.status = HTTP_BAD_REQUEST
            return

        if changes_ids is None:
            resp.status = HTTP_BAD_REQUEST
            return

        results = []
        with scoped_session() as session:
            changes = session.query(Change).filter(
                Change.id.in_(changes_ids)).all()

            for change in changes:
                obj = self.__get_object_dump_by_change(session, change)
                if obj is None:
                    continue

                change_dump, _ = ChangeSchema().dump(change)
                change_dump.update({'object': obj})
                results.append(change_dump)

        resp.status = HTTP_OK
        resp.body = json.dumps(results)
示例#18
0
    def on_post(self, req: Request, resp: Response) -> None:
        """POST /v1/user/level request to check a solution for specific level id."""
        try:

            data = json.loads(req.bounded_stream.read())
            user = self.session.query(User).filter(User.uuid == data["uuid"]).first()
            if user:
                level = (
                    self.session.query(Level).filter(Level.id == data["level"]).first()
                )
                if level:
                    done = self.check(level.numbers, level.goal, data["solution"])
                    if done:
                        user.completed = list(user.completed)
                        if level.id not in user.completed:
                            user.completed.append(level.id)
                            self.session.add(user)
                            self.session.commit()

                        resp.status = falcon.HTTP_200
                        return
            resp.status = falcon.HTTP_404

        except Exception:
            self.session.rollback()
            self.session.close()
示例#19
0
    def authorize_request(self, request: falcon.Request, response: falcon.Response):
        uri, http_method, body, headers = extract_params(request)
        scope = request.params.get('scope') or ''
        scopes = scope.split()
        credentials = dict(
            client_id=request.params.get('client_id'),
            redirect_uri=request.params.get('redirect_uri', None),
            response_type=request.params.get('response_type', None),
            state=request.params.get('state', None)
        )
        log.debug('Fetched credentials from request %r.', credentials)

        try:
            headers, body, status = self._auth_endpoint.create_authorization_response(
                uri, http_method, body, headers, scopes, credentials)
            log.debug('Authorization successful.')
        except FatalClientError as e:
            log.debug('Fatal client error %r', e)
            response.status = falcon.HTTP_SEE_OTHER
            response.set_header('Location', e.in_uri(self.error_url))
        except OAuth2Error as e:
            log.debug('OAuth2Error: %r', e)
            response.status = falcon.HTTP_SEE_OTHER
            response.set_header('Location', e.in_uri(self.error_url))
        else:
            patch_response(response, headers, body, status)
示例#20
0
 def on_post(self, req: Request, resp: Response, snap_id: UUID):
     result = self._resource_manager.create_monitor(req.media['id'])
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = result.json()
         resp.status = falcon.HTTP_201
示例#21
0
 def on_get(self, req: Request, resp: Response):
     monitors = self._resource_manager.monitors()
     if isinstance(monitors, Exception):
         resp.body = json.dumps(dict(error=str(monitors)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = json.dumps(monitors)
         resp.status = falcon.HTTP_201
示例#22
0
 def on_get(self, _: Request, resp: Response, model_id: UUID):
     result = self._model_manager.update_model(model_id)
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = json.dumps(dict(result), cls=DataclassJSONEncoder)
         resp.status = falcon.HTTP_201
示例#23
0
 def on_delete(self, _: Request, resp: Response, model_id: UUID):
     result = self._model_manager.delete_model(model_id)
     if isinstance(result, Model):
         resp.body = result.json()
         resp.status = falcon.HTTP_202
     else:
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_404
示例#24
0
 def on_get(self, _: Request, resp: Response, dataset_id: UUID):
     result = self._dataset_manager.get_dataset(dataset_id)
     if isinstance(result, Dataset):
         resp.body = result.json()
         resp.status = falcon.HTTP_202
     else:
         resp.body = json.dumps(dict(error=result))
         resp.status = falcon.HTTP_404
示例#25
0
 def on_delete(self, _: Request, resp: Response, snap_id: UUID):
     result = self._resource_manager.remove_monitor(snap_id)
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_404
     else:
         resp.body = result.json()
         resp.status = falcon.HTTP_202
示例#26
0
 def on_delete(self, req, resp: falcon.Response, id):
     """ Default method DELETE """
     try:
         resp.media = self.response.success(self.service.delete(id))
         resp.status = falcon.HTTP_200
     except Exception as exception:
         resp.media = self.response.error(exception.__str__())
         resp.status = falcon.HTTP_500
示例#27
0
 def on_post(self, req: Request, resp: Response):
     result = self._model_manager.import_model(req)
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = result.json()
         resp.status = falcon.HTTP_201
示例#28
0
 def on_get(self, _: Request, resp: Response, model_id: UUID):
     result = self._model_manager.model_version_count(model_id)
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = json.dumps(dict(count=result))
         resp.status = falcon.HTTP_200
示例#29
0
    def falcon_handler(_: f.Request, resp: f.Response, ex, _params):
        r: Response = handler(ex)

        if isinstance(ex, f.HTTPError):
            resp.status = ex.status
        else:
            resp.status = r.status_string
        resp.body = r.text
示例#30
0
 def on_get(self, req: Request, resp: Response):
     result = self._method_manager.count_methods()
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = json.dumps(dict(count=result))
         resp.status = falcon.HTTP_201
示例#31
0
 def on_post(self, req: Request, resp: Response):
     result = Result.from_json(req.media['Result'])
     result = self._result_manager.replace(result)
     if isinstance(result, Exception):
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = json.dumps(asdict(result), cls=DataclassJSONEncoder)
         resp.status = falcon.HTTP_201
示例#32
0
def patch_response(resp: falcon.Response, headers, body, status):
    if body:
        resp.body = body
    resp.set_headers(headers)
    if isinstance(status, int):
        status = getattr(falcon, 'HTTP_{}'.format(status))
    resp.status = status
    return resp
示例#33
0
    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()
示例#34
0
    def on_post(self, req: falcon.Request, resp: falcon.Response, dash_id):

        api_key, data = extract_payload(req)

        if not authenticate_request(req, api_key, dash_id):
            raise falcon.HTTPError(falcon.HTTP_401)

        dash = Dash.get(Dash.dash_id == dash_id)

        if dash.num_records > 10 ** 5:
            raise falcon.HTTPBadRequest

        schema = {
            "type": "object",
            "properties": {
                "key": {
                    "type": "string",
                    "maxLength": 32
                },
                "value": {
                    "type": "number"
                }
            },
            "required": ["key", "value"]
        }

        try:
            jsonschema.validate(data, schema)
        except:
            raise falcon.HTTPBadRequest

        with db.transaction():
            event = Event()
            event.dash_id = dash
            event.key = data['key']
            event.val = data['value']
            event.save()

            dash.num_records += 1
            dash.save()

        resp.status = falcon.HTTP_201