예제 #1
0
    def check_book():
        """
        This method checks book discounts every 36 minutes and removes books from which no one is subscribed.
        If there is a discount, then it calls the method of notifying subscribers.
        """

        parser = parser_manager.ParserManager()
        bot_ = bot.Bot()
        while True:
            database = Database()
            books = database.get_books()
            database.delete_empty_subscriptions()

            for book in books:
                try:
                    book_detail = parser.parsing_book(book['link'])

                    if book_detail['price'] != book['price']:
                        database.change_price(book['link'],
                                              book_detail['price'])

                        if book_detail['price'] < book['price']:
                            sale = 100 - int(
                                book_detail['price'] / book['price'] * 100)
                            for follower in book['followers']:
                                if database.check_service(follower):
                                    bot_.send_notification(
                                        follower, book_detail, sale)
                except AttributeError as ae:
                    logger.show_error(system="Book24", error=repr(ae))

            database.__del__()
            time.sleep(2200)
예제 #2
0
    def save_state(self, sqlite_db=None):
        """
        Saves all the data currently in the program to an sqlite database provided.
        If no db is provided, a default database is used
        :param sqlite_db:
        :return:
        """
        if sqlite_db is None:
            db = Database()
        else:
            if len(sqlite_db) < 7:
                return "short"
            elif sqlite_db.split(".")[-1] != "sqlite":
                return "not sqlite file"
            else:
                db = Database(sqlite_db)

        db.clear_state()
        # loop through all the people in the list and save them in the sqlite database
        for person in self.all_people:
            db.add_person(person)

        # loop through all the rooms in the list and save them in the sqlite database
        for room in self.all_rooms:
            db.add_room(room)

        print('State of the application saved successfully')
        print("\n\n\t\t\t---------------------------\n\n")

        return sqlite_db
예제 #3
0
    def stop_user(self, message: Message):
        """
        Make the subscriber inactive.
        """

        logger.show_msg(message)
        database = Database()
        database.stop_following(message.chat.id)
        self.typing(1, message)
        self.bot.send_message(chat_id=message.chat.id,
                              text="Прощайте.\n"
                              "Надеемся, вы вернётесь 😌")
예제 #4
0
    def start_user(self, message: Message):
        """
        Send a welcome message to the user and makes his status active.
        """

        logger.show_msg(message)
        database = Database()
        database.start_following(message.chat.id)
        self.typing(1, message)
        self.bot.send_message(
            chat_id=message.from_user.id,
            parse_mode='Markdown',
            text="Привет, я помогу тебе отслеживать скидки на книги!\n"
            "Хочешь добавить книгу?\n"
            "Просто отправь `ссылку` на неё.")
예제 #5
0
class Peak(Database.instance().Base, CRUDMixin):
    """Model for measures table
    """
    __tablename__ = 'peaks'

    registered_at = Column(
        DateTime,
        primary_key=True)  # este id es del smartcitizen no del sensor
    peak_value = Column(Float)

    @classmethod
    def find_last_min(cls, time):
        """Search setting by name"""
        session = Database.instance().session()
        return session.query(Peak).filter(
            and_(Peak.registered_at > time + timedelta(minutes=-1),
                 Peak.registered_at <= time)).all()

    @classmethod
    def destroy_processed(cls, time):
        """Search setting by name"""
        session = Database.instance().session()
        session.query(Peak).filter(
            Peak.registered_at <= time + timedelta(minutes=-1)).delete()
        session.commit()
예제 #6
0
class Noise(Database.instance().Base, CRUDMixin):
    """Model for measures table
    """
    __tablename__ = 'noises'

    registered_at = Column(
        DateTime,
        primary_key=True)  # este id es del smartcitizen no del sensor
    peak = Column(Float)
    var1 = Column(Float)
    var5 = Column(Float)
    var10 = Column(Float)
    avg = Column(Float)
    synchronized_at = Column(DateTime)

    @classmethod
    def find_unsynchronized(cls):
        """Search setting by name"""
        session = Database.instance().session()
        return session.query(Noise).filter(Noise.synchronized_at == None)

    @classmethod
    def find_synchronized(cls):
        """Search setting by name"""
        session = Database.instance().session()
        return session.query(Noise).filter(Noise.synchronized_at != None)

    @classmethod
    def destroy_synchronized(cls):
        """Search setting by name"""
        session = Database.instance().session()
        session.query(Noise).filter(Noise.synchronized_at != None).delete()
        session.commit()
예제 #7
0
    def get_data(self, ips, proc_num, return_dict):
        result = []

        for ip in ips:
            location = self._database.get_location(Database.int2ip(ip))
            result.append(self._get_main_information(location))

        return_dict[proc_num] = result
