Пример #1
0
    def getResource(self, sid, rid, name):
        if cherrypy.session.get("permission", -1) not in [0, 1, 2]:
            raise cherrypy.HTTPError(401, "权限不足")

        sess = Session()
        try:
            record = sess.query(Record).filter(Record.st_id == sid,
                                               Record.id == rid).one()

            if name == "image1":
                url, _type = record.img_plate_path, "image/jpeg"
            elif name == "image2":
                url, _type = record.img_smoke_path, "image/jpeg"
            elif name == "video":
                url, _type = record.video_path, "video/mp4"
            else:
                raise NoResultFound()
            if not path.isfile(url):
                raise NoResultFound()
            return cherrypy.lib.static.serve_file(url, _type)
        except NoResultFound:
            raise cherrypy.HTTPError(404)
        except:
            server._warning("查询记录时发生错误", exc_info=True)
            raise cherrypy.HTTPError(500, "发生未知错误")
        finally:
            sess.close()
Пример #2
0
def update_wallet(wallet_name, wallet_data):
    session = Session()

    try:
        wallet = session.query(Wallet).filter_by(name=wallet_name).one()
    except NoResultFound:
        raise NoResultFound('Invalid wallet name')

    if wallet.user_id != auth.current_user().id:
        raise NoResultFound('You don\'t have required permission')

    if wallet_data.get('name') and wallet_data.get('name') != wallet_name:
        try:
            session.query(Wallet).filter_by(name=wallet_data.get('name')).one()
        except NoResultFound:
            pass
        else:
            raise ValidationError("Wallet name must be unique")

    for k, val in wallet_data.items():
        if k == 'user_id':
            session.query(User).filter_by(id=val).one()

        setattr(wallet, k, val)

    session.commit()

    return WalletData().dump(wallet)
Пример #3
0
def update_user(user_id, user_data):
    session = Session()
    if auth.current_user().id != user_id:
        raise NoResultFound('You don\'t have required permission')
    try:
        user = session.query(User).filter_by(id=user_id).one()
    except NoResultFound:
        raise NoResultFound('Invalid id')

    if user_data.get('id') and user_data.get('id') != user_id:
        raise ValidationError(f"Different id {user_data.get('id')} != {user_id}")

    if user_data.get('email') and user.email != user_data.get('email'):
        try:
            session.query(User).filter_by(email=user_data.get('email')).one()
        except NoResultFound:
            pass
        else:
            raise ValidationError("Email must be unique")

    for k, val in user_data.items():
        if k == 'password':
            setattr(user, k, generate_password_hash(val))
        else:
            setattr(user, k, val)

    session.commit()

    return UserData(exclude=['password']).dump(user)
Пример #4
0
 def gerar_arquivos_docx(db, session, documento, filename, fonte_docx_id, oid):
     out_filename = '{}_{}_{}.docx'.format(
         filename,
         oid,
         datetime.strftime(datetime.now(), '%Y-%m-%dT%H-%M-%S')
     )
     try:
         ovr_dict = OVRDict(fonte_docx_id).get_dict(
             db=db, session=session, id=oid)
     except NoResultFound:
         raise NoResultFound('{} {} não encontrado!'.format(
             FonteDocx(fonte_docx_id), oid))
     print(ovr_dict)
     if isinstance(ovr_dict, list):
         if len(ovr_dict) == 0:
             raise NoResultFound(f'Marcas não encontradas na ovr {oid}.')
         logger.info('Gerando marcas')
         arquivos = []
         for odict in ovr_dict:
             document = get_doc_generico_ovr(odict, documento,
                                             current_user.name)
             nome_arquivo = '%s_%s.docx' % (out_filename[:-4], odict.get('nome'))
             arquivos.append(nome_arquivo)
             document.save(os.path.join(
                 get_user_save_path(), nome_arquivo))
     else:
         document = get_doc_generico_ovr(ovr_dict, documento,
                                         current_user.name)
         document.save(os.path.join(get_user_save_path(), out_filename))
         arquivos = [out_filename]
     return arquivos
Пример #5
0
def get_wallet(wallet_name):
    session = Session()
    try:
        wallet = session.query(Wallet).filter_by(name=wallet_name).one()
    except NoResultFound:
        raise NoResultFound('Invalid wallet name')
    if wallet.user_id != auth.current_user().id:
        raise NoResultFound('You don\'t have required permission')
    return WalletData().dump(wallet)
