示例#1
0
def order_detail_flush_dirty(a_row: models.OrderDetail, a_session: session):
    old_row = get_old_row(a_row)  # type: models.OrderDetail
    if a_row.OrderId == old_row.OrderId:
        if a_row.ProductId != old_row.ProductId:
            product = a_session.query(models.Product). \
                filter(models.Product.Id == a_row.ProductId).one()
            a_row.UnitPrice = product.UnitPrice
        a_row.Amount = a_row.UnitPrice * a_row.Quantity
        if a_row.Amount != old_row.Amount:
            order = a_row.OrderHeader
            order.AmountTotal += a_row.Amount - old_row.Amount
            old_order = ObjectView(row2dict(order))
            order_update(order, old_order, a_session)
            row_prt(order, "order_detail_flush_dirty adjusted to: " +
                    str(order.AmountTotal))
    else:  # moved item to different order
        order = a_row.OrderHeader  # reduce the old one
        order.AmountTotal -= old_row.Amount
        old_order = ObjectView(row2dict(order))
        order_update(order, old_order, a_session)
        row_prt(order, "order_detail_flush_dirty adjusted to: " +
                str(order.AmountTotal))

        if a_row.ProductId != old_row.ProductId:
            product = a_session.query(models.Product). \
                filter(models.Product.Id == old_row.ProductId).one()
            a_row.UnitPrice = product.UnitPrice
        a_row.Amount = a_row.UnitPrice * a_row.Quantity
        order = a_session.query(models.Order). \
            filter(models.Order.Id == a_row.OrderId).one()
        old_order = ObjectView(row2dict(order))
        order.AmountTotal += a_row.Amount
        order_update(order, old_order, a_session)
        row_prt(order, "order_detail_flush_dirty adjusted to: " +
                str(order.AmountTotal))
示例#2
0
def load_values(db_session: session, module):
    def add_units(data, unit_type: IngredientUnit.UnitType, is_cldr: bool):
        for entry in data:
            unit = IngredientUnit(type_=unit_type,
                                  name=entry[0],
                                  factor=entry[1],
                                  description=entry[2],
                                  cldr=is_cldr)
            db_session.add(unit)

    def add_custom_units(data, unit_type: IngredientUnit.UnitType):
        for entry in data:
            unit = IngredientUnit(type_=unit_type,
                                  name=entry[0],
                                  factor=None,
                                  description=entry[1],
                                  cldr=False)
            db_session.add(unit)

    add_units(cldr.DATA_MASS, IngredientUnit.UnitType.MASS, is_cldr=True)
    add_units(cldr.DATA_VOLUME, IngredientUnit.UnitType.VOLUME, is_cldr=True)

    data_quantity = getattr(module, "DATA_QUANTITY")
    add_units(data_quantity, IngredientUnit.UnitType.QUANTITY, is_cldr=False)

    data_unspecific = getattr(module, "DATA_UNSPECIFIC")
    add_custom_units(data_unspecific, IngredientUnit.UnitType.UNSPECIFIC)

    db_session.commit()
示例#3
0
def destroy(id: int, db: session):
    blog = db.query(models.Blog).filter(models.Blog.id == id)
    if not blog.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Blog with id {id} not found")
    blog.delete(synchronize_session=False)
    db.commit()
    return 'done'
示例#4
0
def update(id: int, request: schemas.Blog, db: session):
    blog = db.query(models.Blog).filter(models.Blog.id == id)
    if not blog.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Blog with id {id} not found")
    blog.update(request)
    db.commit()
    return "done"
示例#5
0
def doctors_delete_by_id(id: int, db: session):
    db_doctor = db.query(models.Doctor).filter(models.Doctor.id == id).first()

    if not db_doctor:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"doctor with the id '{id}' not found")

    db.delete(db_doctor)
    db.commit()
示例#6
0
def patients_delete_by_id(id: int, db: session) -> None:
    db_patient = db.query(
        models.Patient).filter(models.Patient.id == id).first()

    if not db_patient:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"patient with the id '{id}' not found")

    db.delete(db_patient)
    db.commit()
示例#7
0
def pillboxes_delete_by_id(id: int, db: session) -> None:
    db_pillbox = db.query(
        models.Pillbox).filter(models.Pillbox.id == id).first()

    if not db_pillbox:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"pillbox with the id '{id}' not found")

    db.delete(db_pillbox)
    db.commit()
