Пример #1
0
def get_category_chart(start_date, end_date):
    #get the data from the database
    #calculate how many of the articles have been described
    categories = db.get_categories()
    categories = db.get_categories()
    start_date_pretty = start_date.strftime("%m/%d/%Y")
    end_date_pretty = end_date.strftime("%m/%d/%Y")
    #total_articles = len(db.get_articles_by_date_range(start_date,
    #                                                   end_date))
    category_info = [[
        category.category_name,
        db.get_article_count(category_id=category.CategoryID,
                             start_date=start_date,
                             end_date=end_date)
    ] for category in categories]
    category_names = [i[0] for i in category_info]
    article_numbers = [i[1] for i in category_info]
    #create bar chart
    plt.bar(range(len(category_names)), article_numbers)
    plt.title('Articles per category from {0} to {1}'.format(
        start_date_pretty, end_date_pretty))
    plt.ylabel('# of articles')  #label the y-axis

    #label x-axis with movies at bar centers
    plt.xticks(range(len(category_names)), category_names)
    plt.show()
Пример #2
0
def list_categories():
    print("CATEGORIES")
    categories = db.get_categories()    
    #for category in categories:
    #    print(str(category.id) + ". " + category.name)
    print(categories)
    return categories
Пример #3
0
def export_roundup_by_category():
    display_categories()
    roundup_categories = db.get_categories()
    categories_remaining = len(roundup_categories)
    categories_for_roundup = []
    for category in roundup_categories:
        print('Categories remaining: {0}'.format(categories_remaining))
        print('Include {0}'.format(category.category_name))
        category_choice = btc.read_int_ranged('1 to include, 2 to exclude: ',
                                              1, 2)
        if category_choice != 1:
            categories_for_roundup.append(category)
    roundup_title = btc.read_text('Enter the roundup title: ')
    roundup_month = btc.read_int_ranged('Enter roundup month: ', 1, 12)
    roundup_year = btc.read_int_ranged('Enter roundup year: ', 1, 2100)
    filename = btc.read_text('Enter roundup filename: ')
    roundup_choice = btc.read_int_ranged(
        'Enter 1 to export roundup, 2 to cancel: ', 1, 2)
    if roundup_choice == 1:
        for category in categories_for_roundup:
            #        for category in roundup_categories:
            category.articles = db.get_articles_for_roundup(
                roundup_month, roundup_year, category.id)
        roundup_docx.create_complete_roundup(filename=filename,
                                             roundup_title=roundup_title,
                                             categories=categories_for_roundup)
        #display_title()
    elif roundup_choice == 2:
        print('Roundup export cancelled. Return to main menu.\n')
Пример #4
0
 def draw_gui(self):
     lab = ttk.Label(self, text="Add item with ID:")
     lab.grid(column=0, row=6)
     ent = ttk.Entry(self, textvariable=self.addid)
     ent.grid(column=1, row=6)
     lab = ttk.Label(self, text="Add item from Category:")
     lab.grid(column=2, row=6)
     lis = list(set(db.get_categories()))
     lis.sort()
     cb = ttk.Combobox(self, textvariable=self.cat, values=[x[0] for x in lis],
                       state='readonly', width=40)
     cb.grid(column=3, row=6, sticky='W')
     cb.bind("<<ComboboxSelected>>", self.update_item_options)
     lab = ttk.Label(self, text="Number of Affixes:")
     lab.grid(column=0, row=7)
     ent2 = ttk.Entry(self, textvariable=self.affixnum)
     ent2.grid(column=1, row=7)
     lab = ttk.Label(self, text="Specific Item:")
     lab.grid(column=2, row=7)
     self.itemcb = ttk.Combobox(self, textvariable=self.chosenitem, values=[], state='readonly', width=40)
     self.itemcb.grid(column=3, row=7)
     self.itemcb.bind("<<ComboboxSelected>>", self.update_item_id)
     lab = ttk.Label(self, text="Quality:")
     lab.grid(column=0, row=8)
     lis2 = list(set(db.get_quality_levels()))
     lis2.sort()
     cb = ttk.Combobox(self, textvariable=self.qual, values=[x[1] for x in lis2],
                       state='readonly', width=40)
     cb.grid(column=1, row=8, sticky='W')
     self.qual.set("Legendary/Set")
     ttk.Label(self, text="Note: If there's no space in the inventory no item will be added") \
         .grid(column=0, row=20, columnspan=2)
     sb = ttk.Button(self, text="Add Item", command=lambda: self.additem())
     sb.grid(column=0, row=21)