Пример #6
0
def solution_data(exam_id, student_id):
    """Return Python datastructures corresponding to the student submission."""
    exam = Exam.query.get(exam_id)
    if exam is None:
        raise NoResultFound(f"Exam with id #{exam_id} does not exist.")
    student = Student.query.get(student_id)
    if student is None:
        raise NoResultFound(f"Student with id #{student_id} does not exist.")

    sub = Submission.query.filter(Submission.exam == exam,
                                  Submission.student == student,
                                  Submission.validated).one_or_none()
    if sub is None:
        raise RuntimeError('Student did not make a '
                           'submission for this exam')

    results = []
    for solution in sub.solutions:  # Sorted by problem_id
        problem = solution.problem
        if len(problem.feedback_options) < 2:
            # There is no possible feedback for this problem (take into account that root always exist)..
            continue

        problem_data = {
            'id': problem.id,
            'name': problem.name,
            'max_score': max(fb.score for fb in problem.feedback_options) or 0
        }

        feedback = [fo for fo in problem.root_feedback.all_descendants if fo in solution.feedback]

        problem_data['feedback'] = [
            {'id': fo.id,
             'short': fo.text,
             'score': fo.score,
             'description': fo.description}
            for fo in feedback if solution.graded_by
        ]
        problem_data['score'] = (
            sum(i['score'] or 0 for i in problem_data['feedback'])
            if problem_data['feedback']
            else np.nan
        )
        problem_data['remarks'] = solution.remarks

        results.append(problem_data)

    student = {
        'id': student.id,
        'first_name': student.first_name,
        'last_name': student.last_name,
        'email': student.email,
        'total': sum(i['score'] for i in results if not np.isnan(i['score']))
    }

    return student, results
Пример #7
0
def delete(model, id):
    if auth.current_user().id != id:
        raise NoResultFound('You don\'t have required permission')
    session = Session()
    try:
        session.query(model).filter_by(id=id).one()
    except NoResultFound:
        raise NoResultFound('Invalid id')

    session.query(model).filter_by(id=id).delete()
    session.commit()
Пример #8
0
def get_user(user_id):
    session = Session()

    try:
        user = session.query(User).filter_by(id=user_id).one()
    except NoResultFound:
        raise NoResultFound('Invalid id')
    # if user is None:
    #     raise NoResultFound('User is not found')
    if user.id != auth.current_user().id:
        raise NoResultFound('You don\'t have required permission')
    # exclude = ['password']
    return UserData(exclude=['password']).dump(user)
Пример #9
0
def list_wallets(wallets_filter):
    session = Session()
    if auth.current_user().id != wallets_filter.get('user_id'):
        raise NoResultFound('You don\'t have required permission')

    query = session.query(Wallet)

    try:
        session.query(User).filter_by(id=wallets_filter.get('user_id')).one()
    except NoResultFound:
        raise NoResultFound('Invalid id')

    query = query.filter_by(user_id=wallets_filter.get('user_id'))

    return WalletData(many=True).dump(query.all())
Пример #10
0
    def is_current_user_admin(self, db_session: Session, user_id: int,
                              community_id: int):
        community = (db_session.query(Community).options(
            lazyload("admins")).get(community_id))
        if community is None:
            raise NoResultFound("Community not found")

        user = db_session.query(User).get(user_id)
        if user is None:
            raise NoResultFound("User not found")

        if user not in community.admins and not user.is_admin:
            return False

        return True
Пример #11
0
    def remove(self, db_session: Session, community_id: int, user_id: int):
        community = (db_session.query(Community).options(
            lazyload("admins")).get(community_id))
        if community is None:
            raise NoResultFound("Community not found")

        user = db_session.query(User).get(user_id)
        if user is None:
            raise NoResultFound("User not found")

        if user not in community.admins:
            raise Exception("User is not admin of this community")

        db_session.delete(community)
        db_session.commit()
        return community
Пример #12
0
 def test012_load_from_ext_id_none(self):
     m_session = MagicMock()
     external_id = "whatever"
     m_filter = m_session.query().options().filter
     m_filter.side_effect = NoResultFound()
     with self.assertRaises(IrmaDatabaseResultNotFound):
         Scan.load_from_ext_id(external_id, m_session)
Пример #13
0
def test_api_get_token(mock_token, test_client):
    access_token = Mock()
    access_token.id = '1'
    access_token.jti = '54321'
    access_token.token_type = 'access'
    access_token.expires = None
    queryset = Mock()
    queryset.one.return_value = access_token
    mock_token.query.filter_by.return_value = queryset

    data = {'jti': '54321', 'user_id': '1'}

    response = test_client.get('/tokens/',
                               content_type='application/json',
                               data=json.dumps(data, sort_keys=True))

    assert response.status_code == 200
    assert response.json['id'] == "1"
    assert response.json['jti'] == "54321"
    assert response.json['token_type'] == "access"

    # No token found
    queryset.one.side_effect = NoResultFound()
    response = test_client.get('/tokens/',
                               content_type='application/json',
                               data=json.dumps(data, sort_keys=True))

    assert response.status_code == 200
    assert not response.json
