def test_delete_user(): """create and then deletes a user """ user = {"name": "jean-louis"} inserted = db_access.create_user(user) assert inserted read = db_access.get_user(inserted) assert read db_access.delete_user(inserted) read = db_access.get_user(inserted) assert not read
def login(): success = False if session.get('user') is None: if request.method == 'GET': return render_template('login.html') else: try: user = db_access.get_user(request.form.get('username')) if user is None: flash('Wrong username!') else: if check_password_hash(user.get('password'), request.form.get('password')): session['user'] = request.form.get('username') success = True else: flash('Wrong password!') except (db_access.CredentialsMissingError, db_access.DatabaseError): abort(500, 'A database error occured!') else: flash('Already logged in!') success = True if success: return redirect(url_for('index')) else: return render_template('login.html')
def send_current_match_info(message): try: chat_id = message.chat.id user_profile = db_access.get_user(chat_id) current_matches = db_access.current_matches() if(len(current_matches) == 0): bot.send_message(chat_id, 'There are no matches now!') else: for match in current_matches: predictions_for_match = db_access.get_predictions_match(match, user_profile) string_to_send = match['team_1'] + ' vs. ' + match['team_2'] + ':\n' for prediction_for_match in predictions_for_match: if ('name' in prediction_for_match): string_to_send = string_to_send + prediction_for_match['name'] + ': ' if ('predictions' in prediction_for_match): prediction_l = prediction_for_match['predictions'] prediction = prediction_l[0] if (prediction['winner'] == 0): string_to_send = string_to_send + 'Draw ' + str(prediction['goals']) + ':' + str(prediction['goals']) + ', ' else: if (prediction['winner'] == 1): string_to_send = string_to_send + match['team_1'] elif (prediction['winner'] == 2): string_to_send = string_to_send + match['team_2'] string_to_send = string_to_send + ' by ' + str(prediction['goals']) + ' goal(s), ' if (prediction['total'] == 0): string_to_send = string_to_send + '<2.5\n' elif (prediction['total'] == 1): string_to_send = string_to_send + '>2.5\n' else: string_to_send = string_to_send + 'No prediction\n' bot.send_message(chat_id, string_to_send) except Exception as e: bot.reply_to(message, 'Something went wrong! Please, contact the provider of this bot!')
def register(): success = False if session.get('user') is None: if request.method == 'GET': return render_template('register.html') else: try: username = request.form.get('username') password = generate_password_hash(request.form.get('password')) user = db_access.get_user(username) if user is None: if not check_password_hash( password, request.form.get('password_verify')): flash('Passwords do not match!') else: db_access.add_user(username, password) session['user'] = username success = True else: flash('Username taken!') except (db_access.CredentialsMissingError, db_access.DatabaseError): abort(500, 'A database error occured!') else: flash('Already logged in!') success = True if success: return redirect(url_for('index')) else: return render_template('register.html')
def index(): try: owner_id = int(request.vars.get('id')) except ValueError as error: raise HTTP(404) except TypeError as error: if auth.is_logged_in() == False: redirect(URL('default', 'user/login',vars=dict(_next=URL('wishlist','index')))) else: redirect(URL('wishlist','index',vars=dict(id=auth.user_id))) wishlist = db_access.get_wishlist(db, owner_id) owner = db_access.get_user(db, owner_id) # Make sure the user actually exists first. if owner is None: redirect(URL('error', 'not_found', args='user')) response.title = owner.username + "'s Wishlist" page_actions = [ ('Collection', URL('collection', 'index', vars={'id': owner_id}), None), ('Wishlist', URL('wishlist', 'index', vars={'id': owner_id}), 'ok'), ('Trades', URL('trade', 'index', vars={'id': owner_id}), None) ] #if the user is looking at his own page, allow him to add new items own_page = (auth.user_id == owner_id) if own_page: page_actions.append(('Add New Item', URL('item', 'add'), None)) return dict(wishlist=wishlist, page_actions=page_actions, own_page=own_page)
def test_get_user(): """create and then get a user """ user = {"name": "jean-louis"} inserted = db_access.create_user(user) assert inserted read = db_access.get_user(inserted) assert read
def chirps_hn(handle): uid = db_access.get_id(handle) chirp_list = db_access.get_chirps(db_access.get_id(handle)) return render_template('chirp.html', chirps=chirp_list, chirp_from_page=False, markdown=markdown2.markdown, name=db_access.get_user(session['user']))
def follow_user(uid): if 'user' in session: user = db_access.get_user(uid) message = ('Sorry, you cannot follow %s.' % (user), 'danger_message') if db_access.follow(uid, session['user']) == True: message = ('You are now following %s' % (user), 'success_message') flash(*message) return redirect(url_for('user_page', handle=user)) return redirect(url_for('account'))
def index(): """ Display details of a single item. The item should be specified by passing its ID as a query parameter, e.g. /item?id=123 """ # Check that an ID was passed in, and show a 404 error if not. try: item_id = int(request.vars.get('id')) except ValueError as error: redirect(URL('error', 'not_found', args='item')) # Retrieve the item from the database. item = db_access.get_item(db, item_id) # Check that the item actually exists. if item is None: redirect(URL('error', 'not_found', args='item')) # Check if the item is private. If it is, the logged in user must match # the owner of the item. if item.private: if auth.user_id != item.owner_id: redirect(URL('error', 'private', args='item')) # Get the details of the item's owner. user = db_access.get_user(db, item.owner_id) # Set the title of the page to show the user where they are. response.title = item.name # Create a link to the user's profile. user_link = A(user.username, _href=URL('collection', 'index', vars={'id': user.id})) # Set the subtitle to say who owns the item. if item.on_wishlist: response.subtitle = 'On {user}\'s wishlist'.format(user=user_link) else: response.subtitle = 'Owned by {user}'.format(user=user_link) # The action buttons depend on whether the item belongs to the logged-in # user. They shouldn't be able to delete or edit someone else's item. if item.owner_id == auth.user_id: # Add buttons to the top of the page to edit and delete the item. page_actions = [ ('Edit', URL('item', 'edit', vars={'id': item.id}), 'pencil'), ('Delete', URL('item', 'confirm_delete', vars={'id': item.id}), 'trash') ] else: # Add a button to request a trade with the current item. This is shown # even if no user is logged in, so that people don't get confused by # there being no way to actually trade things. The create trade screen # will ask for a login anyway. page_actions = [ ('Request Trade', URL('trade', 'request_item', vars={'id': item.id}), 'transfer') ] return dict(item=item, user=user, page_actions=page_actions)
def login(handle, password): login_info = db_access.get_user_by_handle_and_password(handle, password) if login_info is not None: uid = login_info[0] # uid for user id handle = db_access.get_user(uid) session['user'] = uid session['name'] = handle flash('Hello %s!' % (handle), 'success_message') return True return False
def index(): """ URLs: - /search Function: - Display the search box - Display search results """ # Create the search form to put at the top of the page. form = search_form(submit_button='Search') # Set the title of the page. response.title = 'Search' # Process the form, keeping the text in the search box to remind the # user what they searched for. if form.process(keepvalues=True).accepted: # If a user is logged in, show results from their own collection, # including private comics, at the top of the page. Also, exclude # that user's results from the second section, which searches all # other users' comics. if auth.user_id is not None: my_results = db_access.search(form.vars.search_term, only_user=auth.user_id, include_private=True) other_results = db_access.search(form.vars.search_term, except_user=auth.user_id, include_private=False) # If no user is logged in, search across all users' public comics. else: my_results = None other_results = db_access.search(form.vars.search_term, include_private=False) else: my_results = None other_results = None # Add owner information to each comic. if my_results is not None: my_results = [(comic, db_access.get_user(comic.owner_id)) for comic in my_results] if other_results is not None: other_results = [(comic, db_access.get_user(comic.owner_id)) for comic in other_results] return dict(form=form, my_results=my_results, other_results=other_results)
def copy(): """ URLs: - /comic/copy?id=123 Function: - Ask the user which box to file a copy of a comic into, and then perform the copy operation. """ # Find out which comic is being copied. requested_comic = request.vars.get('id') # If a malformed ID (or no ID) is passed in, throw a 404 error. try: comic_id = int(requested_comic) except ValueError as error: raise HTTP(404) # Get the details of the comic. comic = db_access.get_comic(requested_comic) # If the requested comic doesn't exist, throw a 404. if comic is None: raise HTTP(404) # Get the id of the current user. current_user = auth.user_id # Get the details of the comic's owner. owner = db_access.get_user(comic.owner_id) # Set the title of the page. response.title = 'Copy Comic' # Remind the user what comic they are copying. response.subtitle = 'Copying {title} #{issue} from {name}'.format(title=comic.title, issue=comic.issue_number, name=owner.username) # Create a box selection form populated with a list of the user's boxes. form = box_selection_form(db, current_user, submit_button='Copy') # The form has no validation so it will always be accepted. if form.process().accepted: # Perform the copy operation, assigning the comic to the new user. new_comic_id = db_access.copy_comic(comic_id, current_user) # Create a filing between the new comic and the selected box. db_access.create_filing(new_comic_id, form.vars.box_id) # Take the user to their new comic. redirect(URL('comic', 'index', vars={'id': new_comic_id})) return dict(form=form)
def user_page(handle): uid = db_access.get_id(handle) uid = uid if uid is not None else handle my_followers = [] name = None chirp_list = [] if 'user' in session: my_followers = get_followers() user = session['user'] name = db_access.get_user(user) if db_access.user_exists(uid) is True: chirp_list = db_access.get_chirps(uid) handle = db_access.get_user(uid) return render_template('user_page.html', markdown=markdown2.markdown, handle=handle, uid=uid, user_data=db_access.user_data(uid), my_followers=my_followers, get_user=db_access.get_user, chirps=chirp_list, name=name) else: return render_template('404.html', notfound='user_page', handle=handle)
def vote_for_planet(): try: user = db_access.get_user(session.get('user')) db_access.add_vote(user.get('id'), request.args.get('pname')) result = ''' <div class="flashed-message bg-success"> <p class="text-success">Successfully voted.</p> </div> ''' except (db_access.CredentialsMissingError, db_access.DatabaseError): result = ''' <div class="flashed-message bg-warning"> <p class="text-danger">Vote unsuccessful.</p> </div> ''' return result
def chirp(): if 'user' in session: user = session['user'] MD = False if request.method == 'POST': content = request.form["content"] if len(content) in range(1, 360): db_access.add_chirp(content, user) if 'filter' in request.args: chirp_list = db_access.get_chirps( db_access.get_id(request.args.get('filter'))) else: chirp_list = db_access.get_all_chirps(user) return render_template('chirp.html', chirps=chirp_list, chirp_from_page=True, markdown=markdown2.markdown, name=db_access.get_user(session['user'])) return redirect(url_for('index'))
def send_today_info(message): try: chat_id = message.chat.id today_matches = db_access.today_matches() if (len(today_matches) == 0): bot.send_message(chat_id, 'No matches today!') today_matches_ids = [c['match_no'] for c in today_matches] user_profile = db_access.get_user(chat_id) info_text = 'Matches and your predictions for today:\n' if (user_profile == 0): return (0) else: user_predictions = user_profile['predictions'] today_user_prediction_ids = [c['match_no'] for c in user_predictions if c['match_no'] in today_matches_ids] # TODO: make map instead of for-loop: for match in today_matches: info_text = info_text + match['team_1'] + " vs. " + match['team_2'] + ': ' if match['match_no'] in today_user_prediction_ids: prediction = [c for c in user_predictions if c['match_no'] == match['match_no']][0] if (prediction['winner'] == 0): info_text = info_text + 'Draw ' info_text = info_text + str(prediction['goals']) + ':' + str(prediction['goals']) + ', ' else: if (prediction['winner'] == 1): info_text = info_text + match['team_1'] elif (prediction['winner'] == 2): info_text = info_text + match['team_2'] info_text = info_text + ' by ' + str(prediction['goals']) + ' goals, ' if (prediction['total'] == 0): info_text = info_text + '<2.5' elif (prediction['total'] == 1): info_text = info_text + '>2.5' else: info_text = info_text + 'No prediction (yet)' info_text = info_text + '\n' info_text = info_text + 'Click /predict to make Predictions!' bot.send_message(chat_id, info_text) except Exception as e: bot.reply_to(message, 'Something went wrong! Please, contact the provider of this bot!')
def bio(): if 'user' in session: usr = session['user'] db_access.edit_bio(usr, request.form.get('bio')) return redirect(url_for('user_page', handle=db_access.get_user(usr))) return redirect(url_for('index'))
def check_user(): try: user = db_access.get_user(request.args.get('username')) return str(user is not None) except (db_access.CredentialsMissingError, db_access.DatabaseError): return str(False)
def index(): try: owner_id = int(request.vars.get('id')) except ValueError as error: raise HTTP(404) except TypeError as error: if auth.is_logged_in() == False: redirect(URL('default', 'user/login',vars=dict(_next=URL('trade','index')))) else: redirect(URL('trade','index',vars=dict(id=auth.user_id))) owner = db_access.get_user(db, owner_id) # Make sure the user actually exists first. if owner is None: redirect(URL('error', 'not_found', args='user')) if owner_id == current_user: response.title = "Your Trades" trades = db_access.view_my_trades(db, current_user) else: response.title = "Your Trades with " + owner.username trades = db_access.view_my_trades_with_user(db, current_user, owner_id) # Get the first item in each trade so that images can be shown in the list. trades_and_items = [] for trade in trades: my_items = db_access.get_users_items_in_trade(db, trade.trade.id, current_user) # See which user (a or b) the current user is, then get the id of the # other user, in order to get their items from this trade. if trade.trade.user_a_id == current_user: other_user_id = trade.trade.user_b_id else: other_user_id = trade.trade.user_a_id their_items = db_access.get_users_items_in_trade(db, trade.trade.id, other_user_id) my_first_item = None their_first_item = None if len(my_items) > 0: my_first_item = my_items[0] if len(their_items) > 0: their_first_item = their_items[0] trades_and_items.append( (trade, my_first_item, their_first_item) ) page_actions = [ ('Collection', URL('collection', 'index', vars={'id': owner_id}), None), ('Wishlist', URL('wishlist', 'index', vars={'id': owner_id}), None), ('Trades', URL('trade', 'index', vars={'id': owner_id}), 'ok') ] #if the user is NOT looking at his own page, allow him to add a new trade if auth.user_id != owner_id: page_actions.append(('Request Trade', URL('trade', 'request_trade', vars={'id': owner_id}), 'transfer')) return dict(trades_and_items=trades_and_items, current_user=current_user, page_actions=page_actions)
def index(): """ URLs: - /comic?id=123 Function: - Display the details of the comic with the given ID. """ # Get the ID of the comic to display. requested_comic = request.vars.get('id') # If a malformed ID (or no ID) is passed in, throw a 404 error. try: comic_id = int(requested_comic) except ValueError as error: raise HTTP(404) # Get the details of the comic and its owner. comic = db_access.get_comic(requested_comic) # If the requested comic doesn't exist, throw a 404 error. if comic is None: raise HTTP(404) # Get the details of the comic's owner. user = db_access.get_user(comic.owner_id) # Get a list of the boxes the comic is stored in. If the comic's owner is # the currently logged in user, this can include private boxes. include_private = (comic.owner_id == user.id) boxes = db_access.get_boxes_for_comic(requested_comic, include_private=include_private) # If the comic is only filed in private boxes and the current user doesn't # own the comic, it shouldn't be visible. In this case, since the query # above would have excluded private boxes, then no boxes will have been # returned. has_permission = len(boxes) > 0 # If the user doesn't have permission, redirect to the private page. if not has_permission: redirect(URL('private', 'index', args='comic')) # Set the title of the page to show the user where they are. response.title = "{title} #{issue}".format(title=comic.title, issue=comic.issue_number) # Create a link to the comic's owner. user_link = A(user.username, _href=URL('user', 'index', vars={'id': user.id})) # Display the owner of the comic below the title. response.subtitle = 'Owned by {user}'.format(user=user_link) # The action buttons depend on whether the comic belongs to the logged-in # user. They shouldn't be able to delete or edit someone else's comic, or # copy their own comic to their collection. if comic.owner_id == auth.user_id: # Add buttons to the top of the page to edit, delete, and file the comic. page_actions = [ ('File in Boxes', URL('comic', 'file', vars={'id': comic.id}), 'credit-card'), ('Edit', URL('comic', 'edit', vars={'id': comic.id}), 'pencil'), ('Delete', URL('comic', 'confirm_delete', vars={'id': comic.id}), 'trash') ] elif auth.user_id is not None: # Add a button to copy the comic to the current user's collection, if a # user is actually logged in. page_actions = [ ('Copy to My Collection', URL('comic', 'copy', vars={'id': comic.id}), 'duplicate') ] else: page_actions = [] return dict(comic=comic, user=user, boxes=boxes, has_permission=has_permission, page_actions=page_actions)