def store(modelName, values): module = importlib.import_module('database.tables.'+modelName+'Table') modelName = getattr(module, modelName) print values md = modelName(**values) session.add(md) session.commit()
def add_bills(*args): add = Bills(bill_name=args[0], base_amount_due=args[1], actual_amount_due=args[2], due_date=args[3]) session.add(add) session.commit()
def save(self, session): self.deliveryDataToTable(Film, Categorie, self.categories, session) self.deliveryDataToTable(Film, Production, self.productions, session) self.deliveryDataToTable(Film, Acteur, self.acteurs, session) self.deliveryDataToTable(Film, Directeur, self.directeurs, session) session.add(self) session.commit()
def auth_user(login, password, type): """ @rtype : object """ session = Session() users = session.query(User).order_by(User.id) users_logins = [] for instance in users: users_logins.append(instance.login) for instance in users: if login in users_logins and login == instance.login: user = instance if not check_pass(user, password): return False else: return start_sys(user, session) elif not login in users_logins: if type == "guest": default_room = session.query(Room).filter(Room.name == "default").one() guest_perm = session.query(Perm).filter(Perm.name == "guest").one() a = Associations() a.user = User(login, login, None, 0) u = a.user a.perm = guest_perm default_room.user.append(a) session.add(a) session.commit() return start_sys(u, session) else: continue session.commit() session.close()
def insertEndereco(rua_, numero_, cep_, pessoa_): session = DBSession() e = Endereco(rua=rua_, numero=numero_, cep=cep_, pessoa=pessoa_) session.add(e) session.commit() session.close() return e
def register_user(password): Base.metadata.create_all(engine) pwd_hashed = bcrypt.hashpw(password, bcrypt.gensalt()) user = User(password=pwd_hashed) session.add(user) session.commit()
def db_add_consumption(dct, user): # mthd currently assumes input data fmt matches col names. # need a way to reformat here? dct['user'] = user cons = Consumption(**dct) # unfolds dict session.add(cons) session.commit()
def insertPessoa(nome_, email_): session = DBSession() p = Pessoa(nome=nome_, email=email_) session.add(p) session.commit() session.close() return p
def main(): try: engine = sqlalchemy.create_engine(MYSQL_URL, echo=True) # 返回所有的操作信息 sqlalchemy.orm.session.Session = sqlalchemy.orm.sessionmaker( bind=engine) # 創建Session類型 session = sqlalchemy.orm.session.Session() # 實例化Session對象 bir_date = datetime.datetime.strptime("2016-11-30", "%Y-%m-%d") # 字符串轉為日期 user = User(name="沐言優拓-小李老師", age=16, birthday=bir_date, salary=24000.00, note="www.example.com") logging.info( "--------------------------通過session保存數據--------------------------------" ) session.add(user) # 瞬時態進入到預備態(與session關聯) session.commit() # 事務提交(預備態變為了持久態) logging.info( "--------------------------第一次session事務提交--------------------------------" ) user.name = "爆可愛的小李老師" # 修改持久態下的屬性內容 logging.info( "--------------------------第二次session事務提交--------------------------------" ) session.commit() # 事務提交(預備態變為了持久態) session.close() # 關畢session(釋放連接) except Exception as e: logging.info(traceback.format_exc())
def addRestaurant(resturantName): """ Adds a new Restaurant to the database. """ temp = Restaurant(name=resturantName) session.add(temp) session.commit()
def add(self, item): """ Add an item to storage. Parameters ---------- item : metags.core.Item Returns ------- metags.core.Item """ # FIXME: Handle this by emitting an event instead. The goal would be # to offload calculating this to workers in parallel. Just use # sqlalchemy's event system to monitor new Entity rows? if not item.c4: item.c4 = item.c4id() with self.transaction() as session: try: entity = self.to_entity(item) except NoResultFound: entity = Entity(c4=item.c4, url=item.url) session.add(entity) self.link_meta(entity, item.metadata) return self, item
def add_bank(*args): add = Bank( bank_name=args[0], checkings_total=args[1], savings_total=args[2], ) session.add(add) session.commit()
def funcion_update(funcion): currentFuncion = session.query(Funcion).filter( Funcion.id == funcion.id).first() currentFuncion.codigo = funcion.codigo currentFuncion.nombre = funcion.nombre currentFuncion.pelicula = funcion.pelicula currentFuncion.formato = funcion.formato session.add(currentFuncion) session.commit()
def login(email,password): usuario = session.query(Usuario).filter(Usuario.email == email).filter(Usuario.password == password).first() token = None if usuario is not None: usuario.token = str(uuid.uuid4()) session.add(usuario) session.commit() token = usuario.token return token
def clasificacion_update(clasificacion): currentClasificacion = session.query(Clasificacion).filter( Clasificacion.id == clasificacion.id).first() currentClasificacion.identificador = clasificacion.identificador currentClasificacion.edadMinima = clasificacion.edadMinima currentClasificacion.recomendacion = clasificacion.recomendacion currentClasificacion.definicion = clasificacion.definicion session.add(currentClasificacion) session.commit()
def upgrade(): session = sa.orm.session.Session(bind=op.get_bind()) if session.query(TagCategory).count() == 0: category = TagCategory() category.name = 'default' category.color = 'default' category.version = 1 category.default = True session.add(category) session.commit()
def _schema_test_db_Counters_1record(session: sqlalchemy.orm.session.Session, _schema_test_db_Counters: None) -> None: """ Initialize database: add one record to Counters table. """ session.add(Counters(name='foo', count=0)) session.commit( ) # type: ignore[no-untyped-call] # TODO: untyped commit()??
def main(): engine = sqlalchemy.create_engine(MYSQL_URL,encoding="UTF8",echo=True) sqlalchemy.orm.session.Session = sqlalchemy.orm.sessionmaker(bind=engine) session = sqlalchemy.orm.session.Session() date = time.strftime("%Y-%m-%d",time.localtime()) date_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) meters_data = Meters_data(meter_value=500,get_date=date,get_date_time=date_time,get_date_stamp=date_time,meter_addr="x9999") session.add(meters_data) session.commit() print("data add success,current id is :%s" % meters_data.auto_id) session.close()
def create_post(username, post: str = ''): session = Session() user: User = session.query(User).filter_by(username=username).one_or_none() print('fetching user:'******'users post:', post) print('post after', user.posts) session.close()
def get_or_create(session, model, **kwargs): instance = session.query(model).filter_by(**kwargs).first() if instance: return instance else: params = dict((k, v) for k, v in kwargs.iteritems() if not isinstance(v, ClauseElement)) instance = model(**params) session.add(instance) session.flush() session.commit() return instance
def create_user(name: str, is_staff: bool = False) -> bool: session = Session() username = name try: user = User(username=username, is_staff=is_staff) session.add(user) session.commit() session.close() return 1 except sqlalchemy.exc.IntegrityError as eerr: print('There was an error:', eerr) session.close() return 0
def fill_one_financial(ticker: str, year: int = 1900): with get_session() as session: stock0: Stock = session.query(Stock).filter_by( stock_ticker=ticker).one() # asking print('current financials:', stock0) pe = randrange(1, 100) pb = randrange(1, 100) fin = Financials(price_book=pb, price_earning=pe, year=year, refer_stock_ticker=stock0.stock_ticker) session.add(fin) print('financials after', stock0.financials)
def write_stock(stock): session = Session() for c in stock: print(c) stock_filling = Stock( stock_name=(stock[0]), stock_ticker=(stock[1]), stockable=True, mark_cap=stock[3], ) print('printing...', stock_filling) session.add(stock_filling) session.commit() session.close()
def addjob(session,jlist): for j in jlist : session.add(j) session.commit() class Jobs(Base): _tablename_ = 'Jobs' id = column(Integer,primary_key = True) jen_id = Column(Integer) name = Column(String) timeStamp = Column(DateTime) result = Column(String) building = Column(String) estimatedDuration = Column(String)
def precio_create(): precio = session.query(Precio).first() tipo = session.query(TipoPrecio).filter( TipoPrecio.id == precio.tipoPrecio.id).first() session.query(Precio).filter(Precio.tipoPrecio == precio.tipoPrecio and Precio.activo == True).update( dict(activo=False)) session.add( Precio(nombre="A", codigo="A", valor=333, id_tipoPrecio=tipo.id, activo=True)) session.add(precio) session.commit()
def add_u_to_the_r(uname, room_name, perm_name): session = Session() new_u = Associations() user = session.query(User.id).filter(User.name == uname).scalar() room = session.query(Room.id).filter(Room.name == room_name).scalar() perm = session.query(Perm.id).filter(Perm.name == perm_name).scalar() new_u.user_id = user new_u.perm_id = perm new_u.room_id = room session.add(new_u) session.commit() room_obj = session.query(Room).get(room) room_users = [] the_room = {} for r_user in room_obj.user: room_users.append(session.query(User.name).filter(User.id == r_user.user_id).one()[0]) for r_user in room_obj.user: if r_user.user_id == user: the_room = dict( room_name=room_obj.name, perm=session.query( Perm.id, Perm.name, Perm.add_user, Perm.create_room, Perm.create_vote, Perm.delete_room, Perm.delete_user, Perm.delete_vote, Perm.make_secure, Perm.make_unsecure, Perm.voting, Perm.edit_perm, Perm.edit_perm_def, ) .filter(Perm.id == r_user.perm_id) .one() .__dict__, users=room_users, secure=room_obj.secure, auth=room_obj.auth, ) add_user_obj = {"user_name": uname, "room": the_room} session.close() return add_user_obj
def __init__(self, session: orm.session.Session, code: str, canonicalName: str, otherNames: typing.List[str] = [], protoLanguage: 'Language' = None, family: 'Family' = None, wikidata_item: str = None): self._code = code self._canonical_name = canonicalName self._other_names = json.dumps(otherNames) # self._proto_language = proto_language self._family = family self._wikidata_item = wikidata_item session.add(self)
def main(): try: engine = sqlalchemy.create_engine(MYSQL_URL, echo=True) # 返回所有的操作信息 sqlalchemy.orm.session.Session = sqlalchemy.orm.sessionmaker( bind=engine) # 創建Session類型 session = sqlalchemy.orm.session.Session() # 實例化Session對象 roles = session.query(Role).filter(Role.rid.in_(["admin", "audit"])).all() user = User(uid="python", name="小李老師", roles=roles) session.add(user) session.commit() session.close() # 持久態轉為游離態 except Exception as e: logging.info(traceback.format_exc())
def initialize_states(self, session): with open(os.path.join(os.path.dirname(__file__), 'states.json')) as f: state_data = json.load(f) order = 0 for state in state_data: order += 1 if isinstance(state, str): state = dict(title=state) substates = state.pop("substates", ()) state = State(session, self, order, **state) session.add(state) for sub in substates: order += 1 sub['parent'] = state session.add(State(session, self, order, **sub))
def main(): engine = sqlalchemy.create_engine(MYSQL_URL, encoding='UTF8', echo=True) sqlalchemy.orm.session.Session = sqlalchemy.orm.sessionmaker( bind=engine) #创建sesstion类型 session = sqlalchemy.orm.session.Session() bir_date = datetime.datetime.strptime("2015-11-6", "%Y-%m-%d") user = User(name='小李', age=15, birthday=bir_date, salary=2400, note='aaaaaa') #user.name=''xiao白 可以更改数据 session.add(user) #sql处理(orm)转换 session.commit() print('数据保存成功,当前ID为%s' % user.uid) session.close()
def create_post(title: str, content: str, author: str): post = Post() post.title = title post.content = content post.author = author post.pub_status = 'private' session = db_session.create_session() try: session.add(post) session.commit() finally: session.close() return post.id
async def ban(self, ctx, user_id: int, days: int, *reason): # Check to see if they've already been banned async with sessionmaker() as session: person = await session.get(Banned, user_id) if person is None: user = await self.bot.fetch_user(user_id) unban_time = int(time.time()) + (days * 86400) str_reason = ' '.join(reason) ban_enter = Banned(user_id=user_id, nickname=user.display_name, unban_timestamp=unban_time, reason=str_reason) session.add(ban_enter) await session.commit() if days != -1: await ctx.send(f"User has been banned for {days} days") else: await ctx.send(f"User has been banned Indefinitely") else: await ctx.send("That user is already banned")
def addMenuItem( name=None, id=None, course=None, description=None, price=None, restaurant_id=None ): """ Adds a new Menu Item to the Database, each item is associated with a restaurant. """ temp = MenuItem( name=name, description=description, course=course, price=price, restaurant_id=restaurant_id, ) session.add(temp) session.commit()
password = Column(String(70)) def __repr__(self): return "<User(name='%s', fullname='%s', password='******')>" % ( self.name, self.fullname, self.password) # In order to connect to the database use 'mysql+pymysql' Session = sessionmaker() engine = create_engine('mysql+pymysql://root:[email protected]/wtg_bis') Session.configure(bind=engine) session = Session() # metadata = MetaData() #Base.metadata.drop_all(engine, checkfirst=False) Base.metadata.create_all(engine) print "starting" ed_user = User( name='ed', fullname='Ed Jones', password='******') print ed_user.name print ed_user.password print str(ed_user.id) session.add(ed_user) session.add_all([ User(name='wendy', fullname='Wendy Williams', password='******'), User(name='mary', fullname='Mary Contrary', password='******'), User(name='fred', fullname='Fred Flinstone', password='******')]) session.commit()
class A(Base, Mixin): __tablename__ = "As" a_id = Column("id", Integer, primary_key=True) def __init__(self, b=None): Mixin.__init__(self, b) class B(Base): __tablename__ = "Bs" b_id = Column("id", Integer, primary_key=True) engine = create_engine("sqlite:///:memory:") Session = sessionmaker(bind=engine) session = Session() Base.metadata.create_all(engine) b = B() session.add(b) session.commit() #print session.query(B).first() a = A() assert a.b is b
def install_chat(session, PORT): """ This is a procedure for first setup chat application. It use the command line for setup first user - root user, whom will has fool permissions. """ print "It's first run of the CHAT SERVER.\nSo you need to answer few questions..." login = raw_input("Please type the nick-name (Login) of the root user: "******"\nPlease type your fool name (Screen Name):") password = make_server_password() root_perm = Perm("root", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) admin_perm = Perm("admin", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0) authorised_perm = Perm("auth_user", 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0) guest_perm = Perm("guest", 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0) default_room = Room("default") a = Associations() a.user = User(login, name, password, 1) a.perm = root_perm default_room.user.append(a) session.add(a) session.add(root_perm) session.add(admin_perm) session.add(authorised_perm) session.add(guest_perm) session.add(default_room) session.commit() session.close() print "\nThanks." print "\nChat server started on port " + str(PORT) logging.info("chat was installed")