Пример #5
0
def show_categories(show_type):
    cate_ordered = [{'CATEGORY': 'View All', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'New Arrivals', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Baby Bags', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Backpacks', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Clutches & Evening Bags', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Cross-Body Bags', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Hobos', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Mini Bags', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Satchels & Shoulder Bags', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Totes', 'COUNT': 0, 'CATEGORY_URL': ''},
        {'CATEGORY': 'Sale', 'COUNT': 0, 'CATEGORY_URL': ''}]
    cate = get_categories(show_type)
    if len(cate) == 1:
        cate_ordered = cate
    else:
        for co in cate_ordered:
            for c in cate:
                if c.get("CATEGORY") == co.get("CATEGORY"):
                    if c.get("COUNT") == "":
                        co["COUNT"] = "0"
                    else:
                        co["COUNT"] = str(c["COUNT"])
                    co["CATEGORY_URL"] = c.get("CATEGORY_URL")
    return cate_ordered
Пример #6
0
def category(category_name):
    '''Shows categories and all items in a selected category'''

    category_id = db.get_category_id_by_name(category_name)
    items = db.get_items_by_category_id(category_id)
    categories = db.get_categories()

    num_items = len(items)
    items_string = 'items'
    if (num_items == 1):
        items_string = 'item'

    (state, logged_in, username) = gplus.get_login_state()

    data = {
        'category_name':
        category_name,
        'categories': [category.name for category in categories],
        'items': [[db.get_category_name_by_id(item.category_id), item.name]
                  for item in items],  #NOQA
        'num_items':
        num_items,
        'items_string':
        items_string,
        'state':
        state,
        'logged_in':
        logged_in,
        'username':
        username
    }
    return render_template('category.html', data=data)
Пример #7
0
def category(category_name):
    '''Shows categories and all items in a selected category'''

    category_id = db.get_category_id_by_name(category_name)
    items = db.get_items_by_category_id(category_id)
    categories = db.get_categories()

    num_items = len(items)
    items_string = 'items'
    if (num_items == 1):
        items_string = 'item'

    (state, logged_in, username) = gplus.get_login_state()

    data = {
        'category_name': category_name,
        'categories': [category.name for category in categories],
        'items': [[db.get_category_name_by_id(item.category_id), item.name] for item in items], #NOQA
        'num_items': num_items,
        'items_string': items_string,
        'state': state,
        'logged_in': logged_in,
        'username': username
    }
    return render_template('category.html', data = data)
Пример #8
0
def show_categories(show_type):
    cate_ordered = [{
        'CATEGORY': 'View All',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'New Arrivals',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Baby Bags',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Backpacks',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Clutches & Evening Bags',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Cross-Body Bags',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Hobos',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Mini Bags',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Satchels & Shoulder Bags',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Totes',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }, {
        'CATEGORY': 'Sale',
        'COUNT': 0,
        'CATEGORY_URL': ''
    }]
    cate = get_categories(show_type)
    if len(cate) == 1:
        cate_ordered = cate
    else:
        for co in cate_ordered:
            for c in cate:
                if c.get("CATEGORY") == co.get("CATEGORY"):
                    if c.get("COUNT") == "":
                        co["COUNT"] = "0"
                    else:
                        co["COUNT"] = str(c["COUNT"])
                    co["CATEGORY_URL"] = c.get("CATEGORY_URL")
    return cate_ordered
Пример #9
0
def display_categories(command=''):
    del command
    print("CATEGORIES")
    categories = db.get_categories()
    for category in categories:
        print(str(category.CategoryID) + ". " + category.category_name.strip(),
              end='   ')
    print()
