예제 #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_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})
예제 #3
0
    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)
예제 #4
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})
예제 #5
0
 def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
     """
     ---
     summary: Get all payments owned by the authenticated user from the DB or all if admin
     tags:
         - Payment
     parameters:
         - in: query
           schema: CoreListSchema
     produces:
         - application/json
     responses:
         200:
             description: All Payments
             schema:
                 type: array
                 items: Payment
         401:
             description: Unauthorized
     """
     user = req.context['user']
     user.export()
     if 'Admin' not in user.role.name:
         rv = self._service.find(owner_id=str(user.id))
         resp.body = self._json_or_404(rv)
     else:
         rv = self._service.all()
         resp.body = self._json_or_404(rv)
예제 #6
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
    def process_response(self, req: falcon.Request, resp: falcon.Response,
                         resource: Resource) -> None:
        try:
            payload = resp.payload
        except AttributeError:
            pass
        else:
            method = req.method.lower()
            schema = self._get_schema(resource, method, "response")

            if not schema and bool(payload):
                resp.body = json.dumps(payload)

            if not schema:
                return

            try:
                data = schema.dumps(payload, many=utils.is_collection(payload))
            except ValidationError as err:
                raise falcon.HTTPInternalServerError(
                    title="Could not serialize response",
                    description=json.dumps(err.messages),
                )

            resp.body = data
예제 #8
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)
예제 #9
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
예제 #10
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)
예제 #11
0
 def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
     """
     For an admin user, this endpoint returns all applications, for a user it
     returns all of the applications they own.
     ---
     summary: Get all Applications from the DB
     tags:
         - Application
     parameters:
         - in: query
           schema: CoreListSchema
     produces:
         - application/json
     responses:
         200:
             description: All Applications
             schema:
                 type: array
                 items: Application
         401:
             description: Unauthorized
     """
     user = req.context['user']
     user.export()
     if not user.is_admin:
         rv = self._service.find(owner_id=str(user.id))
         resp.body = self._json_or_404(rv)
     else:
         rv = self._service.all()
         resp.body = self._json_or_404(rv)
예제 #12
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)
    def on_put(self, req: Request, resp: Response, run_id: str) -> None:
        # Start a run

        if self.workflow.in_progress():
            error = f"Can only run one instance of a workflow at a time, {run_id} rejected."
            log.error(error)
            raise falcon.HTTPError(falcon.HTTP_403, 'Concurrency Error', error)

        log.info("Starting calculations for RUN_ID: " + run_id)

        try:
            if not db.is_valid_run_id(run_id):
                result = {'status': "invalid job id: " + run_id}
                resp.status = falcon.HTTP_401
                resp.body = json.dumps(result)
                return

            thr = threading.Thread(target=self.workflow.run_calculations, args=(run_id,))

            thr.start()

            log.info(f"started job: {run_id}")

            result = {'status': "started job: " + run_id}
            resp.body = json.dumps(result)

        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400, 'Invalid JSON',
                                   'Could not decode the request body. The JSON was invalid.')
예제 #14
0
    def on_post(self, req: Request, resp: Response, subreddit: Text):
        log.info('Attempting to create monitored sub %s', subreddit)
        try:
            self.reddit.subreddit(subreddit).mod.accept_invite()
        except APIException as e:
            if e.error_type == 'NO_INVITE_FOUND':
                log.error('No open invite to %s', subreddit)
                raise HTTPInternalServerError(
                    f'No available invite for {subreddit}',
                    f'We were unable to find a '
                    f'pending mod invote for r/{subreddit}')
            else:
                log.exception('Problem accepting invite', exc_info=True)
                raise HTTPInternalServerError(
                    f'Unknown error accepting mod invite for r/{subreddit}',
                    f'Unknown error accepting mod invite for r/{subreddit}.  Please contact us'
                )
        except Exception as e:
            log.exception('Failed to accept invite', exc_info=True)
            raise HTTPInternalServerError(
                f'Unknown error accepting mod invite for r/{subreddit}',
                f'Unknown error accepting mod invite for r/{subreddit}.  Please contact us'
            )

        with self.uowm.start() as uow:
            existing = uow.monitored_sub.get_by_sub(subreddit)
            if existing:
                resp.body = json.dumps(existing.to_dict())
                return
            monitored_sub = create_monitored_sub_in_db(subreddit, uow)
            resp.body = json.dumps(monitored_sub.to_dict())
예제 #15
0
 def on_get(self, req: Request, resp: Response, subreddit: Text):
     with self.uowm.start() as uow:
         sub = uow.monitored_sub.get_by_sub(subreddit)
         if not sub:
             resp.body = json.dumps({})
             return
         resp.body = json.dumps(sub.to_dict())