示例#8
0
async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks , db: session = Depends(get_db)):
    stock = Stock()
    stock.symbol = stock_request.symbol
    db.add(stock)
    db.commit()

    background_tasks.add_task(fetch_stock_data, stock.id)

    return {
        "code": "success",
        "message": "stock was added to the database"
    }
示例#9
0
def create_new_github_info(data_dict: dict, package: Package,
                           session_: session) -> None:
    """Adds github_info to the package package github_info. if the github_info is not
    already in the database in the github_info table then the code adds the github_info to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        github_url = a_dict.get('github_url')
        if github_url:

            github_url_in_db = session_.query(GithubInfo).filter(
                GithubInfo.github_url == github_url).first()
            # if github_url_in_db:
            #     package.github_info = github_url_in_db
            # else:
            package.github_info = GithubInfo(
                github_url=github_url,
                github_stars=a_dict.get('github_stars'),
                github_forks=a_dict.get('github_forks'),
                github_open_issues=a_dict.get('github_open_issues'),
                github_contributors=a_dict.get('github_contributors'))
示例#10
0
def create_new_programming_languages(data_dict: dict, package: Package,
                                     session_: session) -> None:
    """Adds programming languages to the package package_programming_language. if the programming language is not
    already in the database in the programming_language table then the code adds the programming language to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        programming_languages = a_dict.get('programming_language')
        if programming_languages:
            for programming_language in programming_languages:
                programming_languages_in_db = session_.query(
                    ProgrammingLanguage).filter(
                        ProgrammingLanguage.programming_language ==
                        programming_language).first()
                if programming_languages_in_db:
                    package.package_programming_language.append(
                        programming_languages_in_db)
                else:
                    package.package_programming_language.append(
                        ProgrammingLanguage(
                            programming_language=programming_language))
示例#11
0
def home(request: Request, forward_pe = None, dividend_yield = None, ma50 = None, ma200 = None,  db: session = Depends(get_db)):



    stocks = db.query(Stock)

    if forward_pe:
        stocks = stocks.filter(Stock.forward_pe < forward_pe)
    if dividend_yield:
        stocks = stocks.filter(Stock.dividend_yield > dividend_yield)
    if ma50:
        stocks = stocks.filter(Stock.price > Stock.ma50)
    if ma200:
        stocks = stocks.filter(Stock.price > Stock.ma200)


    print(stocks)
    return templates.TemplateResponse("home.html", {
        "request": request,
        "stocks" : stocks,
        "forward_pe" : forward_pe,
        "dividend_yield" : dividend_yield,
        "ma50" : ma50,
        "ma200" : ma200
    }
                                      )
示例#12
0
def doctors_updated_by_id(id: int, doctor: schemas.DoctorBase,
                          db: session) -> dict:
    db_doctor = db.query(models.Doctor).filter(models.Doctor.id == id).first()

    if not db_doctor:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"doctor with the id '{id}' not found")

    db_doctor.first_name = doctor.first_name
    db_doctor.last_name = doctor.last_name
    db_doctor.email = doctor.email
    db_doctor.phone_number = doctor.phone_number

    db.commit()
    db.refresh(db_doctor)

    return db_doctor
示例#13
0
def doctors_read_by_id(id: int, db: session) -> dict:
    db_doctor = db.query(models.Doctor).filter(models.Doctor.id == id).first()

    if not db_doctor:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"doctor with the id '{id}' not found")

    return db_doctor
示例#14
0
def patients_read_by_id(id: int, db: session) -> dict:
    db_patient = db.query(
        models.Patient).filter(models.Patient.id == id).first()

    if not db_patient:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"patient with the id '{id}' not found")

    return db_patient
示例#15
0
def pillboxes_read_by_id(id: int, db: session) -> dict:
    db_pillbox = db.query(
        models.Pillbox).filter(models.Pillbox.id == id).first()

    if not db_pillbox:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"pillbox with the id '{id}' not found")

    return db_pillbox
示例#16
0
def patients_updated_by_id(id: int, patient: schemas.PatientBase,
                           db: session) -> dict:
    db_patient = db.query(
        models.Patient).filter(models.Patient.id == id).first()

    if not db_patient:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"patient with the id '{id}' not found")

    db_patient.first_name = patient.first_name
    db_patient.last_name = patient.last_name
    db_patient.email = patient.email
    db_patient.phone_number = patient.phone_number
    db_patient.doctor_id = patient.doctor_id

    db.commit()
    db.refresh(db_patient)

    return db_patient
