Exemplo n.º 1
0
    def add_history_to_db(self, history_dict):
        """add df to posrgresql database

        Args:
            df (pd.DataFrame): _description_
        """

        history_dict["layers"] = self.n_layers
        history_dict["neurons"] = self.fc_dim
        history_dict["batch_size"] = self.batch_size
        history_dict["epochs"] = self.epoch_avg
        history_dict["method"] = self.method
        history_dict["name"] = self.name
        history_dict["lr"] = self.lr
        history_dict["n_avg"] = self.n_avg
        history_dict["n_patience"] = self.n_patience
        history_dict["csv_dir"] = str(self.csv_dir)
        history_dict["data_name"] = str(self.data_name)
        history_dict["description"] = str(self.case_detail)
        history_dict["client"] = MachineConfig.client_name

        if history_dict["remain_parameters"]:
            history_dict["remain_parameters"] = list(
                map(str.strip, history_dict["remain_parameters"].split(",")))

        if history_dict["choosed_parameters"]:
            history_dict["choosed_parameters"] = list(
                map(str.strip, history_dict["choosed_parameters"].split(",")))

        if self.cv:
            history_dict["cv"] = self.cv
            history_dict["n_splits"] = self.n_splits
            history_dict["test_ratio"] = self.test_ratio

        if self.is_test:
            history_dict["is_test"] = self.is_test

        if self.method == "MIXED":
            history_dict["alpha"] = self.alpha

        if self.data_class == "Duct":
            history_step = models.DuctTable(**history_dict)
        elif self.data_class == "Toy":
            history_step = models.ToyTable(**history_dict)
        elif self.data_class == "Bubble":
            history_step = models.BubbleTable(**history_dict)
        else:
            raise "Not implemented yet"

        db = SessionLocal()
        try:
            db.add(history_step)
            db.commit()
            db.refresh(history_step)

        finally:
            db.close()
Exemplo n.º 2
0
async def websocket_endpoint(websocket: WebSocket, user: str):
    await manager.connect(websocket)
    db = None
    try:
        db = SessionLocal()
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(data, websocket)

    except WebSocketDisconnect:
        if db:
            db.close()
        manager.disconnect(websocket)
Exemplo n.º 3
0
 def get_task_urls(self, uuid: str, session: Session = SessionLocal()):
     try:
         return loads(
             session.query(
                 models.Task).filter(models.Task.uuid == uuid).first().urls)
     except:
         pass
Exemplo n.º 4
0
def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token,
                             Config.SECRET_KEY,
                             algorithms=[Config.ALGORITHM])
        nickname: str = payload.get("sub")
        if nickname is None:
            raise credentials_exception
    except PyJWTError:
        raise credentials_exception
    db = SessionLocal()
    user = get_user_by_nickname(db, nickname)
    db.close()
    if user is None:
        raise credentials_exception
    return user
Exemplo n.º 5
0
 def update_task_status(self,
                        uuid: str,
                        status: str,
                        session: Session = SessionLocal()):
     session.query(models.Task).filter_by(uuid=uuid).update(
         {"status": status})
     try:
         session.commit()
     except Exception:
         session.rollback()
     finally:
         session.close()
Exemplo n.º 6
0
 def create_task(self,
                 task: schemas.Task,
                 session: Session = SessionLocal()):
     task_model = models.Task(**task.dict())
     session.add(task_model)
     try:
         session.commit()
         session.refresh(task_model)
     except Exception:
         session.rollback()
     finally:
         session.close()
Exemplo n.º 7
0
 def check_credentials(self,
                       user: schemas.User,
                       session: Session = SessionLocal()):
     user_meta_as_dict = user.dict()
     user_meta_as_dict.update({
         "password":
         sha512(user_meta_as_dict.get("password").encode()).hexdigest()
     })
     user_model = models.User(**user_meta_as_dict)
     user_db = (session.query(models.User).filter(
         models.User.username == user_model.username).first())
     try:
         return user_db.password == user_model.password
     except:
         pass