Пример #14
0
def deliver_sms(self, notification_id):
    try:
        current_app.logger.info(
            "Start sending SMS for notification id: {}".format(
                notification_id))
        notification = notifications_dao.get_notification_by_id(
            notification_id)
        if not notification:
            raise NoResultFound()
        send_to_providers.send_sms_to_provider(notification)
    except Exception as e:
        if isinstance(e, SmsClientResponseException):
            current_app.logger.warning(
                "SMS notification delivery for id: {} failed".format(
                    notification_id))
        else:
            current_app.logger.exception(
                "SMS notification delivery for id: {} failed".format(
                    notification_id))

        try:
            if self.request.retries == 0:
                self.retry(queue=QueueNames.RETRY, countdown=0)
            else:
                self.retry(queue=QueueNames.RETRY)
        except self.MaxRetriesExceededError:
            message = "RETRY FAILED: Max retries reached. The task send_sms_to_provider failed for notification {}. " \
                      "Notification has been updated to technical-failure".format(notification_id)
            update_notification_status_by_id(notification_id,
                                             NOTIFICATION_TECHNICAL_FAILURE)
            raise NotificationTechnicalFailureException(message)
Пример #15
0
def deliver_email(self, notification_id):
    try:
        current_app.logger.info(
            "Start sending email for notification id: {}".format(
                notification_id))
        notification = notifications_dao.get_notification_by_id(
            notification_id)
        if not notification:
            raise NoResultFound()
        send_to_providers.send_email_to_provider(notification)
    except EmailClientNonRetryableException as e:
        current_app.logger.exception(
            f"Email notification {notification_id} failed: {e}")
        update_notification_status_by_id(notification_id, 'technical-failure')
    except Exception as e:
        try:
            if isinstance(e, AwsSesClientThrottlingSendRateException):
                current_app.logger.warning(
                    f"RETRY: Email notification {notification_id} was rate limited by SES"
                )
            else:
                current_app.logger.exception(
                    f"RETRY: Email notification {notification_id} failed")

            self.retry(queue=QueueNames.RETRY)
        except self.MaxRetriesExceededError:
            message = "RETRY FAILED: Max retries reached. " \
                      "The task send_email_to_provider failed for notification {}. " \
                      "Notification has been updated to technical-failure".format(notification_id)
            update_notification_status_by_id(notification_id,
                                             NOTIFICATION_TECHNICAL_FAILURE)
            raise NotificationTechnicalFailureException(message)
Пример #16
0
def test_get_account_gce(mock_gce_account, mock_handle_request, test_client):
    account = Mock()
    account.id = '1'
    account.name = 'user1'
    account.bucket = 'images'
    account.region = 'us-east-1'
    account.testing_account = None
    account.is_publishing_account = False

    queryset = Mock()
    queryset.one.return_value = account
    mock_gce_account.query.filter_by.return_value = queryset

    request = {'name': 'test', 'user_id': 'user1'}

    response = test_client.get('/gce_accounts/',
                               content_type='application/json',
                               data=json.dumps(request, sort_keys=True))

    assert response.status_code == 200
    assert response.json['id'] == "1"
    assert response.json['name'] == "user1"
    assert response.json['region'] == "us-east-1"

    # Not found
    mock_gce_account.query.filter_by.side_effect = NoResultFound()

    response = test_client.get('/gce_accounts/',
                               content_type='application/json',
                               data=json.dumps(request, sort_keys=True))
    assert response.status_code == 200
    assert response.data == b'{}\n'
Пример #17
0
 def run(self, containers, family, app=app):
     apps = []
     with app.app_context():
         for container in containers:
             try:
                 repo, commit_hash = container[0].split(':')
             except ValueError:
                 raise ValueError('"{}" should look like repo:id'.format(
                     container[0]))
             build = Build.query.join(Commit).filter(
                 Commit.repository == repo,
                 or_(Commit.commit_hash == commit_hash,
                     Commit.tag == commit_hash),
             ).first()
             if build is None:
                 raise NoResultFound("No row found for {}/{}".format(
                     repo, commit_hash))
             apps.append(
                 ECSBuilder.DockerContainer(
                     build=build,
                     environment=container[1],
                     memory=container[2],
                     portmappings=[{
                         "hostPort": 8080,
                         "containerPort": 80
                     }] if repo == "adsws" else None,
                 ))
         tmpl = ECSBuilder(apps, family=family).render_template()
         print(tmpl)
         return tmpl