示例#17
0
def initialize_db(my_session: session, load_data: bool = True):
    """

    Args:
        load_data (): Load the default date (false for tests)

    Returns:

    """

    db.Base.metadata.drop_all(db.engine, checkfirst=True)
    db.Base.metadata.create_all(db.engine, checkfirst=True)

    if load_data:
        load_all(my_session)

    # Setup the default ingredient_unit
    unit_group = data.IngredientUnit(name="Internal group unit", cldr=False, factor=None,
                                     type_=data.IngredientUnit.UnitType.GROUP)
    my_session.add(unit_group)
    my_session.commit()
    data.IngredientUnit.update_unit_dict(my_session)
示例#18
0
def create(request: schemas.User, db: session):
    new_user = models.User(name=request.name,
                           email=request.email,
                           password=Hash.bcrypt(request.password))
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user
示例#19
0
def pillboxes_create(how_many: int, db: session) -> list[dict]:

    for _ in range(how_many):
        pillbox_model = models.Pillbox()

        db.add(pillbox_model)
        db.commit()
        db.refresh(pillbox_model)

        yield pillbox_model
示例#20
0
def login(request: OAuth2PasswordRequestForm = Depends(),
          db: session = Depends(database.get_db)):
    user = db.query(
        models.User).filter(models.User.email == request.username).first()
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Invalid Credentials")

    if not Hash.verify(user.password, request.password):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"username password combination doesn't matches")

    access_token = token.create_access_token(data={"sub": user.email})
    return {"access_token": access_token, "token_type": "bearer"}
    return user
示例#21
0
def create_new_topics(data_dict: dict, package: Package,
                      session_: session) -> None:
    """Adds topics to the package package_topic. if the topic is not
    already in the database in the topic table then the code adds the topic to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """

    data = data_dict.values()
    for a_dict in data:
        topics = a_dict.get('topic')
        if topics:
            for topic in topics:
                topic_in_db = session_.query(Topic).filter(
                    Topic.topic == topic).first()
                if topic_in_db:
                    package.package_topic.append(topic_in_db)
                else:
                    package.package_topic.append(Topic(topic=topic))
示例#22
0
def create_new_environments(data_dict: dict, package: Package,
                            session_: session) -> None:
    """Adds environments to the package package_environment. if the environment is not
    already in the database in the environment table then the code adds the environment to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        environments = a_dict.get('environment')
        if environments:
            for environment in environments:
                environment_in_db = session_.query(Environment).filter(
                    Environment.environment == environment).first()
                if environment_in_db:
                    package.package_environment.append(environment_in_db)
                else:
                    package.package_environment.append(
                        Environment(environment=environment))
示例#23
0
def create_new_frameworks(data_dict: dict, package: Package,
                          session_: session) -> None:
    """Adds frameworks to the package package_framework. if the framework is not
    already in the database in the framework table then the code adds the framework to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        frameworks = a_dict.get('framework')
        if frameworks:
            for framework in frameworks:
                framework_in_db = session_.query(Framework).filter(
                    Framework.framework == framework).first()
                if framework_in_db:
                    package.package_framework.append(framework_in_db)
                else:
                    package.package_framework.append(
                        Framework(framework=framework))
示例#24
0
def create_new_maintainer(maintainer_dict: dict, session_: session,
                          package: Package) -> None:
    """Adds maintainers to the package package_maintainer. if the maintainer is not
    already in the database in the maintainer table then the code adds the maintainer to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param maintainer_dict: A dict of the maintainer data.
    :param session_: sqlalchemy.orm.session.
    :param package: A package object (sqlalchemy table)
    """

    name = maintainer_dict.get('name')
    if name is None:
        name = 'None'
    person_in_db = session_.query(Maintainer).filter(
        Maintainer.name == name).first()
    if person_in_db:
        package.package_maintainer.append(person_in_db)
    else:
        maintainer = Maintainer(name=name,
                                email=maintainer_dict.get('email'),
                                pypi_page=maintainer_dict.get('pypi_page'))
        package.package_maintainer.append(maintainer)
