コード例 #1
0
def get_db() -> Generator:
    db = SessionLocal()
    db.current_user_id = None
    try:
        yield db
    finally:
        db.close()
コード例 #2
0
ファイル: db-rki.py プロジェクト: j-gimbel/covid19
    def __init__(self):

        models.Base.metadata.create_all(bind=engine)
        self.session = SessionLocal()
        self.date_today = date.today().isoformat()

        self.sources = json.load(
            open(os.path.dirname(__file__) + "/../rki/sources.json", "r"))

        self.data_dir = "downloads"

        # create logger
        self.logger = logging.getLogger("create_db")
        self.logger.setLevel(logging.DEBUG)
        # create formatter
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        # add formatter to ch
        ch.setFormatter(formatter)
        # add ch to logger
        self.logger.addHandler(ch)
        # create file handler and set level to debug
        fh = logging.FileHandler("create_db.log")
        fh.setLevel(logging.DEBUG)
        # add formatter to ch
        fh.setFormatter(formatter)
        # add ch to logger
        self.logger.addHandler(fh)
コード例 #3
0
def get_db():
    db = SessionLocal()

    try:
        yield db
    finally:
        db.close()
コード例 #4
0
def test_create_prescription(client, mocker):
    data = {
        "clinic": "1",
        "physician": "1",
        "patient": "1",
        "text": "Dipirona 1x ao dia"
    }

    mocker.patch.object(Metric, '_send_metrics', return_value=True)

    response = client.post("/prescriptions/",
                           headers={"Content-Type": "application/json"},
                           json=data)
    assert response.status_code == 200

    result = response.json()
    assert result['clinic'] == int(data['clinic'])
    assert result['physician'] == int(data['physician'])
    assert result['patient'] == int(data['patient'])
    assert result['text'] == data['text']

    db = SessionLocal()
    prescription_db = db.query(models.Prescription).filter(
        models.Prescription.id == result['id']).first()
    db.close()
    assert prescription_db.id == result['id']