Пример #10
0
def edit_item(item_name):
    '''Allows a logged-in user to edit an item they created'''

    # Ensure there is a user logged in:
    if not gplus.is_logged_in():
        return redirect('/')

    # Ensure the item being edited exists:
    query = db.session.query(Item).filter_by(name=item_name)
    if not db.session.query(query.exists()):
        return redirect('/')

    # Ensure the logged-in user owns this item:
    item = query.one()
    if item.user_id != login_session['user_id']:
        return redirect('/')

    if request.method == 'POST':
        new_item_name = request.form['item_name']
        new_item_description = request.form['item_description']
        new_category_name = request.form['category_name']

        # Ensure the new category exists:
        query = db.session.query(Category).filter_by(name=new_category_name)
        if not db.session.query(query.exists()):
            return redirect('/')

        new_category = query.one()

        # Validate the new item name and description
        if not db.is_valid_item(new_item_name, new_item_description):
            return redirect('/catalog/%s/%s' % (new_category.name, item_name))

        item.name = new_item_name
        item.description = new_item_description
        item.category_id = new_category.id
        db.session.commit()
        return redirect('/catalog/%s/%s' % (new_category.name, new_item_name))
    elif request.method == 'GET':
        item_description = db.session.query(Item).filter_by(
            name=item_name).one().description  #NOQA

        categories = db.get_categories()
        categories = [category.name for category in categories]

        (state, logged_in, username) = gplus.get_login_state()

        data = {
            'item_name': item_name,
            'item_description': item_description,
            'categories': categories,
            'state': state,
            'logged_in': logged_in,
            'username': username
        }
        return render_template('edit.html', data=data)
Пример #11
0
def edit_item(item_name):
    '''Allows a logged-in user to edit an item they created'''

    # Ensure there is a user logged in:
    if not gplus.is_logged_in():
        return redirect('/')

    # Ensure the item being edited exists:
    query = db.session.query(Item).filter_by(name = item_name)
    if not db.session.query(query.exists()):
        return redirect('/')

    # Ensure the logged-in user owns this item:
    item = query.one()
    if item.user_id != login_session['user_id']:
        return redirect('/')

    if request.method == 'POST':
        new_item_name = request.form['item_name']
        new_item_description = request.form['item_description']
        new_category_name = request.form['category_name']

        # Ensure the new category exists:
        query = db.session.query(Category).filter_by(name = new_category_name)
        if not db.session.query(query.exists()):
            return redirect('/')

        new_category = query.one()

        # Validate the new item name and description
        if not db.is_valid_item(new_item_name, new_item_description):
            return redirect('/catalog/%s/%s' % (new_category.name, item_name))

        item.name = new_item_name
        item.description = new_item_description
        item.category_id = new_category.id
        db.session.commit()
        return redirect('/catalog/%s/%s' % (new_category.name, new_item_name))
    elif request.method == 'GET':
        item_description = db.session.query(Item).filter_by(name = item_name).one().description #NOQA

        categories = db.get_categories()
        categories = [category.name for category in categories]

        (state, logged_in, username) = gplus.get_login_state()

        data = {
            'item_name': item_name,
            'item_description': item_description,
            'categories': categories,
            'state': state,
            'logged_in': logged_in,
            'username': username
        }
        return render_template('edit.html', data = data)
Пример #12
0
async def process_callback(callback_query: types.CallbackQuery):
    if callback_query.id:
        for id, name in db.get_categories():
            if callback_query.data == str(id):
                await bot.send_message(
                    callback_query.message.chat.id,
                    f"`Категорія:` *{callback_query.message.text}*\n`Товари:`",
                    parse_mode="Markdown")
                for t in db.get_tovar(id):
                    await bot.send_message(callback_query.message.chat.id,
                                           db.output(t),
                                           parse_mode="Markdown")
Пример #13
0
def classify_dataset():
    user_id = int(request.args['user_id']) 
    dataset_id = request.args["dataset_id"]
    dataset_ids = db.get_available_dataset_ids_for_user(user_id)

    name, description, keywords = db.get_dataset_details(dataset_id)

    categories = db.get_categories()

    return render_template('dataset_browser.html', dataset_ids = dataset_ids, 
        user_id = user_id, dataset_id = dataset_id, dataset_name = name,
        dataset_description = remove_html_tags(description), dataset_keywords = keywords,
        display_classifications = True, categories = categories)
