Beispiel #1
0
def create_validated_transcription(session: Session, data):

    validated_transcription = ValidatedTranscription(**data)
    session.add(validated_transcription)
    # Flush the changes to the database. This will populate the customer
    # id.
    session.flush()
Beispiel #2
0
 def save(self, session: Session, commit=True):
     """Save the record."""
     session.add(self)
     if commit:
         session.commit()
     session.flush()
     return self
Beispiel #3
0
def delete_auto(session: Session, auto_id: int,
                data: http.RequestData) -> None:
    """ Delete a given auto. Called from DELETE /autos/:id """
    auto = session.query(Auto).get(auto_id)
    session.delete(auto)
    session.flush()
    return None
Beispiel #4
0
def signup(session: Session, data: SignupData, settings: Settings):
    user = User(username=data['username'],
                password=hash_password(data['password'], settings))
    session.add(user)
    session.flush()

    return {'id': user.id, 'username': user.username}
Beispiel #5
0
def create_note(session: Session, data: NoteCreate, auth: Auth):
    """
    This endpoint created note
    """
    instance = Note(
        user_id=auth.user.id,
        title=data['title'],
        text=data['text'],
        device_token=data['device_token']
    )

    if data.get('reminder_date'):
        try:
            instance.reminder_date = datetime.strptime(
                data['reminder_date'], '%Y/%m/%d %H:%M'
            )
        except ValueError:
            raise ValidationError({
                'message': 'invalid reminder date'
            })

    if data.get('category'):
        category = session.query(Category).filter(
            Category.id == data['category'],
            Category.user_id == auth.user.id
        ).first()

        if not category:
            raise ValidationError({'message': 'Invalid category'})

        instance.category_id = category.id

    session.add(instance)
    session.flush()
    return NoteList(instance)
Beispiel #6
0
def create_user(session: Session, user: schemas.User):
    """
    Create User.
    """
    obj = User(**user)
    session.add(obj)
    session.flush()
    return {'id': obj.id, 'fullname': obj.fullname}
Beispiel #7
0
def create_payment(session: Session, payment: schemas.Payment):
    """
    Create Payment and relation involve with User.
    """
    obj = Payment(**payment)
    session.add(obj)
    session.flush()
    return {'id': obj.id, 'method': obj.method, 'status': obj.status}
Beispiel #8
0
def update_auto(session: Session, auto_id: int,
                data: http.RequestData) -> dict:
    """ Update a given auto. Called from PATCH /autos/:id """
    auto_properties = ["name", "make", "model", "year"]
    auto = session.query(Auto).get(auto_id)
    for auto_prop in auto_properties:
        if auto_prop in data:
            setattr(auto, auto_prop, data[auto_prop])
    session.flush()
    return make_auto_dict(auto)
Beispiel #9
0
def patch_book(session: Session, book_id: int, checked_out: bool) -> Response:
    book = session.query(BookModel).get(book_id)
    book.checked_out = checked_out
    session.commit()
    session.flush()
    return {
        'id': book.id,
        'title': book.title,
        'checked_out': book.checked_out
    }
Beispiel #10
0
def create_category(session: Session, data: CategoryCreate, auth: Auth):
    """
    This endpoint creates category
    """
    instance = Category(
        user_id=auth.user.id,
        name=data['name']
    )
    session.add(instance)
    session.flush()
    return CategoryList(instance)
Beispiel #11
0
def create_video(session: Session, video: schemas.Video):
    """Cast given locale to string. Supports also callbacks that return locales.
        title:
            Object or "class" to use as a possible parameter to locale calla   ble
        length:
            Locale object or string or callable that returns a locale.
    """
    obj = Video(**video)
    session.add(obj)
    session.flush()
    return {'id': obj.id, 'title': obj.title}
Beispiel #12
0
def fixtures(session: Session):
    # Add a test user
    user = User(email="*****@*****.**", password="******")
    session.add(user)
    session.flush()

    # Add matrix
    session.add(Matrix(name="Candidates", active=True, user=user.id))
    session.add(Matrix(name="Multiplication", active=False, user=user.id))
    session.add(Matrix(name="Gradebook", active=False, user=user.id))
    session.add(Matrix(name="Survey Grid 1", active=False, user=user.id))
    session.flush()

    # Populate matrix axis
    m = session.query(Matrix).get(1)
    session.add(Row(name="Bob", sort=1, matrix=m.id))
    session.add(Row(name="Suzy", sort=2, matrix=m.id))
    session.add(Row(name="Joe", sort=3, matrix=m.id))

    o5 = Options(key="text")
    o2 = Options(key="drop")
    session.add(o2)
    session.add(o5)
    session.flush()

    session.add(Option(key="0", value="Sad", options=o2.id, sort=1))
    session.add(Option(key="1", value="Meh", options=o2.id, sort=2))
    session.add(Option(key="2", value="Happy", options=o2.id, sort=3))

    session.add(Col(name="Skills (1 - 5)", sort=1, matrix=m.id, options=o5.id))
    session.add(Col(name="Looks (1 - 5)", sort=1, matrix=m.id, options=o5.id))
    session.add(Col(name="Joy", sort=2, matrix=m.id, options=o2.id))
    session.add(Col(name="Notes", sort=3, matrix=m.id, options=o5.id))

    session.flush()