Пример #18
0
    def find_thumbnail(self, width=None, height=None):
        """Finds the thumbnail of the image with the given ``width``
        and/or ``height``.

        :param width: the thumbnail width
        :type width: :class:`numbers.Integral`
        :param height: the thumbnail height
        :type height: :class:`numbers.Integral`
        :returns: the thumbnail image
        :rtype: :class:`Image`
        :raises sqlalchemy.orm.exc.NoResultFound:
           when there's no image of such size

        """
        if width is None and height is None:
            raise TypeError('required width and/or height')
        q = self
        if width is not None:
            q = q.filter_by(width=width)
        if height is not None:
            q = q.filter_by(height=height)
        try:
            return q.one()
        except NoResultFound:
            if width is not None and height is not None:
                msg = 'size: ' + repr((width, height))
            elif width is not None:
                msg = 'width: ' + repr(width)
            else:
                msg = 'height: ' + repr(height)
            raise NoResultFound('no thumbnail image of such ' + msg)
 def one(self) -> Any:
     if len(self._result) == 1:
         return self._result[0]
     elif self._result:
         raise MultipleResultsFound("Multiple rows returned for one()")
     else:
         raise NoResultFound("No rows returned for one()")
Пример #20
0
def update_calc(calc_id: int,
                data: Dict[str, Union[str, int]]) -> CalculationResult:
    """ update calc data by calc_id

    Args:
        calc_id (int): calc id
        data (dict): calc data for update

    Raises:
        CalcNotFound: Not found data
        InternelServerError: Internel server error

    Returns:
        CalculationResult: Calculation, status_code
    """
    try:
        calc = _calculation.select_id(calc_id=calc_id)

        if not calc.first():
            raise NoResultFound('CalcNotFound')
        else:
            calc = _calculation.update(calc=calc, data=data)

        return CalculationResult(data=_calc_schema.dump(calc.first()),
                                 status_code=200)

    except NoResultFound as e:
        abort(404, message=str(e))
    except Exception as e:
        abort(500, message='InternelServerError')
Пример #21
0
def test_get_account_ec2(mock_ec2_account, mock_handle_request, test_client):
    account = Mock()
    account.id = '1'
    account.name = 'user1'
    account.partition = 'aws'
    account.region = 'us-east-1'
    account.subnet = None
    account.additional_regions = None
    account.group = None

    queryset = Mock()
    queryset.one.return_value = account
    mock_ec2_account.query.filter_by.return_value = queryset

    request = {'name': 'test', 'user_id': 'user1'}

    response = test_client.get('/ec2_accounts/',
                               content_type='application/json',
                               data=json.dumps(request, sort_keys=True))

    assert response.status_code == 200
    assert response.json['id'] == "1"
    assert response.json['name'] == "user1"
    assert response.json['region'] == "us-east-1"

    # Not found
    mock_ec2_account.query.filter_by.side_effect = NoResultFound()

    response = test_client.get('/ec2_accounts/',
                               content_type='application/json',
                               data=json.dumps(request, sort_keys=True))
    assert response.status_code == 200
    assert response.data == b'{}\n'
Пример #22
0
    def helper_email_to_api_uid(permission_data):
        """
        A proxy to the user/e-mail resolver service. Passes on any errors from
        the API.

        :param permission_data: dictionary that should contain an e-mail key
        :return: int of the user id
        """
        try:
            service = '{api}/{email}'.format(
                api=current_app.config['BIBLIB_USER_EMAIL_ADSWS_API_URL'],
                email=permission_data['email']
            )
            current_app.logger.info('Obtaining UID of user: {0}'
                                    .format(permission_data['email']))
            response = client().get(
                service
            )
        except KeyError as error:
            current_app.logger.error('No user email provided. [{0}]'
                                     .format(error))
            raise

        if response.status_code == 200:
            return int(response.json()['id'])
        elif response.status_code == 404:
            raise NoResultFound('API does not have this user')
        else:
            raise Exception('Unknown internal error')
Пример #23
0
def switch_environments(game_object_id, env_id, pos=Vector(0, 0)):
    new_env = Environment.query.filter_by(id=env_id)
    game_object = GameObject.query.filter_by(id=game_object_id)
    if not new_env:
        raise NoResultFound(f"No environment found with id={env_id}")
    elif not game_object:
        raise NoResultFound(f"No GameObject found with id={game_object_id}")
    # Boundary Check
    if pos.x + game_object.width > new_env.width:
        raise ValueError("HEYCHANGETHISEXCEPIONTYPE\nGameObject out of bounds (x)")
    elif pos.y + game_object.height > new_env.height:
        raise ValueError("HEYCHANGETHISEXCEPIONTYPE\nGameObject out of bounds (y)")
    # Everything peachy. Set position
    else:
        game_object.environment = new_env
        game_object.pos = pos