예제 #16
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
예제 #17
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
예제 #18
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
예제 #19
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
예제 #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_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
예제 #22
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
예제 #23
0
파일: ModelItem.py 프로젝트: magreiner/MMLP
 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, 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
    def on_get(req: falcon.Request, resp: falcon.Response):

        database = connect(constants.DB_URL)
        current_analyses_table = database[constants.CURRENT_ANALYSES_TABLE]

        if req.get_param(constants.TWEET_TOPIC_TABLE_KEY_NAME):
            if current_analyses_table.find_one(
                    analysis_topic_id=req.get_param_as_int(
                        constants.TWEET_TOPIC_TABLE_KEY_NAME)):
                resp.status = falcon.HTTP_OK
                resp.body = dumps({'currently_analysing': True})
            else:
                resp.status = falcon.HTTP_OK
                resp.body = dumps({'currently_analysing': False})

        elif req.get_param(constants.TWEET_USER_TABLE_KEY_NAME):
            if current_analyses_table.find_one(
                    analysis_user_id=req.get_param_as_int(
                        constants.TWEET_USER_TABLE_KEY_NAME)):
                resp.status = falcon.HTTP_OK
                resp.body = dumps({'currently_analysing': True})
            else:
                resp.status = falcon.HTTP_OK
                resp.body = dumps({'currently_analysing': False})

        elif req.get_param('all'):
            data = {'current_analyses': []}

            current_analyses = current_analyses_table.all()
            for current_analysis in current_analyses:
                if current_analysis[constants.TWEET_TOPIC_TABLE_KEY_NAME]:
                    if current_analysis['is_hashtag']:
                        data['current_analyses'].append({
                            'type':
                            'hashtag',
                            'analysis_topic_id':
                            current_analysis[
                                constants.TWEET_TOPIC_TABLE_KEY_NAME]
                        })
                    else:
                        data['current_analyses'].append({
                            'type':
                            'topic',
                            'analysis_topic_id':
                            current_analysis[
                                constants.TWEET_TOPIC_TABLE_KEY_NAME]
                        })
                elif current_analysis[constants.TWEET_USER_TABLE_KEY_NAME]:
                    data['current_analyses'].append({
                        'type':
                        'user',
                        'analysis_user_id':
                        current_analysis[constants.TWEET_USER_TABLE_KEY_NAME]
                    })
            resp.status = falcon.HTTP_OK
            resp.body = dumps(data)
        else:
            resp.status = falcon.HTTP_NOT_FOUND
예제 #26
0
 def on_post(self, req: Request, resp: Response):
     snap = ModelSnapshot.from_json(req.media['ModelSnapshot'])
     result = self._snapshot_manager.create_snapshot(snap)
     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
예제 #27
0
 def on_delete(self, _: Request, resp: Response, dataset_id: UUID,
               version_id: UUID):
     result = self._dataset_manager.delete_version(dataset_id, version_id)
     if isinstance(result, DatasetVersion):
         resp.body = result.json()
         resp.status = falcon.HTTP_200
     else:
         resp.body = json.dumps(dict(error=str(result)))
         resp.status = falcon.HTTP_404
예제 #28
0
 def on_get(self, req: Request, resp: Response):
     query = get_params_to_query(req, SORT_ATTRIBUTES, 'created', 'desc')
     methods = self._method_manager.list_methods(query=query)
     if isinstance(methods, Exception):
         resp.body = json.dumps(dict(error=str(methods)))
         resp.status = falcon.HTTP_500
     else:
         resp.body = f"[{','.join(map(lambda x: x.json(), methods))}]"
         resp.status = falcon.HTTP_201
예제 #29
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
예제 #30
0
    def on_get(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 access another user\'s data'
            return

        user_notes = self._notes.find({'_id': ObjectId(note_id)})
        resp.body = json_util.dumps(user_notes)
예제 #31
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()
예제 #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
파일: Views.py 프로젝트: hkarasek/iot-dash
    def on_get(self, req: falcon.Request, resp: falcon.Response, dash_id):
        res = []
        for event in get_data_cursor(dash_id):
            res.append({
                'date': event[0].isoformat(),
                'value': float(event[2])
            })

        resp.body = json.dumps(res)
예제 #34
0
 def on_get(self, req: falcon.Request, res: falcon.Response):
     nickname = req.get_param('nickname')
     if nickname:
         user = r.db(DB_NAME).table(DB_TABLE_USERS).get(nickname).run(conn)
         if self.user and self.user['nickname'] == user['nickname']:
             response = user_schema_internal.dumps(user)
         else:
             response = user_schema_external.dumps(user)
     else:
         users = r.db(DB_NAME).table(DB_TABLE_USERS).run(conn)
         response = user_schema_external.loads(list(users), many=True)
     res.body = response.data
예제 #35
0
 def on_patch(self, req: falcon.Request, res: falcon.Response):
     # todo: use salted password
     if self.auth_error:
         raise self.auth_error
     nickname = req.get_param('nickname')
     if not nickname:
         raise falcon.HTTPMethodNotAllowed(ERROR_INVALID_REQUEST)
     if self.user and self.user['nickname'] == nickname:
         result = r.db(DB_NAME).table(DB_TABLE_USERS).update(self.data).run(conn)
         res.body = json.dumps(result)
     else:
         raise falcon.HTTPUnauthorized('Unauthorized Error', ERROR_INVALID_REQUEST)
예제 #36
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)
예제 #37
0
 def on_post(self, _req: falcon.Request, res: falcon.Response):
     # todo: use salted password
     self.data['created_on'] = int(time.time() * 1000)
     result = r.db(DB_NAME).table(DB_TABLE_USERS).insert(self.data).run(conn)
     res.body = json.dumps(result)