Пример #14
0
async def mm(message: types.Message):
    if message.text == "Товари📦":
        for t in db.data:
            await bot.send_message(message.from_user.id,
                                   db.output(t),
                                   parse_mode="Markdown")
    elif message.text == "Категорії🔡":
        for c in db.get_categories():
            keyboard = types.InlineKeyboardMarkup()
            callback_button = types.InlineKeyboardButton(text="Вибрати👆",
                                                         callback_data=c[0])
            keyboard.add(callback_button)
            await bot.send_message(message.chat.id,
                                   "*{c}*".format(c=str(c[1])),
                                   reply_markup=keyboard,
                                   parse_mode="Markdown")
Пример #15
0
def index():
    '''Shows categories and latest items'''

    categories = db.get_categories()
    categories = [category.name for category in categories]

    items = db.get_items()
    latest_items = [[item.name, db.get_category_name_by_id(item.category_id)] for item in items] #NOQA

    (state, logged_in, username) = gplus.get_login_state()

    data = {
        'categories': categories,
        'latest_items': latest_items,
        'state': state,
        'logged_in': logged_in,
        'username': username
    }
    return render_template('index.html', data = data)
Пример #16
0
def get_date_range_category_stats(start_date, end_date):
    '''
    The roundups must have at least a few articles in each category. This
    function gets the stats for the categories between a start date and an
    end date input by the user.
    '''
    categories = db.get_categories()
    total_articles = db.get_article_count(start_date=start_date,
                                          end_date=end_date)
    category_ids = [[
        category.CategoryID, category.category_name,
        db.get_article_count(category_id=category.CategoryID,
                             start_date=start_date,
                             end_date=end_date)
    ] for category in categories]
    category_ids = sorted(category_ids,
                          key=operator.itemgetter(2),
                          reverse=True)
    undescribed_articles = db.get_undescribed_article_count(
        description_snippet='Not specified',
        start_date=start_date,
        end_date=end_date)
    print('{0} articles are undescribed'.format(undescribed_articles))
    try:
        percent_incomplete = (undescribed_articles / total_articles) * 100
        total_articles_completed = 100
        percent_incomplete = total_articles_completed - percent_incomplete
        print('CATEGORY STATS')
        print('-' * 64)
        line_format = '{0:<3} {1:11s} \t{2:10}'
        print('{0:<3} {1:11s} {2:10}'.format('ID', 'Name', '\tQty.'))
        print('-' * 64)
        for item in category_ids:
            print(line_format.format(item[0], item[1], str(item[2])))
        print('-' * 64)
        print('Undescribed Articles: {0} (Completed: {1:.2f} percent)'.format(
            undescribed_articles, percent_incomplete))
        print('Total Articles: {0}'.format(total_articles))
    except ZeroDivisionError as e:
        print(e)
        return
Пример #17
0
def index():
    '''Shows categories and latest items'''

    categories = db.get_categories()
    categories = [category.name for category in categories]

    items = db.get_items()
    latest_items = [[item.name,
                     db.get_category_name_by_id(item.category_id)]
                    for item in items]  #NOQA

    (state, logged_in, username) = gplus.get_login_state()

    data = {
        'categories': categories,
        'latest_items': latest_items,
        'state': state,
        'logged_in': logged_in,
        'username': username
    }
    return render_template('index.html', data=data)
Пример #18
0
def teas(page=1, category=None):
    query = request.args.get('search')
    print(query)
    if isinstance(category, str) and str.lower(category) == 'all':
        category = None
    if query:
        rows = search_teas(page - 1, query)
    elif category:
        rows = get_teas(page - 1, category)
    else:
        rows = get_all_teas(page - 1)
    pages = get_teas_pages(category)
    if not rows:
        abort(404)
    categories = get_categories()
    return render_template('teas.html',
                           user=session.get('user'),
                           rows=rows,
                           active_category=category,
                           categories=categories,
                           active_page=page,
                           pages=pages)
