async def post_orders(order_list: Orders): db = Session() order_ids = [] order_fail_ids = [] for order in order_list.data: db_order = OrderSchema(order_id=order.order_id, weight=order.weight, region=order.region, delivery_hours=order.delivery_hours) db.add(db_order) try: db.commit() except IntegrityError: order_fail_ids.append(order.order_id) else: db.refresh(db_order) order_ids.append(order.order_id) if len(order_fail_ids) == 0: return JSONResponse( content={'couriers': [{ 'id': c_id } for c_id in order_ids]}, status_code=status.HTTP_201_CREATED) else: return JSONResponse(content={ "validation_error": { 'couriers': [{ 'id': c_id } for c_id in order_fail_ids] } }, status_code=status.HTTP_400_BAD_REQUEST)
async def post_couriers(courier_list: Couriers): db = Session() courier_ids = [] courier_fail_ids = [] for courier in courier_list.data: db_courier = CourierSchema(courier_id=courier.courier_id, courier_type=courier.courier_type, regions=courier.regions, working_hours=courier.working_hours) db.add(db_courier) try: db.commit() except IntegrityError: courier_fail_ids.append(courier.courier_id) else: db.refresh(db_courier) courier_ids.append(courier.courier_id) if len(courier_fail_ids) == 0: return JSONResponse( content={'couriers': [{ 'id': c_id } for c_id in courier_ids]}, status_code=status.HTTP_201_CREATED) else: return JSONResponse(content={ "validation_error": { 'couriers': [{ 'id': c_id } for c_id in courier_fail_ids] } }, status_code=status.HTTP_400_BAD_REQUEST)
def today_orders_import(ctx): """ read orders from url and write new today orders into database """ url = 'https://online.moysklad.ru/api/remap/1.1/entity/customerorder' login = '******' password = '******' resp = get(url, auth=HTTPBasicAuth(login, password)) get_orders = resp.json() session_orders = Session() session_clients = Session() if settings.debug: today = date(2019, 2, 15) else: today = datetime.today().date() for i in get_orders['rows']: if datetime.strptime(i['moment'], "%Y-%m-%d %H:%M:%S").date() == today: if not session_orders.query(DenysOrders).filter( DenysOrders.id == i['id']).all(): client_data = get(i['agent']['meta']['href'], auth=HTTPBasicAuth(login, password)).json() if not session_clients.query(DenysClients).filter( DenysClients.id == client_data['id']).all(): session_clients.add( DenysClients( id=client_data['id'], name=client_data['name'], )) session_orders.add( DenysOrders( id=i['id'], name=i['name'], # description = moment=i['moment'], sum=i['sum'], counterparty_id=client_data['id'], )) session_clients.commit() session_orders.commit()
self.user = user_id self.quote = quote_id if reaction not in REACTIONS_OPTIONS: raise ModelError(f'reaction must be one of {REACTIONS_OPTIONS}') self.reaction = reaction self.seen_date = kwargs.get('creation_date', datetime.now().date()) def __str__(self): return f'Reaction[id={self.id}, seen_date={self.seen_date}, reaction={self.reaction}, user={self.user}, quote_id={self.quote}]' if __name__ == '__main__': Base.metadata.create_all(engine) session = Session() user = User('3649028588457703', 'DAILY') session.add(user) quote = Quote( "If you want to achieve greatness stop asking for permission.", "Anonymous") session.add(quote) session.commit() user_quote = Reaction('3649028588457703', quote.id, 'LIKE') session.add(user_quote) session.commit() session.close() print("=== Now querying data ===") session = Session() users = session.query(User).all() for user in users: print(user) quotes = session.query(Quote).all()
import csv from db.base import Session from db.models import Quote if __name__ == '__main__': session = Session() with open('quotes.csv', newline='') as csvfile: data = list(csv.reader(csvfile)) for row in data: print(row) quote = Quote(row[0], row[1]) session.add(quote) session.commit()
class Context: def __init__(self): Base.metadata.create_all(engine) self.session = Session() def getAdById(self, adId): return self.session.query(Ad).get(adId) def getAdByTitle(self, title): return self.session.query(Ad).filter_by(title=title).one_or_none() def getAdsByTags(self, tags): return self.session.query(Ad).filter(Ad.hiddenTags.any(Tag.value.in_(tags))).all() def addAd(self, ad): self._adTags(ad) try: self.session.commit() self.session.add(ad) self.session.commit() return ad except exc.SQLAlchemyError: print("Context: cannot create ad: ", ad) return None def getAds(self, limit, offset=0): return self.session.query(Ad).limit(limit).offset(offset).all() def updateAd(self, adId, updated): fromDb = self.getAdById(adId) if fromDb is None: return None self._removeTags(fromDb) self._adTags(updated) try: fromDb.update(updated) self.session.commit() return fromDb except exc.SQLAlchemyError: print("Context: cannot remove ad: ", fromDb) return None def _adTags(self, ad): try: for tag in ad.tags: self.session.add(tag) except exc.SQLAlchemyError: print("Context: cannot add hidden tags: ", ad.tags) return None try: for tag in ad.hiddenTags: self.session.add(tag) except exc.SQLAlchemyError: print("Context: cannot add hidden tags: ", ad.hiddenTags) def _removeTags(self, ad): try: for tag in ad.tags: self.session.query(ad_tags_association).filter_by(tag_id=tag.id).delete() self.session.delete(tag) self.session.commit() except exc.SQLAlchemyError: print("Context: cannot delete tags: ", ad.tags) return None try: for tag in ad.hiddenTags: self.session.query(hidden_ad_tags_association).filter_by(tag_id=tag.id).delete() self.session.delete(tag) self.session.commit() except exc.SQLAlchemyError: print("Context: cannot delete hidden tags: ", ad.hiddenTags) def removeAd(self, adId): fromDb = self.getAdById(adId) if fromDb is None: return False self._removeTags(fromDb) try: self.session.commit() self.session.delete(fromDb) self.session.commit() return True except exc.SQLAlchemyError: print("Context: cannot delete ad: ", fromDb) return False def getTagById(self, tagId): return self.session.query(Tag).get(tagId) def getTagByValue(self, value): return self.session.query(Tag).filter_by(value=value).first() def addTag(self, tag): self.session.add(tag) self.session.commit() def __del__(self): try: self.session.close() except AttributeError as err: print(err)
def main(): Base.metadata.drop_all(engine) Base.metadata.create_all(engine) models.Group.set_max_players_no(5) session = Session() address_1 = models.Address("city", "postcode", "street", 2) address2 = models.Address("city", "postcode", "street", 1) person = models.Person(first_name="Jan", last_name="Kowalski") owner_1 = models.EscapeRoomOwnerPerson(username="******", password="******", address=address2, er_owner_person=person) owner_2 = models.EscapeRoomOwnerCompany(username="******", password="******", name="Escapers Inc.", establishment_date=date( 2020, 1, 1), address=address_1) owner_3 = models.EscapeRoomOwnerCompany(username="******", password="******", name="Crazytown", establishment_date=date( 2020, 1, 1), address=address_1) escape_room1 = models.FixedPriceEscapeRoom( name="W krainie zła", opening_date=date(2020, 5, 1), category=models.EscapeRoomCategory.THRILLER, min_players_no=1, max_players_no=5, price=80, owner=owner_1) escape_room2 = models.VariablePriceEscapeRoom( name="Dziki zachód", opening_date=date(2020, 5, 1), category=models.EscapeRoomCategory.HORROR, min_players_no=1, max_players_no=5, max_price=15, price=80, owner=owner_3) escape_room3 = models.WeekendPriceEscapeRoom( name="Wszyscy ludzie prezydenta", opening_date=date(2020, 5, 1), category=models.EscapeRoomCategory.CRIME, min_players_no=1, max_players_no=5, weekend_price=90, price=80, owner=owner_2) escape_room4 = models.FixedPriceEscapeRoom( name="Uprowadzeni przez wampira", opening_date=date(2019, 1, 1), closing_date=date(2020, 5, 3), category=models.EscapeRoomCategory.THRILLER, min_players_no=1, max_players_no=5, price=80, owner=owner_2) escape_room5 = models.FixedPriceEscapeRoom( name="Rycerze", opening_date=date(2020, 5, 1), category=models.EscapeRoomCategory.HISTORY, min_players_no=1, max_players_no=5, price=80, owner=owner_2) escape_room6 = models.FixedPriceEscapeRoom( name="Subnautica", opening_date=date(2020, 5, 1), category=models.EscapeRoomCategory.ADVENTURE, min_players_no=1, max_players_no=5, price=80, owner=owner_1) group1 = create_group() player1 = models.Player(username="******", password="******", person=models.Person(first_name="Sandra", last_name="Rawicz")) player2 = models.Player(username="******", password="******", person=models.Person(first_name="Anna", last_name="Barańska")) player3 = models.Player(username="******", password="******", person=models.Person(first_name="Jan", last_name="Nowacki")) group2 = models.Group(name="Ja i mój chłopak", players=[player1]) group3 = models.Group(name="Znajomi z pracy", players=[player1, player2]) visit1 = models.Visit(group=group2, escape_room=escape_room2, visit_date=date(2020, 6, 19), duration=61, rating=3) visit2 = models.Visit(group=group3, escape_room=escape_room6, visit_date=date(2020, 6, 16), duration=50, rating=5) recommendation1 = models.Recommendation(player=player1, escape_room=escape_room1, expected_rating=4) recommendation2 = models.Recommendation(player=player2, escape_room=escape_room2, expected_rating=5) recommendation3 = models.Recommendation(player=player1, escape_room=escape_room3, expected_rating=3) objects = [ escape_room1, escape_room2, escape_room3, escape_room4, escape_room5, escape_room6, player3, group1, group2, group3, visit1, visit2, recommendation1, recommendation2, recommendation3 ] session.add(player1) try: session.commit() except Exception as ex: print(ex) for obj in objects: session.add(obj) try: session.commit() except Exception as ex: print(ex) print(person.player) print(person.er_owner) print(escape_room5.get_rating())
class PrometeyService(): def __init__(self): Base.metadata.create_all(engine) self.session = Session() self.__downloader = PrometeyDownloader() self.__amazon = PrometeyAmazon(config['aws']) @Transactional def register_user(self, telegram_user_id): user = User(telegram_user_id) self.session.add(user) return user @Transactional def get_user(self, telegram_user_id): user = self.session.query(User).filter(User.telegram_user_id == telegram_user_id).one_or_none() return user @Transactional def create_content(self, user_id, name): content = Content(name, 'DRAFT') content.user_id = user_id self.session.add(content) self.session.flush() user = self.session.query(User).filter(User.id == user_id).one() user.current_content = content return content @Transactional def change_current(self, user_id, new_content_id): user = self.session.query(User).filter(User.id == user_id).one() user.current_content_id = new_content_id @Transactional def add_url(self, user_id, url): user = self.session.query(User).filter(User.id == user_id).one() t = urlparse(url) if user.current_content and user.current_content.status == 'DRAFT' and t.hostname == 'vm.tiktok.com': video = Video(url) user.current_content.videos.append(video) return video else: pass # todo ошибка @Transactional def finish_video(self, user_id): user = self.session.query(User).filter(User.id == user_id).one() content = user.current_content if content: content.status = 'FINISHED' user.current_content_id = None return content # stay def get_download_list(self): videos = self.session.query(Video).join(Content). \ filter(Video.status == 'NEW').limit(3) return videos @Transactional def set_video_status_downloaded(self, video): video.status = 'DOWNLOADED' @Transactional def get_content_to_encode(self): content = self.session.query(Content).join(Video). \ filter(Content.status == "FINISHED"). \ filter(Content.all_downloaded).first() return content @Transactional def get_content_to_send(self): content = self.session.query(Content).filter(Content.status == "READY").first() return content @Transactional def set_content_status(self, content, status): content.status = status return content def download_videos(self): videos = self.get_download_list() for video in videos: self.__download_video(video) return videos @Transactional def __download_video(self, video): data = self.__downloader.download_video(video.url) print(f'{video.url} - скачано из сети.') key = f'{video.content_id}/{video.id}.mp4' print(f'Загружаю на s3 {key}') print(self.__amazon.upload(key, data)) video.status = 'DOWNLOADED'