コード例 #5
0
ファイル: main.py プロジェクト: opacam/user-service
def get_db():
    """A function to get a database session."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
コード例 #6
0
def init():
    db = SessionLocal()

    status = crud.status.get(db)
    if not status:
        crud.status.create(db, obj_in={'id': 0, 'status': False})

    settings = crud.settings.get(db)
    if not settings:
        crud.settings.create(db, obj_in={'id': 0, 'smart_off': True})

    bri_curve = crud.curve.get_default_by_kind(db, kind='bri')
    if not bri_curve:
        bri_curve = models.Curve(name='Default', kind='bri', default=True)
        models.Point(x=0, y=245, first=True, curve=bri_curve)
        models.Point(x=360, y=216, curve=bri_curve)
        models.Point(x=660, y=182, curve=bri_curve)
        models.Point(x=900, y=221, curve=bri_curve)
        models.Point(x=1080, y=27, curve=bri_curve)
        models.Point(x=1440, y=12, last=True, curve=bri_curve)
        db.add(bri_curve)

    ct_curve = crud.curve.get_default_by_kind(db, kind='ct')
    if not ct_curve:
        ct_curve = models.Curve(name='Default', kind='ct', default=True)
        models.Point(x=0, y=153, first=True, curve=ct_curve)
        models.Point(x=420, y=324, curve=ct_curve)
        models.Point(x=900, y=347, curve=ct_curve)
        models.Point(x=1080, y=475, curve=ct_curve)
        models.Point(x=1440, y=500, last=True, curve=ct_curve)
        db.add(ct_curve)

    db.commit()
    db.close()
コード例 #7
0
def external_apis_fetch_data(data_type: str,
                             external_api_id: int = None,
                             platform_id: int = None):
    try:
        data_type = DataTypeEnum[data_type]
    except KeyError:
        # TODO details
        raise Exception()

    # Init DB Session
    db = SessionLocal()

    if external_api_id is not None:
        # Read external api object
        external_api_db = crud.external_api.get(db, external_api_id)
        if external_api_db is None:
            # TODO details
            raise Exception()

        # Read platform object
        platform = external_api_db.account.platform
        if platform is None:
            # TODO details
            raise Exception()
    elif platform_id is not None:
        external_api_db = None
        platform = crud.platform.get(db, platform_id)
    else:
        # TODO details
        raise Exception()

    # Load module
    platform_module = platform_to_module[platform.name]

    # TODO create loop

    # Get the request
    request = platform_module.get_fetch_data_request(data_type,
                                                     external_api_db)

    sleep(request.rate_limit / 1000)

    # Send the request
    response = requests.request(method=request.method,
                                url=request.url,
                                params=request.parameters,
                                data=request.data,
                                headers=request.headers)

    account_id = external_api_db.account_id if external_api_db is not None else None
    platform_module.write_results(db, response.content, data_type, account_id)

    # TODO write in DB (re-send to external_api module)

    # logger.info(test)

    db.close()
コード例 #8
0
ファイル: db-rki.py プロジェクト: j-gimbel/covid19
 def _clear_db(self):
     print("clearing")
     self.session.close()
     print(os.path.dirname(__file__) + "/../database.db")
     os.remove(os.path.dirname(__file__) + "/../database.db")
     # print(models.Base.metadata.tables.values())
     # models.Base.metadata.drop_all(bind=engine)
     models.Base.metadata.create_all(bind=engine)
     self.session = SessionLocal()
コード例 #9
0
def prescription():
    prescription = schemas.PrescriptionCreate(clinic=1,
                                              physician=1,
                                              patient=1,
                                              text='Dipirona 1x ao dia')
    db = SessionLocal()
    db_prescription = crud.create_prescription(db=db,
                                               prescription=prescription)
    db.close()

    return db_prescription
コード例 #10
0
ファイル: schedules.py プロジェクト: LukasPatzke/ambientHUE
def reset_offsets():
    db = SessionLocal()

    curves = crud.curve.get_multi(db)
    for curve in curves:
        try:
            crud.curve.update(db, db_obj=curve, obj_in={'offset': 0})
        except HTTPException as e:
            log.error(e.detail)
    log.info('Reset offset for %s curves', len(curves))
    db.close()
コード例 #11
0
def populate_database() -> None:
    db = SessionLocal()

    with open("initial_data.json") as json_file:
        initial_data = json.load(json_file)

        add_asset_types(db, initial_data["asset_types"])
        add_platforms(db, initial_data["platforms"])
        add_transaction_types(db, initial_data["transaction_types"])
        add_assets(db, initial_data["assets"])

    add_platforms_assets(db)

    db.close()
コード例 #12
0
def create_default_data():
	hpassword = bcrypt.hashpw(bytes("123", 'utf-8'), bcrypt.gensalt())
	db = SessionLocal()
	objects = [
	    models.User(username="******", fullname="Archibald Weng", password=hpassword),
	    models.User(username="******", fullname="Boris Tien", password=hpassword),
	    models.User(username="******", fullname="Larry Chuang", password=hpassword),
	    models.User(username="******", fullname="Thomas Lin", password=hpassword),
	    models.User(username="******", fullname="Dora Yen", password=hpassword),
	    models.User(username="******", fullname="Wimy Kuo", password=hpassword),
	    models.User(username="******", fullname="Kathy Wu", password=hpassword),
	    
	    models.Task(taskname="TIIP", fullname="TIIP-全方位減碳系統服務平台開發計畫", organization="永智"),
	    models.Task(taskname="108高雄溫管", fullname="108年高雄市溫室氣體管理計畫", organization="臺中市政府環境保護局"),
	    models.Task(taskname="108台中溫減", fullname="108年台中市溫室氣體減量計畫", organization="臺中市政府環境保護局"),
	    models.Task(taskname="109台中溫減", fullname="109年台中市溫室氣體減量計畫", organization="臺中市政府環境保護局"),
	    models.Task(taskname="台電-風力", fullname="台灣電力公司風力發電計畫(一)抵換專案", organization="台灣電力股份有限公司環境保護處"),
	    models.Task(taskname="台電-太陽光電", fullname="台灣電力公司台中及興達太陽光電計畫", organization="台灣電力股份有限公司環境保護處"),
	    models.Task(taskname="108台電-碳限制計畫", fullname="台電公司碳限制管理及對策研析計畫", organization="台灣電力股份有限公司環境保護處"),
	    models.Task(taskname="尚承-盤查", fullname="尚承鋼鐵股份有限公司108年度溫室氣體盤查", organization="尚承鋼鐵股份有限公司"),
	    models.Task(taskname="尚承-抵換", fullname="尚承鋼鐵加熱爐能源效率提升及天然氣替代重油溫室氣體減量抵換專案", organization="尚承鋼鐵股份有限公司"),
	    models.Task(taskname="109低碳辦", fullname="109年臺中市低碳城市推動計畫", organization="臺中市政府環境保護局"),
	    models.Task(taskname="106CORSIA", fullname="推動我國國際航空業碳抵換及減量計畫第一期計畫", organization="交通部民用航空局"),
	    models.Task(taskname="109CORSIA", fullname="推動我國國際航空業碳抵換及減量計畫第二期計畫", organization="交通部民用航空局"),

	    models.Task(taskname="瑞振工業-盤查及SBTi專案", fullname="瑞振工業溫室氣體管理專案", organization="瑞振工業公司"),
	    models.Task(taskname="108台電-碳限制計畫", fullname="台電公司碳限制管理及對策研析計畫", organization="台灣電力股份有限公司環境保護處"),

	]
	db.bulk_save_objects(objects)
	db.commit()
	db.close()
コード例 #13
0
def seed_brand_data():
    logger.info("Seeding brands")
    db = SessionLocal()
    if crud.brand.count(db) > 0:
        return
    json_file = os.path.join(settings.BASE_DIR, 'app', 'database', 'data',
                             'brands.json')
    with open(json_file) as json_file:
        data = json.load(json_file)
        db = SessionLocal()
        for brand_data in data:
            brand = crud.brand.get_by_id(db=db, id=brand_data['id'])
            if not brand:
                brand = BrandCreate(**brand_data)
                crud.brand.create(db, object_to_create=brand)
コード例 #14
0
def seed_item_data():
    logger.info("Seeding items")
    db = SessionLocal()
    if crud.item.count(db) > 0:
        return
    json_file = os.path.join(settings.BASE_DIR, 'app', 'database', 'data',
                             'items.json')
    with open(json_file) as json_file:
        data = json.load(json_file)
        db = SessionLocal()
        for item_data in data:
            item = crud.item.get_by_id(db=db, id=item_data['id'])
            if not item:
                item = ItemCreate(**item_data)
                crud.item.create(db, object_to_create=item)
コード例 #15
0
def seed_discount_data():
    logger.info("Seeding discounts")
    db = SessionLocal()
    if crud.discount.count(db) > 0:
        return
    json_file = os.path.join(settings.BASE_DIR, 'app', 'database', 'data',
                             'discounts.json')
    with open(json_file) as json_file:
        data = json.load(json_file)
        db = SessionLocal()
        for discounts_data in data:
            discount = crud.discount.get_by_id(db=db, id=discounts_data['id'])
            if not discount:
                discount = DiscountCreate(**discounts_data)
                crud.discount.create(db, object_to_create=discount)
コード例 #16
0
def seed_product_data():
    logger.info("Seeding products")
    db = SessionLocal()
    if crud.product.count(db) > 0:
        return
    json_file = os.path.join(settings.BASE_DIR, 'app', 'database', 'data',
                             'products.json')
    with open(json_file) as json_file:
        data = json.load(json_file)
        db = SessionLocal()
        for product_data in data:
            product = crud.product.get_by_id(db=db, id=product_data['id'])
            if not product:
                product = ProductCreate(**product_data)
                crud.product.create(db, object_to_create=product)
コード例 #17
0
ファイル: schedules.py プロジェクト: LukasPatzke/ambientHUE
def scheduled_sync():
    try:
        db = SessionLocal()
        api = get_api(db)
        log.info(crud.bridge.sync(db, api))
    except HTTPException as e:
        log.error(e.detail)
コード例 #18
0
def create_repository():
    try:
        repository = Repository()
        repository.set_db(SessionLocal())
        yield repository
    finally:
        repository.close()
コード例 #19
0
ファイル: schedules.py プロジェクト: LukasPatzke/ambientHUE
def scheduled_run():
    try:
        db = SessionLocal()
        api = get_api(db)
        run(db=db, api=api)
    except HTTPException as e:
        log.error(e.detail)
コード例 #20
0
ファイル: manage.py プロジェクト: ischaojie/soulapi
def createsuperuser(noinput: bool = typer.Option(
    False, help="create superuser in env")):
    db = SessionLocal()

    if noinput:
        username = settings.SUPERUSER_NAME
        email = settings.SUPERUSER_EMAIL
        password = settings.SUPERUSER_PASSWORD

    else:
        username = typer.prompt("username:"******"admin")
        email = typer.prompt("email:", default="*****@*****.**")
        password = typer.prompt("password:"******"This email superuser already exist")
        exit(0)

    user_db = crud.user.create_superuser(db, obj=superuser)
    typer.echo("superuser created.")
コード例 #21
0
def run_water(zone, alias, minutes):
    with SessionLocal() as db:
        start_time = datetime.now()
        b = Board(
        )  # init a new board since tasks dont seem to have GPIO setup...
        b.register_flow()

        temperature = b.get_temp()
        db.add(Temperature(temperature))
        db.commit()

        #     moisture0 = board.read_analog_sensor(analog0)
        #     moisture1 = board.read_analog_sensor(analog1)
        #     moisture2 = board.read_analog_sensor(analog2)
        #     moisture3 = board.read_analog_sensor(analog3)
        #     sql_helper.insert_moistures(moisture0, moisture1, moisture2, moisture3)

        b.set_high(pins[zone])
        time.sleep(minutes *
                   60)  # sleep for our duration with the solenoid open
        b.set_low(pins[zone])

        water_used = b.read_water_flow()
        db.add(Water(zone, alias, start_time, water_used))
        db.commit()

        b.deregister_flow()
コード例 #22
0
 async def db_session_middleware(request: Request, call_next):
     try:
         request.state.db = SessionLocal()
         response = await call_next(request)
     finally:
         request.state.db.close()
     return response
コード例 #23
0
    def valid_platform_id(cls, v):
        db = SessionLocal()

        platform = crud.platform.get(db, v)
        if platform is None:
            raise ValueError("The platform is invalid")

        return v
コード例 #24
0
async def db_session_middleware(request: Request, call_next):
    response = Response("Internal server error", status_code=500)
    try:
        request.state.db = SessionLocal()
        response = await call_next(request)
    finally:
        request.state.db.close()
    return response
コード例 #25
0
async def db_session_middleware(request: Request, call_next):
    response = Response("Unexpected error", status_code=404)
    try:
        request.state.db = SessionLocal()
        log.info("Opened a db session instance")
        response = await call_next(request)
    finally:
        log.info("Closing the db session instance")
        request.state.db.close()
    return response
コード例 #26
0
ファイル: crud.py プロジェクト: kowabunga314/LifeLoot
def end_game(session: SessionLocal, game_id: int):
    game = session.query(models.Game).filter(models.Game.id == game_id).first()

    # Make sure game was found
    if not game:
        raise LookupError()

    game.active = False

    return game
コード例 #27
0
def process_data():
    data: pd.DataFrame = pd.read_excel('tmp/pydev_test_task_data2.xlsx')

    data = data.sort_values('timestamp')

    conn = engine.connect()
    Data.create(engine)

    with SessionLocal() as session:
        conn.execute(Data.insert(), data.to_dict('records'))
        session.commit()
コード例 #28
0
def startup_event():
    Base.metadata.create_all(bind=engine)
    db: Session = SessionLocal()
    user = crud.get_user_by_email(db, settings.super_user_email)
    if not user:
        user_in = users_schemas.UserCreate(
            email=settings.super_user_email, password=settings.super_user_password
        )
        logging.info("Creating superuser")
        crud.create_user(db, user_in)
    db.close()
コード例 #29
0
    def account_has_platform(cls, v):
        db = SessionLocal()

        account = crud.account.get(db, v)
        if account is None:
            raise ValueError("The account id is invalid")

        if account.platform_id is None:
            raise ValueError("The account is not linked to any platform")

        return v
コード例 #30
0
ファイル: auth.py プロジェクト: rikuuuuu/media-python
def get_current_user_from_token(token: str, token_type: str):
    # """tokenからユーザーを取得"""
    # トークンをデコードしてペイロードを取得。有効期限と署名は自動で検証される。
    payload = jwt.decode(token, "SECRET_KEY123", algorithms=["HS256"])

    # トークンタイプが一致することを確認
    if payload["token_type"] != token_type:
        raise HTTPException(status_code=401, detail=f"トークンタイプ不一致")

    # DBからユーザーを取得
    # user = User.get_by_id(payload['user_id'])
    db = SessionLocal()
    user = db.query(User).filter(User.id == int(payload["user_id"])).first()

    # リフレッシュトークンの場合、受け取ったものとDBに保存されているものが一致するか確認
    if token_type == "refresh_token" and user.refresh_token != token:
        print(user.refresh_token, "¥n", token)
        raise HTTPException(status_code=401, detail="リフレッシュトークン不一致")

    return user