示例#25
0
def create_new_operating_systems(data_dict: dict, package: Package,
                                 session_: session) -> None:
    """Adds operating systems to the package package_operating_system. if the operating system is not
    already in the database in the operating_system table then the code adds the operating system to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        operating_systems = a_dict.get('operating_system')
        if operating_systems:
            for operating_system in operating_systems:
                operating_systems_in_db = session_.query(
                    OperatingSystem).filter(OperatingSystem.operating_system ==
                                            operating_system).first()
                if operating_systems_in_db:
                    package.package_operating_system.append(
                        operating_systems_in_db)
                else:
                    package.package_operating_system.append(
                        OperatingSystem(operating_system=operating_system))
示例#26
0
def create_new_natural_languages(data_dict: dict, package: Package,
                                 session_: session) -> None:
    """Adds natural languages to the package package_natural_language. if the natural language is not
    already in the database in the natural_language table then the code adds the natural languages to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        natural_languages = a_dict.get('natural_language')
        if natural_languages:
            for natural_language in natural_languages:
                natural_language_in_db = session_.query(
                    NaturalLanguage).filter(NaturalLanguage.natural_language ==
                                            natural_language).first()
                if natural_language_in_db:
                    package.package_natural_language.append(
                        natural_language_in_db)
                else:
                    package.package_natural_language.append(
                        NaturalLanguage(natural_language=natural_language))
示例#27
0
def create_new_intended_audiences(data_dict: dict, package: Package,
                                  session_: session) -> None:
    """Adds intended audiences to the package package_intended_audience. if the intended audience is not
    already in the database in the intended_audience table then the code adds the intended audience to the table.
    Dose NOT COMMIT to the database but only adds to the session.
    :param data_dict: Dict with package info (that is returned from the scraper).
    :param package: A package object (sqlalchemy table)
    :param session_: sqlalchemy.orm.session.
    """
    data = data_dict.values()
    for a_dict in data:
        intended_audiences = a_dict.get('intended_audience')
        if intended_audiences:
            for intended_audience in intended_audiences:
                intended_audiences_in_db = session_.query(
                    IntendedAudience).filter(IntendedAudience.intended_audience
                                             == intended_audience).first()
                if intended_audiences_in_db:
                    package.package_intended_audience.append(
                        intended_audiences_in_db)
                else:
                    package.package_intended_audience.append(
                        IntendedAudience(intended_audience=intended_audience))
示例#28
0
def doctors_create(doctor: schemas.DoctorCreateIn, db: session) -> dict:
    password = pg.generate()

    doctor_model = models.Doctor(
        first_name=doctor.first_name,
        last_name=doctor.last_name,
        email=doctor.email,
        phone_number=doctor.phone_number,
        hashed_password=hashing.get_password_hash(password),
    )

    db.add(doctor_model)
    db.commit()
    db.refresh(doctor_model)

    doctor_model.__dict__['password'] = password

    return doctor_model
示例#29
0
def patients_create(patient: schemas.PatientCreateIn, db: session) -> dict:
    password = pg.generate()

    patient_model = models.Patient(
        first_name=patient.first_name,
        last_name=patient.last_name,
        email=patient.email,
        phone_number=patient.phone_number,
        hashed_password=hashing.get_password_hash(password),
        doctor_id=patient.doctor_id)

    db.add(patient_model)
    db.commit()
    db.refresh(patient_model)

    patient_model.__dict__['password'] = password

    return patient_model
示例#30
0
def order_detail_flush_new(a_row: models.OrderDetail, a_session: session):
    """
    OrderDetail before_flush, new rows
    compute amount, adjust Order.AmountTotal
    .. which adjusts Customer.balance)
    """
    # no "old" in inserts...  old_row = get_old_row(a_row)
    row_prt(a_row, "\norder_detail_flush_new")  # readable log: curr/old values
    # nice try.. product = row.Product
    product = a_session.query(models.Product).\
        filter(models.Product.Id == a_row.ProductId).one()
    a_row.UnitPrice = product.UnitPrice
    a_row.Amount = a_row.Quantity * a_row.UnitPrice
    order = a_row.OrderHeader
    """
        2 issues make this a little more complicated than expected:
            1. can't just alter AmountTotal - does not trigger Order's before_flush
            2. can't just call Order's before_flush - old values not available
    """
    old_order = ObjectView(row2dict(order))
    order.AmountTotal += a_row.Amount
    order_update(order, old_order, a_session)
    row_prt(order, "order_detail_flush_new adjusted to: " +
            str(order.AmountTotal))