Exemplo n.º 8
0
 def create_user(self,
                 user: schemas.User,
                 session: Session = SessionLocal()):
     user_meta_as_dict = user.dict()
     user_meta_as_dict.update({
         "password":
         sha512(user_meta_as_dict.get("password").encode()).hexdigest()
     })
     user_model = models.User(**user_meta_as_dict)
     session.add(user_model)
     try:
         session.commit()
         session.refresh(user_model)
     except Exception:
         session.rollback()
     finally:
         session.close()
Exemplo n.º 9
0
    def setup_class(cls):
        cls.db = SessionLocal()

        cls.new_user = schemas.UserCreate(nickname='nickname', password='******')
        cls.user: models.User = None

        cls.new_recipe = schemas.RecipeCreate(
            name='Recipe',
            description='Description',
            steps_making='1. asdfasdf 2.asdasd',
            type='Десерт',
            is_active=True,
            tags=['tag1', 'tag2'],
            date_creation='2020-04-09',
            author_id=0)
        cls.recipe: models.Recipe = None
        cls.photo = None

        cls.tags = ['Cake', 'Chocolate', 'Cream']
        cls.hashtags: List[models.Hashtag] = None
Exemplo n.º 10
0
    def setup_class(cls):
        cls.db = SessionLocal()

        cls.new_user = {'nickname': 'nick', 'password': '******'}
        cls.new_recipe = {
            'name': 'Recipe',
            'description': 'Description',
            'steps_making': '1. asdfasdf 2.asdasd',
            'type': 'dessert',
            'is_active': True,
            'date_creation': '2020-04-09',
            'author_id': 0
        }
        cls.recipe_id = None
        cls.user_id = None
        cls.jwt = {'user': None}

        cls.new_admin = {'nickname': 'admin', 'password': '******'}
        cls.admin = user.registration(cls.db,
                                      schemas.UserCreate(**cls.new_admin),
                                      'admin')
Exemplo n.º 11
0
 def get_db() -> Generator:
     try:
         db = SessionLocal()
         yield db
     finally:
         db.close()
Exemplo n.º 12
0
        """
        pass

    def delete_child(self):
        """
        expected behavior
        delete one child all parent remains
        """
        pass


def obj_creator():
    r = RDG(["name"])
    p1 = r()
    p2 = r()
    c1 = r()
    c2 = r()
    c3 = r()

    p1['children'] = [c1, c2]
    p2['children'] = [c1, c2]
    c3['parent'] = [p1, p2]
    # c1['p_id'] = 1
    # c2['p_id'] = 1
    return p1, p2, c1, c2, c3


p1, p2, c1, c2, c3 = obj_creator()
t = TestInstance(URL=SQLALCHEMY_DATABASE_URL, SETUP=True)
t.insert_all_by_once(db=SessionLocal(), parents=[p1, p2])
Exemplo n.º 13
0
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
Exemplo n.º 14
0
 def get_user_id(self, username: AnyStr, session: Session = SessionLocal()):
     return (session.query(models.User).filter(
         models.User.username == username).first().password)
Exemplo n.º 15
0
 def get_task_uuids(self, session: Session = SessionLocal()):
     return session.query(models.Task.uuid)
Exemplo n.º 16
0
app = Flask(__name__)
# CORS(app, resources={r"/*": {"origins": "https://flaskreactor.herokuapp.com"}})
pg = os.environ.get('DATABASE_URL')

# if ENV == 'dev':
#     app.debug = True
#     app.config['SQLALCHEMY_DATABASE_URI'] = LOCAL_DB

if ENV == 'prod':
    app.debug = False
    app.config['SQLALCHEMY_DATABASE_URI'] = pg

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SessionLocal()
models.Base.metadata.create_all(bind=engine)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/daily')
def daily():
    e_select = db.query(Daily).all()[0]
    e_info = vars(e_select)
    e_data = list(e_info.items())
    e_list = e_data[1:]
    e_filter = [item for item in e_list if 'symbol' in item]