예제 #8
0
    def show_list(self, message: Message):
        """
        Show a list of subscriptions from the database, attaching a delete button.

        If the user does not exist or the list is empty,
         then the message that the list is empty is displayed.
        If the image does not exist, only text is sent.
        """

        logger.show_msg(message)
        database = Database()
        parser = ParserManager()
        markup = InlineKeyboardMarkup()
        markup.add(
            InlineKeyboardButton(text="Удалить", callback_data="delete_book"))

        subscriptions = database.get_subscriptions(message.chat.id)

        if subscriptions == [None] or not subscriptions:
            self.typing(0.3, message)
            self.bot.send_message(message.chat.id, "Кажется, ничего нет 🤕")

        else:
            for subscription in database.get_subscriptions(message.chat.id):
                detail_book = parser.parsing_book(subscription)
                image_path = f"images/{detail_book['image_name']}"
                self.uploading_photo(0.2, message)

                if os.path.exists(image_path):
                    reply_msg = self.bot.send_photo(
                        chat_id=message.chat.id,
                        photo=open(f"images/{detail_book['image_name']}",
                                   'rb'),
                        caption=
                        f"{detail_book['title']} ({detail_book['price']}р.)",
                        reply_markup=markup)
                else:
                    reply_msg = self.bot.send_message(
                        chat_id=message.chat.id,
                        text=
                        f"{detail_book['title']} ({detail_book['price']}р.)",
                        reply_markup=markup)

                self.book_to_delete[reply_msg.message_id] = detail_book
예제 #9
0
    def get_from_db(cls, id):
        """get_from_db(str) -> return(obj)

        id      : blog id
        Returns : object

        Takes a given blog id and returns the data of a single blog.
        The return data is in the form of an object.
        """
        blog_data = db.find_one('blogs', id) # search the blog db and return one blog object based
        return cls(**blog_data)
예제 #10
0
    def __delete_book(self, call):
        """
        Remove a book from subscriptions.

        If the book does not exist in the book queue for deletion,
         a message is displayed asking you to repeat.
        """

        database = Database()
        try:
            link = self.book_to_delete[call.message.message_id]['link']
            database.delete_subscription(call.message.chat.id, link)
            self.book_to_delete.pop(call.message.message_id)
        except KeyError:
            self.bot.answer_callback_query(callback_query_id=call.id,
                                           text='Попробуйте ещё раз 🐙')

        else:
            self.bot.answer_callback_query(callback_query_id=call.id,
                                           text='Книга удалена 🦄')
예제 #11
0
    def get_data(self, ips, proc_num, return_dict):
        result = []

        for ip in ips:
            try:
                location = self._database.city(Database.int2ip(ip))
            except AddressNotFoundError:
                location = None

            result.append(self._get_main_information(location))

        return_dict[proc_num] = result
예제 #12
0
    def _get_info(cls, key, query):
        """_get_info(str, str) -> return(object)

        key   : The key used to searched the database's index
        query : The query requested
        return: Returns an object

        A helper method that searches the database using a key in order
        to find infomation. If the information is found within the database's
        index it returns an object.        i
        """
        data = db.find_one("users", {key: query}) # returns a dictionary if found
        return cls(**data) if data else None # passes the dictionary in a class object
예제 #13
0
    def load_state(self, sqlite_db):
        """
        Loads data from a database into the application
        :param sqlite_db:
        :return:
        """

        # first clear the lists in the application to avoid duplication
        self.all_rooms.clear()
        self.all_people.clear()
        if len(sqlite_db) < 7:
            return "short"
        elif sqlite_db.split(".")[-1] != "sqlite":
            return "not sqlite file"
        else:
            db = Database(sqlite_db)
            self.all_people = db.get_people_list()
            self.all_rooms = db.get_rooms_list()

        print('Database information loaded into the application successfully')
        print("\n\n\t\t\t---------------------------\n\n")

        return sqlite_db
예제 #14
0
    def ___add_book(self, call):
        """
        Add a book from subscriptions.

        If the book does not exist in the queue of books to be added,
         then a message is displayed asking you to repeat.
        """

        database = Database()
        try:
            book_ = self.book_to_add[call.message.message_id]
            database.insert_book(book_, [call.message.chat.id])
            database.insert_follower([book_['link']], call)
            database.start_following(call.message.chat.id)
            self.book_to_add.pop(call.message.message_id)
        except KeyError:
            self.bot.answer_callback_query(
                callback_query_id=call.id,
                text='Попробуйте отправить ссылку ещё раз ❌')
        else:
            self.bot.answer_callback_query(callback_query_id=call.id,
                                           text='Книга добавлена в список ✅')