Beispiel #13
0
def signup(session: Session, data: Signup, settings: Settings):
    """
    This endpoint creates user
    """
    user = User(
        username=data['username'],
        password=hash_password(data['password'], settings)
    )

    session.add(user)
    session.flush()

    token = AccessToken(token=generate_key(), user_id=user.id)
    session.add(token)

    return {
        'id': user.id,
        'username': user.username,
        'token': token.token
    }
Beispiel #14
0
def get_authority_generation(
        session: Session, authority: typing.Text, start_at: http.QueryParam,
        end_at: http.QueryParam) -> typing.List[GenerationDatumSchema]:
    """Get a timeseries of energy generation for a balancing authority."""
    start_dt = get_dt_from_string(start_at,
                                  default_dt=pytz.utc.localize(dt.utcnow() -
                                                               td(days=1)))
    end_dt = get_dt_from_string(end_at,
                                default_dt=pytz.utc.localize(dt.utcnow()))

    meta = session.query(DatumMeta).filter_by(
        authority_code=authority,
        data_type=GenerationDatum.__tablename__).first()
    new_meta = False
    # we might not have the metadata for this authority/data_type combo
    if meta is None:
        new_meta = True
        meta = DatumMeta(
            authority_code=authority,
            most_recent=end_dt,
            least_recent=start_dt,
            data_type=GenerationDatum.__tablename__,
        )
    if not new_meta and \
            (meta.most_recent + td(minutes=5)) >= end_dt and \
            meta.least_recent <= start_dt:
        logging.info('requested data is stored in database')
    elif meta.most_recent >= end_dt and not (meta.least_recent <= start_dt):
        logging.info('requested data is strictly older than stored data')
        auth_client = client_factory(authority)
        new_data = auth_client.get_generation(start_at=start_dt,
                                              end_at=meta.least_recent)
        gen_models = [GenerationDatum(**g) for g in pull_gen_data(new_data)]
        meta.least_recent = start_dt
        session.add_all(gen_models + [meta])
        session.flush()
    elif not (meta.most_recent >= end_dt) and meta.least_recent <= start_dt:
        logging.info('requested data is strictly newer than stored data')
        auth_client = client_factory(authority)
        new_data = auth_client.get_generation(start_at=meta.most_recent,
                                              end_at=end_dt)
        gen_models = [GenerationDatum(**g) for g in pull_gen_data(new_data)]
        meta.most_recent = end_dt
        session.add_all(gen_models + [meta])
        session.flush()
    else:
        logging.info('requested data is a superset of stored data')
        auth_client = client_factory(authority)
        left_hand_data = auth_client.get_generation(start_at=meta.least_recent,
                                                    end_at=end_dt)
        right_hand_data = auth_client.get_generation(start_at=start_dt,
                                                     end_at=meta.most_recent)
        gen_models = list(
            set([
                GenerationDatum(**g)
                for g in pull_gen_data(left_hand_data + right_hand_data)
            ]))
        meta.most_recent = end_dt
        meta.least_recent = start_dt
        session.add_all(gen_models + [meta])
        session.flush()

    filter_set = [
        GenerationDatum.authority_code == authority,
        GenerationDatum.timestamp <= end_dt,
        GenerationDatum.timestamp >= start_dt,
    ]
    query_set = session.query(GenerationDatum).filter(*filter_set).all()
    return [GenerationDatumSchema(g) for g in query_set]
Beispiel #15
0
def create_auto(session: Session, data: http.RequestData) -> dict:
    """ Creates auto in db. Called from POST /autos/ """
    auto = Auto(**data)
    session.add(auto)
    session.flush()
    return make_auto_dict(auto)
Beispiel #16
0
def create_user(session: Session, user: UserSchemas):
    print(user)
    user = User(**user)
    session.add(user)
    session.flush()
    return UserSchemas(user)
Beispiel #17
0
def create_student(session: Session, name: str, address: str):
    student = Student(name=name, address=address)
    session.add(student)
    session.flush(
    )  # Flush the changes to the database. This will populate the customer id.
    return {'id': student.id, 'name': student.name, 'address': student.address}
Beispiel #18
0
def delete_book(session: Session, book_id: int) -> Response:
    book = session.query(BookModel).get(book_id)
    session.delete(book)
    session.flush()
    return {'id': book.id, 'title': book.title}