Пример #19
0
def add_item():
    '''Adds an item to the database'''

    # Ensure there is a user logged in:
    if not gplus.is_logged_in():
        return redirect('/')

    if request.method == 'POST':
        category_name = request.form['category_name']

        # Ensure the category exists:
        query = db.session.query(Category).filter_by(name = category_name) #NOQA
        if not db.session.query(query.exists()):
            return redirect('/')

        category = query.one()
        item_name = request.form['item_name']
        item_description = request.form['item_description']

        # Validate the item name and descriptions
        if not db.is_valid_item(item_name, item_description):
            return redirect('/')

        user_id = db.get_user_id_by_name(login_session['username'])
        db.create_item(item_name, item_description, category.id, user_id)

        return redirect("/catalog/%s/items" % category_name)
    elif request.method == 'GET':
        categories = db.get_categories()

        (state, logged_in, username) = gplus.get_login_state()
        data = {
            'categories': [category.name for category in categories],
            'state': state,
            'logged_in': logged_in,
            'username': username
        }
        return render_template('add.html', data = data)
Пример #20
0
def add_item():
    '''Adds an item to the database'''

    # Ensure there is a user logged in:
    if not gplus.is_logged_in():
        return redirect('/')

    if request.method == 'POST':
        category_name = request.form['category_name']

        # Ensure the category exists:
        query = db.session.query(Category).filter_by(name=category_name)  #NOQA
        if not db.session.query(query.exists()):
            return redirect('/')

        category = query.one()
        item_name = request.form['item_name']
        item_description = request.form['item_description']

        # Validate the item name and descriptions
        if not db.is_valid_item(item_name, item_description):
            return redirect('/')

        user_id = db.get_user_id_by_name(login_session['username'])
        db.create_item(item_name, item_description, category.id, user_id)

        return redirect("/catalog/%s/items" % category_name)
    elif request.method == 'GET':
        categories = db.get_categories()

        (state, logged_in, username) = gplus.get_login_state()
        data = {
            'categories': [category.name for category in categories],
            'state': state,
            'logged_in': logged_in,
            'username': username
        }
        return render_template('add.html', data=data)
Пример #21
0
def export_roundup_by_date():
    roundup_title = btc.read_text('Enter the roundup title: ')
    start_date = btc.read_date('Enter the starting date: ')
    end_date = btc.read_date('Enter the ending date: ')
    print('start date: ', start_date, 'end date: ', end_date)
    print('start date type:', type(start_date), 'end date type:',
          type(end_date))
    filename = btc.read_text('Enter roundup filename: ')
    roundup_choice = btc.read_int_ranged(
        'Enter 1 to export roundup, 2 to cancel: ', 1, 2)
    if roundup_choice == 1:
        roundup_categories = db.get_categories()  #We get the articles by
        #category to sort them by category
        for category in roundup_categories:
            #category.articles = db.get_articles_for_roundup(roundup_month, roundup_year, category.id)
            category.articles = db.get_articles_for_roundup(
                start_date, end_date, category.CategoryID)
            print(len(category.articles))
        roundup_docx.create_complete_roundup(filename=filename,
                                             roundup_title=roundup_title,
                                             categories=roundup_categories)
        #display_title()
    elif roundup_choice == 2:
        print('Roundup export cancelled. Return to main menu.\n')
Пример #22
0
def list_all_category():
    db.connect()
    movies = db.get_categories()
    return(movies)
Пример #23
0
 def populateCombo(self):
     cat_list = []
     categories = db.get_categories()
     for category in categories:
         cat_list.append(str(category.name))
     return cat_list
Пример #24
0
def list_categories():
    return jsonify(get_categories(get_db()))
