예제 #1
0
def data_init():
    """Function that creates the different tables
    """
    # Create Category table (SQL REQUEST)
    categorie = Category()
    product = Product()
    favorite = Favorite()
    tables = {
        'Category': categorie.create(),
        'Product': product.create(),
        'Favorite': favorite.create()
    }
    # Create all tables of database
    for table_name in tables:
        table_description = tables[table_name]
        try:
            print(f"Création de la table {table_name} : ", end='')
            my_cursor.execute(table_description)
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
                print("existe déjà.")
            else:
                print(err.msg)
        else:

            print("OK")

    # Insert 7 categories in my category table(manually)
    categorie.insert_data()
    # The categories of my table
    category_index = list()
    for item in data_categories:
        category_index.append(item[1])

        # browse categories and insert data
    for index in enumerate(category_index):
        # Upload json file from api
        data_for_insert = upload_data(index[1], 1)
        # Insert data in Product table
        size = len(data_for_insert['products'])
        print(f'{index[1]} - produits: {size}')

        # The loop that inserts the data into my tables
        for i in range(size):
            try:
                store = data_for_insert['products'][i]['stores']
                name = data_for_insert['products'][i]['product_name']
                grade = data_for_insert['products'][i][
                    'nutrition_grades_tags'][0]
                url = data_for_insert['products'][i]['url']
                id_category = index[0] + 1
            except (KeyError, TypeError):
                continue
            finally:
                product.insert_data(name, url, grade, id_category, store)
예제 #2
0
 def make_search(self):
     """This method will take all needed actions to make a substitute
     search"""
     substitutor = Susbtitutor()
     favorite_repository = Favorite()
     # offering choice between categories
     substitutor.pick_category(connector)
     # offering choice between five random ingredients in a given category
     substitutor.pick_products(connector)
     substitutor.pick_substitute(connector)
     favorite_repository.save_fav(connector, substitutor)
     self.welcome()
예제 #3
0
 def save_product_substitute(self, product_choice, product_substitute,
                             id_product_substitute, id_product):
     """
     Method saves selected product in favorite table in database
     """
     menu_save()
     self.response = yes_no()
     favorite = Favorite()
     if self.response == 'Oui':
         favorite.insert_data(product_choice, product_substitute,
                              id_product_substitute, id_product)
         print("Produit enregistré aux Favoris")
     else:
         print("Ce produit n'est pas sauvegardé")
예제 #4
0
 def display_favorite(self):
     """
     Function that displays favorites in the database
     """
     menu_favorite()
     self.user_choice = validate_entering(1, 2)
     favorite1 = Favorite()
     list_favorite = favorite1.get_all()
     if self.user_choice == 1:
         browse_favorite(NUMBER_FAVORITE, list_favorite)
     else:
         favorite1.empty_favorite()
         print('Tous les favoris ont été supprimés')
         os.system('pause')
예제 #5
0
 def favorite_add(self, name, channels, priority, days, times, once, substring):
     """
     add a favorite
     """
     log.info('favorite.add: %s', name)
     f = Favorite(name, channels, priority, days, times, once, substring)
     if f in self.favorites:
         return NameError('Already scheduled')
     self.favorites.append(f)
     # Align favorites id(s)
     next = 0
     for r in self.favorites:
         r.id = next
         next += 1
     # update schedule
     self.check_favorites_and_reschedule()