Пример #24
0
 def delete_product(self, id: int):
     product = Product.query.get(id)
     if product is None:
         raise NoResultFound({'error': 'Product not found', 'field': 'id'})
     db.session.delete(product)
     db.session.commit()
     return product
Пример #25
0
 def get_by_vk_id(self, db_session: Session, community_vk_id: int):
     community = (db_session.query(Community).options(
         lazyload("managers"), lazyload("admins")).filter_by(
             community_vk_id=community_vk_id).first())
     if community is None:
         raise NoResultFound("Community not found")
     return community
Пример #26
0
def deliver_email(self, notification_id):
    try:
        current_app.logger.info(
            "Start sending email for notification id: {}".format(
                notification_id))
        notification = notifications_dao.get_notification_by_id(
            notification_id)
        if not notification:
            raise NoResultFound()
        send_to_providers.send_email_to_provider(notification)
    except InvalidEmailError as e:
        current_app.logger.exception(e)
        update_notification_status_by_id(notification_id, 'technical-failure')
    except Exception as e:
        try:
            current_app.logger.exception(
                "RETRY: Email notification {} failed".format(notification_id))
            self.retry(queue=QueueNames.RETRY)
        except self.MaxRetriesExceededError:
            message = "RETRY FAILED: Max retries reached. " \
                      "The task send_email_to_provider failed for notification {}. " \
                      "Notification has been updated to technical-failure".format(notification_id)
            update_notification_status_by_id(notification_id,
                                             NOTIFICATION_TECHNICAL_FAILURE)
            raise NotificationTechnicalFailureException(message)
Пример #27
0
def get_user_inventory(user_id):
    logger.info(f"Getting user inventory for user with id={user_id}")
    if User.query.filter_by(id=user_id).one():
        return UserInventory.query.filter_by(user_id=user_id)
    else:
        logger.error(f"No result found for user with id={user_id}")
        raise NoResultFound(f"User with id={user_id} does not exist.")
Пример #28
0
    def it_raises_error_if_email_not_found(self, mocker, client, db_session,
                                           sample_email, sample_uuid):
        data = {
            "event_id": str(sample_email.event_id),
            "details": sample_email.details,
            "extra_txt": '<div>New extra text</div>',
            "replace_all": sample_email.replace_all,
            "email_type": EVENT,
            "email_state": READY
        }

        mocker.patch('app.routes.emails.rest.dao_get_email_by_id',
                     side_effect=NoResultFound())

        response = client.post(url_for('emails.update_email',
                                       email_id=sample_uuid),
                               data=json.dumps(data),
                               headers=[('Content-Type', 'application/json'),
                                        create_authorization_header()])

        assert response.status_code == 400

        json_resp = json.loads(response.get_data(as_text=True))

        assert json_resp['message'] == '{} did not update email'.format(
            sample_uuid)
Пример #29
0
 def test_classmethod_load_from_sha256_raise_NoResultFound(self):
     sample = "test"
     session = MagicMock()
     session.query.side_effect = NoResultFound(sample)
     with self.assertRaises(IrmaDatabaseResultNotFound) as context:
         module.File.load_from_sha256("whatever", session)
     self.assertEqual(str(context.exception), sample)
Пример #30
0
def test_get_accounts_in_ec2_group(mock_group, test_client):
    group = Mock()
    queryset = Mock()
    queryset.one.return_value = group
    mock_group.query.filter_by.return_value = queryset

    account = Mock()
    account.id = '1'
    account.name = 'user1'
    account.partition = 'aws'
    account.region = 'us-east-1'
    account.subnet = None
    account.additional_regions = None
    account.group = None

    group.accounts = [account]
    request = {'group_name': 'test', 'user_id': 'user1'}

    response = test_client.get('/ec2_accounts/group_accounts',
                               content_type='application/json',
                               data=json.dumps(request, sort_keys=True))

    assert response.status_code == 200
    assert response.json[0]['id'] == "1"
    assert response.json[0]['name'] == "user1"
    assert response.json[0]['region'] == "us-east-1"

    # Not found
    queryset.one.side_effect = NoResultFound()

    response = test_client.get('/ec2_accounts/group_accounts',
                               content_type='application/json',
                               data=json.dumps(request, sort_keys=True))
    assert response.status_code == 404
    assert response.data == b'{"msg":"Group test not found."}\n'