Пример #25
0
def gconnect():
    if is_logged_in():
        categories = db.get_categories()
        categories = [category.name for category in categories]
        latest_items = db.get_items()
        latest_items = [[item.name, db.get_category_name_by_id(item.category_id)] for item in latest_items] #NOQA
        data = {
            'categories': categories,
            'latest_items': latest_items,
            'logged_in': True,
            'username': views.login_session['username']
        }
        return render_template('index.html', data = data)

    if request.args.get('state') != views.login_session['state']:
        response = make_response(views.json.dumps('Invalid state paremeter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = views.flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except views.FlowExchangeError:
        response = make_response(views.json.dumps('Failed to upgrade the authorization code.'), 401) #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid:
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) #NOQA
    http = httplib2.Http()
    result = views.json.loads(http.request(url, 'GET')[1])

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(views.json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user:
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response("Token's user ID doesn't match given user ID.", 401) #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app:
    if result['issued_to'] != views.CLIENT_ID:
        response = make_response(views.json.dumps("Token's client ID does not match app's."), 401) #NOQA
        print("Token's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check to see if user is already logged in
    stored_credentials = views.login_session.get('credentials')
    stored_gplus_id = views.login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id  == stored_gplus_id:
        response = make_response(views.json.dumps("Current user is already connected."), 200) #NOQA
        response.headers['Content-Type'] = 'application/json'

    # Get user info
    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params = params)
    data = views.json.loads(answer.text)

    # Store the access token in the session for later use.
    views.login_session['credentials'] = credentials.access_token
    views.login_session['gplus_id'] = gplus_id
    views.login_session['username'] = data['name']

    # Add a new user if this user doesn't already exist
    user_id = db.get_user_id_by_name(data['name'])
    if not user_id:
        user_id = db.create_user(views.login_session)

    views.login_session['user_id'] = user_id

    return redirect('/')
Пример #26
0
    open_url = openurl()

    if db.category_is_empty(sql_cursor) or defines.ALWAYS_REINIT_CATEGORY:
        print("open catalog..")
        db.clear_category(sql_cursor)
        #categories = parseCategories(open('test.html'))
        catalog = open_url.get(defines.CATALOG_HEAD_URL)

        with codecs.open("test.html", "w", encoding='utf8') as f:
            f.write(catalog)

        categories = parseCategories(open_url.get(defines.CATALOG_HEAD_URL))
        for category in categories:
            db.set_category(sql_cursor, category)
    else:
        categories = db.get_categories(sql_cursor)

    if (defines.UPDATE_DATABASE):
        if not db.category_is_empty(sql_cursor) and db.check_goods_time(
                sql_cursor):
            db.save_goods_table(sql_cursor)
        db.clear_goods(sql_cursor)

    #
    # use multithreading for the url open
    #

    ## Make the Pool of workers
    #threads_count = multiprocessing.cpu_count()
    #print("threads count = " + str(threads_count))
    #pool = ThreadPool( threads_count )
Пример #27
0
def display_categories():
    print("CATEGORIES")
    categories = db.get_categories()
    for category in categories:
        print(str(category.id) + ". " + category.name)
    print()
Пример #28
0
def gconnect():
    if is_logged_in():
        categories = db.get_categories()
        categories = [category.name for category in categories]
        latest_items = db.get_items()
        latest_items = [[
            item.name, db.get_category_name_by_id(item.category_id)
        ] for item in latest_items]  #NOQA
        data = {
            'categories': categories,
            'latest_items': latest_items,
            'logged_in': True,
            'username': views.login_session['username']
        }
        return render_template('index.html', data=data)

    if request.args.get('state') != views.login_session['state']:
        response = make_response(views.json.dumps('Invalid state paremeter'),
                                 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = views.flow_from_clientsecrets('client_secrets.json',
                                                   scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except views.FlowExchangeError:
        response = make_response(
            views.json.dumps('Failed to upgrade the authorization code.'),
            401)  #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid:
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)  #NOQA
    http = httplib2.Http()
    result = views.json.loads(http.request(url, 'GET')[1])

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(views.json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user:
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            "Token's user ID doesn't match given user ID.", 401)  #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app:
    if result['issued_to'] != views.CLIENT_ID:
        response = make_response(
            views.json.dumps("Token's client ID does not match app's."),
            401)  #NOQA
        print("Token's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check to see if user is already logged in
    stored_credentials = views.login_session.get('credentials')
    stored_gplus_id = views.login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(
            views.json.dumps("Current user is already connected."), 200)  #NOQA
        response.headers['Content-Type'] = 'application/json'

    # Get user info
    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = views.json.loads(answer.text)

    # Store the access token in the session for later use.
    views.login_session['credentials'] = credentials.access_token
    views.login_session['gplus_id'] = gplus_id
    views.login_session['username'] = data['name']

    # Add a new user if this user doesn't already exist
    user_id = db.get_user_id_by_name(data['name'])
    if not user_id:
        user_id = db.create_user(views.login_session)

    views.login_session['user_id'] = user_id

    return redirect('/')