예제 #6
0
class Controller(object):
    """
    Class for the tvserver.
    """
    def __init__(self, datafile):
        epg.init()
        self.locked = False
        self.datafile = datafile
        # load the recordings file
        self.load_schedule()
        # connect to recorder signals
        device.signals['start-recording'].connect(self._recorder_start)
        device.signals['stop-recording'].connect(self._recorder_stop)
        device.signals['changed'].connect(self.reschedule)
        # start by checking the recordings/favorites
        self.check_favorites_and_reschedule()
        # add schedule timer for SCHEDULE_TIMER / 3 seconds
        kaa.Timer(self.check_favorites_and_reschedule).start(SCHEDULE_TIMER / 3)

    @kaa.timed(0.1, kaa.OneShotTimer, policy=kaa.POLICY_ONCE)
    def print_schedule(self):
        """
        Print current schedule (for debug only)
        """
        if self.locked:
            # system busy, call again later
            self.print_schedule()
            return False
        if hasattr(self, 'only_print_current'):
            # print only latest recordings
            all = False
        else:
            # print all recordings in the list
            all = True
            # mark that all are printed once
            self.only_print_current = True
        # print only from the last 24 hours
        maxtime = int(time.time()) - 60 * 60 * 24
        info = 'recordings:\n'
        for r in self.recordings:
            if all or r.stop > maxtime:
                info += '%s\n' % r
        log.info(info)
        info = 'favorites:\n'
        for f in self.favorites:
            info += '%s\n' % f
        log.info(info)
        return True

    @kaa.coroutine()
    def reschedule(self):
        """
        Reschedule all recordings.
        """
        if self.locked:
            # system busy, call again later
            kaa.OneShotTimer(self.reschedule).start(0.1)
            yield False
        self.locked = True
        # get current time (UTC)
        ctime = int(time.time())
        # remove old recorderings
        self.recordings = filter(lambda r: r.start > ctime - 60*60*24*7, self.recordings)
        # run the scheduler to attach devices to recordings
        yield scheduler.schedule(self.recordings)
        # sort by start time
        self.recordings.sort(lambda l, o: cmp(l.start,o.start))
        # save schedule
        self.save_schedule()
        self.print_schedule()
        # Schedule recordings on recorder for the next SCHEDULE_TIMER seconds.
        log.info('schedule recordings')
        for r in self.recordings:
            if r.start < ctime + SCHEDULE_TIMER and r.status == SCHEDULED:
                r.schedule()
        self.locked = False
        yield True

    @kaa.coroutine()
    def check_favorites_and_reschedule(self):
        """
        Update recordings based on favorites and epg.
        """
        if self.locked:
            # system busy, call again later
            kaa.OneShotTimer(self.check_favorites_and_reschedule).start(0.1)
            yield False
        self.locked = True
        yield epg.check(self.recordings, self.favorites)
        self.locked = False
        self.reschedule()
        yield True

    #
    # load / save schedule file with recordings and favorites
    #

    def load_schedule(self):
        """
        load the schedule file
        """
        self.recordings = []
        self.favorites = []
        if not os.path.isfile(self.datafile):
            return
        try:
            xml = kaa.xmlutils.create(self.datafile, root='schedule')
        except Exception, e:
            log.exception('tvserver.load: %s corrupt:' % self.datafile)
            sys.exit(1)
        for child in xml:
            if child.nodename == 'recording':
                try:
                    r = Recording(node=child)
                except Exception, e:
                    log.exception('tvserver.load_recording')
                    continue
                if r.status == RECORDING:
                    log.warning('recording in status \'recording\'')
                    # Oops, we are in 'recording' status and this was saved.
                    # That means we are stopped while recording, set status to
                    # missed
                    r.status = MISSED
                if r.status == SCHEDULED:
                    # everything is a conflict for now
                    r.status = CONFLICT
                self.recordings.append(r)
            if child.nodename == 'favorite':
                try:
                    f = Favorite(node=child)
                except Exception, e:
                    log.exception('tvserver.load_favorite:')
                    continue
                self.favorites.append(f)
예제 #7
0
 def find_search(self):
     """This method will take all needed actions to find all saved
     substitutes"""
     favorite_repository = Favorite()
     favorite_repository.find_old_fav(connector)
     self.welcome()
예제 #8
0
from picture import Picture
from rehype import Rehype
from role import Role
from trending import Trending
from user import User
from hypeblock import Hypeblock
from dislike import dislike
from hypes import Hype
from login import Login

app = Flask(__name__)
app.secret_key = 'A0Z//hdfg^+%j/3yX R~XHHsadfaf]LWX/,?RT'
app.attachment=Attachment(app)
app.block=block(app)
app.contacts=Contact(app)
app.favorite=Favorite(app)
app.followers=followers(app)
app.hypeline=Hypeline(app)
app.picture=Picture(app)
app.rehype=Rehype(app)
app.role=Role(app)
app.trending=Trending(app)
app.user=User(app)
app.hypeblock=Hypeblock(app)
app.dislike=dislike(app)
app.hype=Hype(app)
app.login=Login(app)


def get_elephantsql_dsn(vcap_services):
    """Returns the data source name for ElephantSQL."""
예제 #9
0
"""
    AN NGUYEN
    A simple Python Flask MVC webapp for DOGGO
    A user can be able to search, add to favorite list and delete a doggo from favorite list
"""
import flask
from flask.views import MethodView
from index import Index
from favorite import Favorite
from search import Search
from search import Result

application = flask.Flask(__name__)  # our Flask app

application.add_url_rule('/favorite/',
                         view_func=Favorite.as_view('favorite'),
                         methods=['GET'])

application.add_url_rule('/search/',
                         view_func=Search.as_view('search'),
                         methods=['GET', 'POST'])

application.add_url_rule('/result/',
                         view_func=Result.as_view('result'),
                         methods=['GET', 'POST'])

application.add_url_rule('/',
                         view_func=Index.as_view('index'),
                         methods=["GET"])

if __name__ == '__main__':