예제 #15
0
 def get_by_author_id(cls, author_id):
     """
     Return a lists of blogs belong to a specific author with the id
     """
     blogs = db.find(collections='blogs', query={'author_id': author_id})
     return [cls(**blog) for blog in blogs ]
예제 #16
0
 def save(self):
     """
     Saves the user details
     """
     db.insert('users', self.get_json())
예제 #17
0
 def save(self):
     """Save whatever post created by the user to the blog database.
     The post is saved in json format and it includes the author,
     the author id, the title, the description and the post id.
     """
     return db.insert('blogs', self.json())
예제 #18
0
 def destroy_processed(cls, time):
     """Search setting by name"""
     session = Database.instance().session()
     session.query(Peak).filter(
         Peak.registered_at <= time + timedelta(minutes=-1)).delete()
     session.commit()
예제 #19
0
 def find_last_min(cls, time):
     """Search setting by name"""
     session = Database.instance().session()
     return session.query(Peak).filter(
         and_(Peak.registered_at > time + timedelta(minutes=-1),
              Peak.registered_at <= time)).all()
예제 #20
0
def main():
    while True:
        led.default(door)
        rawCard = input("SwipeCard: ")
        formCard = rawCard[1:8]; print(door.is_blocked())

        if door.is_blocked():
            continue

        if checkCard(formCard):
            if door.unlock():
                print("Door open")
                Thread(target=beeper.beep, args=(5,.05)).start()
                time.sleep(3)
            else:
                print("Door is locked: ")

            door.lock()
        else:
            #Flash LEDs
            Thread(target=beeper.beep, args=(1,1)).start()
            led.flashColor(Led.RED)


if __name__ == "__main__":
        userDB = Database()
        door = Door()
        led = Led()
        beeper = Beeper()
        main()
예제 #21
0
 def save(self):
     """save(void) -> return(None)
     Returns :None
     Store the json representive of the data to mongo
     """
     db.insert('posts', self.json()) # insert json in the post table
예제 #22
0
    def get_posts_by_blog_id(cls, blog_id):
        """get_posts_by_id(str) -> return(obj)

        Returns all posts that belong to a specific blog.
        """
        return [cls(**post) for post in db.find('posts', {'blog_id':blog_id})]
예제 #23
0
 def find_synchronized(cls):
     """Search setting by name"""
     session = Database.instance().session()
     return session.query(Noise).filter(Noise.synchronized_at != None)
예제 #24
0
from api.handlers.ApiAddCourse import ApiAddCourse


from databases.database import Database


global_settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "autoreload": True,
    "template_path": os.path.join(os.path.dirname(__file__), "templates"),
    "login_url": "/login",
    "cookie_secret": "Hello world!"
    }

# the gloabl database
db = Database()

# a list of web routes and the objects to which they connect
class_rank = Application([
    # things relating to the homepage
    (r'/', IndexHandler, dict(db=db)),
    (r'/index/?', IndexHandler, dict(db=db)),

    # authentication/signin
    (r'/register/?', RegisterHandler, dict(db=db)),
    (r'/login/?', LoginHandler, dict(db=db)),
    (r'/logout/?', LogoutHandler, dict(db=db)),

    #require authentication for normal users
    (r'/welcome/?', WelcomeHandler, dict(db=db)),
    (r'/dash/?', DashHandler, dict(db=db)),  # partial
예제 #25
0
from api.handlers.ApiUser import ApiUser
from api.handlers.ApiToggleSocket import ApiToggleSocket
from api.handlers.ApiAddCourse import ApiAddCourse

from databases.database import Database

global_settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "autoreload": True,
    "template_path": os.path.join(os.path.dirname(__file__), "templates"),
    "login_url": "/login",
    "cookie_secret": "Hello world!"
}

# the gloabl database
db = Database()

# a list of web routes and the objects to which they connect
class_rank = Application(
    [
        # things relating to the homepage
        (r'/', IndexHandler, dict(db=db)),
        (r'/index/?', IndexHandler, dict(db=db)),

        # authentication/signin
        (r'/register/?', RegisterHandler, dict(db=db)),
        (r'/login/?', LoginHandler, dict(db=db)),
        (r'/logout/?', LogoutHandler, dict(db=db)),

        #require authentication for normal users
        (r'/welcome/?', WelcomeHandler, dict(db=db)),
예제 #26
0
def initialize():
    db.initialize()
예제 #27
0
 def create_database(self):
     """Creates the database if it doesn't exist"""
     db = Database.instance()
     db.Base.metadata.create_all(bind=db.engine)
     db.set_session()
예제 #28
0
 def destroy_synchronized(cls):
     """Search setting by name"""
     session = Database.instance().session()
     session.query(Noise).filter(Noise.synchronized_at != None).delete()
     session.commit()