Example #1
0
    def __init__(self):

        #Удаляем queue
        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql = 'DROP TABLE queue;'
        crud.deleteAct()
        print('Drop\'нули таблицу queue')
        crud.closeConnection()
Example #2
0
    def getWholeVerseData(self, verse_id):
        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql = 'SELECT * FROM verses_list WHERE id=\'{0}\''.format(
            verse_id)
        verse_data = crud.readAct()
        crud.closeConnection()

        return verse_data
Example #3
0
    def queueBlocker(self):

        exec_time = self.curTime + 72000
        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql="INSERT INTO queue (name, email, exec_time, verse_id)" \
                 "VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\')".format(
                'blocker_queue','none',exec_time,1234567)
        crud.createAct()
        crud.closeConnection()
Example #4
0
    def addRowIntoQueue(self, name, email, exec_time, verse_id):

        # print(' Имя - {0},\n Email - {1},\n exec_time - {2},\n '
        #       'verse_id - {3}\n'.format(name,email,exec_time,verse_id))
        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql="INSERT INTO queue (name, email, exec_time, verse_id) " \
                 "VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\')".format(name,
                 email,exec_time,verse_id)
        crud.createAct()
        crud.closeConnection()
Example #5
0
    def canSend(self, id):

        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql = 'SELECT exec_time FROM queue WHERE id=\'{0}\''.format(id)
        exec_time = (crud.readAct())[0][0]
        curTime = round(time.time())
        crud.closeConnection()

        if curTime >= exec_time:
            print(curTime - exec_time)
            return True
        else:
            print(curTime - exec_time)
            return False
Example #6
0
    def getRandVerseID(self, authors):

        # получить случайного автора
        authors = authors.split(',')
        rand_author = (random.choice(authors)).strip()
        print('random author ------ > {0}'.format(rand_author))
        #получить случайный verse_id
        crud = Crud('localhost', 'andrew', 'andrew', 'verses')

        crud.sql = '''SELECT * FROM verses_list WHERE author_id={0}
                    ORDER BY RAND() LIMIT 1'''.format(rand_author)
        #Возвращает кортеж, поэтому прийдеться извлечь ключ
        verse_id = (crud.readAct())[0][0]
        crud.closeConnection()

        return verse_id
Example #7
0
    def __init__(self):

        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        #получить количество элементов queue
        crud.sql = 'SELECT * FROM queue'
        queue = crud.readAct()
        if (len(queue)) >= 1:

            # По-тихоньку отправляем письма из очереди
            for x in queue:

                if self.canSend(x[0]) == True:
                    self.sender(x)
                    # Если не одного элемента не осталось - завершаем цикл
                else:
                    'Прийдеться подождать с отправкой сообщений...'
        else:
            print('Очередь на данный момент пустая!')

        crud.closeConnection()
#!/usr/bin/python3

#        отступы пробелами
#        by Andrew Sotnikov aka Luca Brasi,
#        e-mail: [email protected]
#        --------------

#        clearing cash in DB and removing log file_as_well

from saumysql import Crud
from subprocess import call

passwd = "fearofthedark"
logfile = "/var/log/andrew/good_verse_mailer.log"

#removing temporary tables from DataBase
crud = Crud('localhost', 'andrew', 'andrew', 'verses')
crud.sql = ("DROP TABLE queue, time_marks")
crud.deleteAct()

#clearing logs
call("echo \"{0}\" | sudo -S rm {1}".format(passwd, logfile),
     shell=True,
     universal_newlines=True)
Example #9
0
    def __init__(self):

        # Время для начала отсчета
        st_time = self.curTime
        #задержка межу отправками сообщения получателям
        delay = -10

        #Проверить существует ли таблица queue
        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql = 'SHOW TABLE STATUS LIKE \'queue\''
        result = crud.readAct()
        # Таблицы нету, его прийдеться создать
        if len(result) == 0:
            print('Нету таблицы queue!')
            #Cоздадим таблицу queue
            crud.sql = '''CREATE TABLE queue(
                            id INT NOT NULL AUTO_INCREMENT,
                            name VARCHAR(40) NOT NULL,
                            email VARCHAR(40) NOT NULL,
                            exec_time INT NOT NULL,
                            verse_id INT NOT NULL,
                            PRIMARY KEY (id)
                            );'''
            result = crud.createAct()

        #В противном случае можно завязывать с этапом создания queue
        else:
            print('queue?! Походу есть такая таблица!')

        # Сделать выборку из таблицы с контактами
        crud.sql = 'SELECT * FROM contacts'
        list = crud.readAct()
        #print(list)

        for row in list:
            exec_time = self.curTime
            name = str(row[1])
            email = str(row[2])
            interval = 2
            # author_id. Атовра представлены в виде id
            authors = str(row[5])
            # quantity_per_day - желаемое количество стишков в день
            qpd = int(row[3])

            if qpd == 0:
                print('Этот человек уже отписался от рассылки!')
                continue

            elif qpd == 1:
                # каждый раз генериуем новый verse_id для следущего абонента
                # в таблице queue
                verse_id = self.getRandVerseID(authors)
                exec_time = exec_time + delay
                self.addRowIntoQueue(name, email, exec_time, verse_id)

            # Для тех кто отписался от рассылки стишки не рассылаем!

            else:
                #то же что и в ветке if, только для больего количества qpd
                #print('qpd is {0}'.format(qpd))
                interval_list = self.calculateDayInterval(qpd)

                for once, interval in zip((range(0, qpd)), interval_list):

                    exec_time = self.curTime
                    verse_id = self.getRandVerseID(authors)
                    exec_time = exec_time + delay + interval
                    self.addRowIntoQueue(name, email, exec_time, verse_id)

        crud.closeConnection()
        self.queueBlocker()
Example #10
0
    def deleteFromQueue(self, id):

        crud = Crud('localhost', 'andrew', 'andrew', 'verses')
        crud.sql = 'DELETE FROM queue WHERE id=\'{0}\''.format(id)
        verse_data = crud.deleteAct()
        crud.closeConnection()