def viewProfile(username='******'): if username == 'None': return redirect('/') viewer=session['username'] criteria= {"username":username} user=db.find_user(criteria) clubs=[] clubList= db.list_clubs(username) for club in clubList: clubs.append(club[0]) info=[username,user['first'],user['last'],user['schedule'],user['essays'],clubs] essays = db.find_essays({'user':username}) if request.method== 'GET': return render_template('profile.html',viewer=viewer,info=info,counter=False,user=user, essays=essays) else: button = request.form['button'] if button == 'Search': return redirect('/search/'+request.form['query']) localtime = time.strftime("%B %d, %Y, %I:%M %p") userMessage= user['Message'] message = request.form['User_Message'] message = {"Message":message,"Sender":session['username'],"Time":localtime} if userMessage== None: userMessage=[] userMessage.append(message) user=db.find_user(criteria) db.update_user(criteria,{"Message":userMessage}) essays = db.find_essays({'user':username}) return render_template('profile.html',info=info,viewer=viewer,counter=True,user=user, essays=essays)
def valid_change(username, password): if username == session['username']: #lets the user change his password if password == db.find_user({'username': username})['password']: return "Your information has not been changed." elif db.find_user({'username': username}): return "That username has already been taken." return True
def search_friends(q): user = db.find_user(current_user.username) ret = [] for c in user['contributors']: f = db.find_user(c, strip_id=True) if q['name'].lower() in f['name'].lower(): ret.append(f) return ret
def valid_change(username, password): if username == session['username']: #lets the user change his password if password == db.find_user({'username':username})['password']: return "Your information has not been changed." elif db.find_user({'username':username}): return "That username has already been taken." return True
def init_test_user(): if db.find_user('*****@*****.**') is None: password = '******' pw_hash = bcrypt.generate_password_hash(password).decode('utf-8') db.create_user(1, pw_hash, 2) if db.find_user('*****@*****.**') is None: password = '******' pw_hash = bcrypt.generate_password_hash(password).decode('utf-8') db.create_user(7, pw_hash, 3)
def contributors(username, q=None): ret = [] for f in db.find_user(username, q)['contributors']: f_doc = db.find_user(f, strip_id=True) if f_doc: ret.append(f_doc) else: print 'could not find', f return ret
def viewProfile(username='******'): if username == 'None': return redirect('/') viewer = session['username'] criteria = {"username": username} user = db.find_user(criteria) clubs = [] clubList = db.list_clubs(username) for club in clubList: clubs.append(club[0]) info = [ username, user['first'], user['last'], user['schedule'], user['essays'], clubs ] essays = db.find_essays({'user': username}) if request.method == 'GET': return render_template('profile.html', viewer=viewer, info=info, counter=False, user=user, essays=essays) else: button = request.form['button'] if button == 'Search': return redirect('/search/' + request.form['query']) localtime = time.strftime("%B %d, %Y, %I:%M %p") userMessage = user['Message'] message = request.form['User_Message'] message = { "Message": message, "Sender": session['username'], "Time": localtime } if userMessage == None: userMessage = [] userMessage.append(message) user = db.find_user(criteria) db.update_user(criteria, {"Message": userMessage}) essays = db.find_essays({'user': username}) return render_template('profile.html', info=info, viewer=viewer, counter=True, user=user, essays=essays)
def change_account(): if request.method == 'GET': return render_template('change_account.html') if request.form['button'] == 'cancel': return redirect('/') criteria = {'username': session['username']} old_password = request.form['old_password'] password = request.form['password'] password2 = request.form['password2'] first = request.form['first'] last = request.form['last'] changeset = {} if password: if old_password != db.find_user(criteria)['password']: return render_template('change_account.html', error="Incorrect old password entered.") if password == password2: changeset['password'] = password change_user_info('password',password) else: return render_template('change_account.html', error="Passwords must match.") if first: changeset['first'] = first change_user_info('first',first) if last: changeset['last'] = last change_user_info('last',last) return redirect('/display')
def display(): if request.method == 'POST': button = request.form['button'] if button == 'Change Settings': return redirect('/change') user = db.find_user({'username': session['username']}) return render_template('display.html', user=user)
def update_user(email): # Retrieve user data. row = db.find_user(email) if row is None: flash("User {} doesn't exist".format(email)) return redirect(url_for('all_users')) # Initialize object with form data if available (this is the default behavior for a FlaskForm; # you need not even provide the argument. Otherwise initialize with specific values fetched # previously from the database. user_form = UserForm(email=row['email'], first_name=row['first_name'], last_name=row['last_name']) if user_form.validate_on_submit(): # If we get here, we're handling a POST request and the form validated successfully. rowcount = db.update_user(email, user_form.first_name.data, user_form.last_name.data, user_form.password.data) # We're updating a single row, so we're successful if the row count is one. if rowcount == 1: # Everything worked. Flash a success message and redirect to the home page. flash("User '{}' updated".format(email)) return redirect(url_for('index')) else: # The update operation failed for some reason. Flash a message. flash('User not updated') return render_template( 'user-form.html', form=user_form, mode='update', )
def viewMessage(): user = db.find_user({'username': session['username']}) Message = user["Message"] if request.method == 'GET': return render_template('view_message.html', Message=Message) else: button = request.form['button'] if button == 'Search': return redirect('/search/' + request.form['query']) if button == "Submit Changes": counter = 0 toBeRemoved = [] for message in Message: try: request.form[str(counter) + "message"] removal = True except: removal = False if removal == True: toBeRemoved.append(counter) counter = counter + 1 for number in toBeRemoved: Message.pop(number) criteria = {"username": session['username']} db.update_user(criteria, {"Message": Message}) Message = user["Message"] return render_template('view_message.html', Message=Message)
def login(): if request.method== 'POST': button = request.form['button'] username = request.form['username'] password = request.form['password'] if button == 'Submit': criteria = {'username': username, 'password': password} user = db.find_user(criteria) if user!=None and username!= "": session['username'] = username return redirect('/home') else: return render_template('login.html',error="wrong info") else: return redirect('/register') else: if 'username' in session: return redirect('/home') return render_template('login.html')
def checkinmode(): clear() ui.chk() iny = raw_input("NAME: ") if iny == ":EXIT": home() else: pass def markin(uid): db.checkin(uid) try: x = db.find_user("name",iny) if chky(x.id) is False: markin(x.id) ui.ok() time.sleep(1) checkinmode() elif chky(x.id) is True: ui.chkold() time.sleep(1) checkinmode() else: #@error 003 ui.err("#003") time.sleep(1) checkinmode() except AttributeError: #@Error 001 ui.fail() time.sleep(1) checkinmode() except: #@error 002 #print sys.exc_info()[0] ui.err("#002") time.sleep(1) sys.exit()
def set_key(self, bot: Bot, update: Update, session: Session): tg_user = update.message.from_user user = find_user(session, tg_user.id) if user is None: update.message.reply_text(m.NOT_FOUND_USER) return tg.ConversationHandler.END try: redmine = Redmine(url=self.config.redmine_host, key=update.message.text) redmine.auth() except AuthError: update.message.reply_text(m.INVALID_REDMINE_KEY) user.redmine_user.key = '' session.add(user.redmine_user) session.commit() return tg.ConversationHandler.END user.redmine_user.key = update.message.text session.add(user.redmine_user) session.commit() update.message.reply_text(m.DONE_REDMINE_SETTINGS) update.message.reply_text(m.WELCOME_MESSAGES) return tg.ConversationHandler.END
def register(): if request.method == 'GET': return render_template('register.html') button = request.form['button'] username = request.form['username'] password = request.form['password'] first = request.form['first'] last = request.form['last'] if button == 'cancel': return redirect('/') else: if not password or not first or not last: return render_template('register.html', error='incomplete') criteria = {'username': username} if db.find_user(criteria): return render_template('register.html', error='username taken') else: initial_Schedule = [ "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "", "", "", "", "", "", "", "", "", "" ] user_params = { 'username': username, 'password': password, 'first': first, 'last': last, 'schedule': initial_Schedule, 'essays': [], 'Message': [] } db.new_user(user_params) session['username'] = username return redirect('/')
def start(self, bot, update, user_data, session): user = find_user(session, update.message.from_user.id) if user is None or user.redmine_user.empty(): update.message.reply_text(m.NOT_FOUND_USER) return tg.ConversationHandler.END update.message.reply_text(m.WELCOME_ENTRY_TIME) track_task = TimeEntry() track_task.user = user session.add(track_task) session.commit() user_data['track_task_id'] = track_task.id buttons = [ InlineKeyboardButton(russian_date(d), callback_data=str(d)) for d in date_from_today(range(0, -8, -1)) ] message = update.message.reply_text( m.SET_SPENT_ON.format(self.track_task_to_str(user_data)), reply_markup=InlineKeyboardMarkup(build_menu(buttons, n_cols=2))) user_data['message_id'] = message.message_id return SET_SPENT_ON
def spent_on(self, bot, update, user_data, session): tg_message = update.callback_query.message user_data['spent_on'] = dt.datetime.strptime( update.callback_query.data, '%Y-%m-%d').date() user = find_user(session, update.effective_user.id) if user is None or user.redmine_user.empty(): tg_message.reply_text(m.NOT_FOUND_USER) return tg.ConversationHandler.END redmine = Redmine(url=self.config.redmine_host, key=user.redmine_user.key) issues = self.config.redmine_general_issue for issue in redmine.auth().issues: issues[issue.id] = issue.subject user_data['issues'] = issues buttons = [ InlineKeyboardButton(name, callback_data=str(id)) for id, name in issues.items() ] reply_markup = InlineKeyboardMarkup(build_menu(buttons, n_cols=1)) bot.edit_message_text(m.SET_ISSUE.format( self.track_task_to_str(user_data)), chat_id=tg_message.chat.id, message_id=tg_message.message_id, reply_markup=reply_markup) return SET_ISSUE
def getClassmates(period): index = period - 1 user = db.find_user({'username': session['username']}) course = user['schedule'][index] classmates = db.find_classmates({'schedule.' + str(index): course}, 'username') return classmates
def change_account(): if request.method == 'GET': return render_template('change_account.html') if request.form['button'] == 'cancel': return redirect('/') criteria = {'username': session['username']} old_password = request.form['old_password'] password = request.form['password'] password2 = request.form['password2'] first = request.form['first'] last = request.form['last'] changeset = {} if password: if old_password != db.find_user(criteria)['password']: return render_template('change_account.html', error="Incorrect old password entered.") if password == password2: changeset['password'] = password change_user_info('password', password) else: return render_template('change_account.html', error="Passwords must match.") if first: changeset['first'] = first change_user_info('first', first) if last: changeset['last'] = last change_user_info('last', last) return redirect('/display')
def login(): username = request.form.get('username', '') password = request.form.get('password', '') user = db.check_password(username, password) exists = db.find_user(username) port = find_open_port() if port is None: return abort(503) if exists and user: t = binascii.hexlify(os.urandom(16)).decode('ascii') ws_ports[port] = 1 # placeholder tokens[t] = port usernames[t] = username return jsonify({'token': t}) elif exists: return abort(403) elif username and password and meets_requirements(username): db.create_user(username, password) t = binascii.hexlify(os.urandom(16)).decode('ascii') ws_ports[port] = 1 # placeholder tokens[t] = port usernames[t] = username return jsonify({'token': t}) else: return abort(400)
def __init__(self, email): self.email = email if db.find_user(self.email) is not None: self.role = db.find_user(self.email)['role'] self.name = db.find_member_info(self.email)['first_name'] self.user_id = db.find_user(self.email)['id'] self.member_id = db.find_member_info(self.email)['id'] else: self.role = 'no role' self.name = 'no name' if (self.role == 'homegroup_leader'): self.homegroup_id = db.find_user_homegroup(self.email) self.is_authenticated = True self.is_active = True self.is_anonymous = False
def viewMessage(): user= db.find_user({'username':session['username']}) Message=user["Message"] if request.method=='GET': return render_template('view_message.html',Message=Message) else: button = request.form['button'] if button == 'Search': return redirect('/search/'+request.form['query']) if button== "Submit Changes": counter=0 toBeRemoved=[] for message in Message: try: request.form[str(counter)+"message"] removal=True except: removal= False if removal==True: toBeRemoved.append(counter) counter= counter+1 for number in toBeRemoved: Message.pop(number) criteria= {"username":session['username']} db.update_user(criteria,{"Message":Message}) Message= user["Message"] return render_template('view_message.html',Message=Message)
def cancel_change_location(message): db_user = db.find_user(message.from_user.username) location = db_user.lastLocations[0] chat_index = user_queue.index(message.chat.id) del user_queue[chat_index] ask_forecast_type(message, location['locationName'])
def user_comments(email): user = db.find_user(email) if user is None: flash('No user with email {}'.format(email)) comments = [] else: comments = db.comments_by_user(email) return render_template('user-comments.html', user=user, comments=comments)
def wrapper(*args, **kwds): self, bot, update = args session = kwds['session'] user = find_user(session, update.callback_query.from_user.id) if user is None or user.redmine_user.empty(): update.message.reply_text(m.WELCOME_MESSAGES) return return f(*args, **kwds)
def test_edit_password_page(self): self.login('*****@*****.**', 'password') email = '*****@*****.**' db.open_db_connection('MyDatabase.sqlite') user = db.find_user(email) resp = self.client.get(url_for('update_user', user_id=user['id'])) self.assertTrue(b'Update Password' in resp.data, "Did not find the phrase: Update Password") self.assertTrue(b'*****@*****.**' in resp.data, "Did not find the phrase: [email protected]")
def classmates(): user = db.find_user({'username': session['username']}) periods = [1,2,3,4,5,6,7,8,9,10] classmates = {} #a dictionary with indices with the format... period:[classmates] for p in periods: course = user['schedule'][p-1] if course != 'N/A': l = getClassmates(p) #a list of classmates classmates[p] = l return render_template('classmates.html',user=user,classmates=classmates)
def fetch_user_computers(username): print '>>', username user = db.find_user(username) print user['computers'] if user: return jsonify(html=render_template('items.html', items=user['computers'], item_type='computers'), item_data=user['computers']) else: return jsonify(html='No items found.', item_data=[])
def suggest_friends(username, q={}): '''returns 2nd degree connections as suggestions or all participants if no friends are found''' user = db.find_user(username) if not user: print 'could not find user', username return [] ret = [] if len(user['contributors']) == 0: return find_non_friends(user) for cname in user['contributors']: c = db.find_user(cname) if c: for suggestion in [db.find_user(i, strip_id=True) for i in c['contributors']]: if suggestion and not suggestion['username'] in user['contributors']: ret.append(suggestion) if len(ret) == 0: return find_non_friends(user) return ret
def viewSchedule(): if request.method == 'POST': button = request.form['button'] if button == 'Change Schedule': return redirect('/edit_schedule') elif button == 'View Classmates': return redirect('/classmates') elif button == 'View Teachers': return redirect('/view_teachers') user = db.find_user({'username': session['username']}) return render_template('view_schedule.html',user=user)
def test_add_user(self): """Make sure we can add a new user.""" row_count = db.create_user('*****@*****.**', 'FirstName', 'LastName', 'pass') self.assertEqual(row_count, 1) test_user = db.find_user('*****@*****.**') self.assertIsNotNone(test_user) self.assertEqual(test_user['first_name'], 'FirstName') self.assertEqual(test_user['last_name'], 'LastName')
def editSchedule(): user = db.find_user({'username': session['username']}) if request.method == 'GET': return render_template('edit_schedule.html', staff=staff, user=user) else: button = request.form['button'] if button == 'cancel': return redirect('/') else: user = db.find_user({'username': session['username']}) sL = [] xd = 1 while xd != 11: sL.append(request.form['teacher' + str(xd)]) xd += 1 while xd != 21: sL.append(request.form['course' + str(xd - 10)]) xd += 1 db.update_schedule(user, sL) return redirect('/view_schedule')
def return_tomorrow_forecast(message): db_user = db.find_user(message.from_user.username) location = db_user.lastLocations[0] location_name, lat, lon = location['locationName'], location[ 'lat'], location['lon'] forecast = get_forecast_by_coords(lat, lon, forecast_types['tomorrow']) bot_response = forecast_template(forecast, forecast_types["tomorrow"], location_name) bot.send_message(message.chat.id, f'{bot_response}', parse_mode='HTML')
def classmates(): user = db.find_user({'username': session['username']}) periods = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] classmates = { } #a dictionary with indices with the format... period:[classmates] for p in periods: course = user['schedule'][p - 1] if course != 'N/A': l = getClassmates(p) #a list of classmates classmates[p] = l return render_template('classmates.html', user=user, classmates=classmates)
def editSchedule(): user = db.find_user({'username': session['username']}) if request.method == 'GET': return render_template('edit_schedule.html', staff=staff, user=user) else: button = request.form['button'] if button == 'cancel': return redirect('/') else: user = db.find_user({'username': session['username']}) sL=[] xd = 1 while xd !=11: sL.append( request.form['teacher'+str(xd)]) xd+= 1 while xd !=21: sL.append(request.form['course'+str(xd-10)]) xd+=1 db.update_schedule(user,sL) return redirect('/view_schedule')
def home_search(): def outy(iny): print "NAME CHECK-INS" y = 14 - len(iny.name) l = " "*y print iny.name, l, iny.checkins print "=====================" print "---> SEARCH MENU <---" print "=====================" do = raw_input("Search by [N]ame or [I]D ") if do in ("N", "n"): x = raw_input("Search by Full Name: ") z = db.find_user("name",x) outy(z) elif do in ("I","i"): x = raw_input("Search by ID: ") z = db.find_user("id",x) outy(z) raw_input("Press [enter] to go home") home()
def viewSchedule(): if request.method == 'POST': button = request.form['button'] if button == 'Change Schedule': return redirect('/edit_schedule') elif button == 'View Classmates': return redirect('/classmates') elif button == 'View Teachers': return redirect('/view_teachers') user = db.find_user({'username': session['username']}) return render_template('view_schedule.html', user=user)
def create_user(): if request.method == "GET": users_info = db.find_user() return render_template("login.html", users_info=users_info) if request.method == "POST": userid = request.form["userid"] name = request.form["name"] password = request.form["password"] db.create_user(userid, name, password) return redirect(url_for("add_goal"))
async def login(request): params = ['username', 'password'] data = with_body(request, params) if len(data) == len(params): user = find_user(data) if user is not None: return __create_session(user) else: return response.json({'message': 'invalid credentials'}, status=404) else: return response.json({'message': 'missing data'}, status=400)
def create_user(member_id): allRoles = db.find_roles() roleList = [] email_list = [] for role in allRoles: roleList.append((role["id"], role["role"])) member = db.find_member(member_id) email = member['email'] user_form = UserForm() user_form.role.choices = roleList homegroups = db.get_all_homegroups() homegroup_list = [] for homegroup in homegroups: homegroup_list.append((homegroup['id'], homegroup['name'])) user_form.homegroups.choices = homegroup_list if user_form.validate_on_submit(): email_list.append(email) password = user_form.password.data pw_hash = bcrypt.generate_password_hash(password).decode('utf-8') db.create_user(member_id, pw_hash, user_form.role.data) user = db.find_user(email) email_html = render_template('user_account_email.html', email=email, password=password, user_id=user['id']) msg = Message( 'User account created for Verbo Velocity', sender='*****@*****.**', recipients=email_list, html=email_html) mail.send(msg) if user_form.homegroups.data is not None: homegroupId = user_form.homegroups.data user_id = db.find_user(email)['id'] db.add_leader_to_homegroup(user_id, homegroupId) flash('User Created') return redirect(url_for('all_members')) return render_template('create_user.html', form=user_form, email = email)
def test_update_user(self): """Add and then update a user.""" row_count = db.create_user('*****@*****.**', 'FirstName', 'LastName', 'pass') self.assertEqual(row_count, 1) row_count = db.update_user('*****@*****.**', 'NewFirstName', 'LastName', 'newpass') self.assertEqual(row_count, 1) test_user = db.find_user('*****@*****.**') self.assertIsNotNone(test_user) self.assertEqual(test_user['first_name'], 'NewFirstName') self.assertEqual(test_user['last_name'], 'LastName')
def start(self, bot: Bot, update: Update, session: Session): tg_user = update.message.from_user user = find_user(session, tg_user.id) if user is None: user = User( telegram_id=tg_user.id, telegram_name=tg_user.first_name) # add last_name if exists session.add(user) session.commit() update.message.reply_text(m.START_REDMINE_SETTINGS) update.message.reply_text(m.SET_REDMINE_KEY) return STAGE_SET_KEY
def manage_friend(friend_username, add=False, remove=False): print 'add_friend(%s)' % friend_username user = db.Participant(current_user.username, load=True) if db.find_user(friend_username): try: if add: user['contributors'].append(friend_username) elif remove: user['contributors'].pop(user['contributors'].index(friend_username)) user.save() except: print 'unknown error occured when managing friend' return jsonify(nailedit=False) return jsonify(nailedit=True) else: return jsonify(nailedit=False)
def ask_first_location(message): user_queue.append(message.chat.id) db_user = db.find_user(message.from_user.username) if not db_user: new_user = db.create_user(message.from_user.username) markup = types.ReplyKeyboardMarkup(row_width=1, one_time_keyboard=True, resize_keyboard=True) location_button = types.KeyboardButton('Отправить текущее место', request_location=True) markup.add(location_button) bot.send_message( message.chat.id, 'Напишите название локации, для которой хотите узнать погоду или отправьте текущее местоположение (достутпно только для мобильных устройств)', reply_markup=markup)
def handleLogin(self): username = str(self.username.text()) password = str(generate_password_hash(str(self.password.text()))) print(self.username.text(), password) results = find_user(username, password) print(results) if results != None: self.close() self.child_win = Sharingan(username) self.child_win.setWindowTitle('Sharingan') self.child_win.show() else: self.child_win = Popup('incorrect password/username. Please Check it again !') self.child_win.setWindowTitle('Alert') self.child_win.show()
def register(): if request.method == 'GET': return render_template('register.html') button = request.form['button'] username = request.form['username'] password = request.form['password'] if button == 'cancel': return redirect('/') else: criteria = {'username': username} if db.find_user(criteria): return render_template('register.html',error=True) else: user_params = {'username': username, 'password': password} db.new_user(user_params) session['username'] = username return redirect('/')
def login(): if request.method == 'GET': return render_template('login.html') button = request.form['button'] username = request.form['username'] password = request.form['password'] valid_user = valid(username, password) if button == 'cancel' or not(valid_user): return redirect('/') else: criteria = {'username': username, 'password': password} user = db.find_user(criteria) if user: session['username'] = username db.touch_user_login_time(criteria) return redirect('/') else: return render_template('login.html',error=True)
def register(): if request.method == 'GET': return render_template('register.html') button = request.form['button'] username = request.form['username'] password = request.form['password'] first = request.form['first'] last = request.form['last'] if button == 'cancel': return redirect('/') else: if not password or not first or not last: return render_template('register.html',error='incomplete') criteria = {'username': username} if db.find_user(criteria): return render_template('register.html',error='username taken') else: initial_Schedule= ["N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","","","","","","","","","",""] user_params = {'username': username, 'password': password, 'first': first, 'last': last, 'schedule':initial_Schedule, 'essays':[],'Message':[]} db.new_user(user_params) session['username'] = username return redirect('/')
def register(): if request.method == 'GET': return render_template('register.html') button = request.form['button'] username = request.form['username'] password = request.form['password'] first = request.form['first'] last = request.form['last'] if button == 'Cancel': return redirect('/') else: if not password or not first or not last: return render_template('register.html',error='incomplete') criteria = {'username': username} if db.find_user({'username':username}): return render_template('register.html',error='username taken') else: user_params = {'username': username, 'password': password, 'first': first, 'last': last} db.new_user(user_params) return redirect('/')
def post_essay(): user = db.find_user({'username': session['username']}) if request.method == 'GET': return render_template('post_essay.html') else: button = request.form['button'] if button == 'Cancel': return redirect('/') elif button == 'Post': title = request.form['title'] topic = request.form['topic'] essay = request.form['essay'] anon = request.form['anon'] if not title or not essay: return render_template('post_essay.html',error='Please complete all required fields.') if not topic: topic = "None" newEssay={} newEssay['title'] = title newEssay['topic'] = topic newEssay['essay'] = essay if anon == "yes": newEssay['author'] = "Anonymous" else: newEssay['author'] = session['username'] #adds essay id to essays list in user previous_essays = db.find_attribute({'username': session['username']}, "essays") essay_id = session['username'] + str(len(previous_essays)) previous_essays.append(essay_id) change_user_info('essays', previous_essays) newEssay['essay_id'] = essay_id localtime = time.strftime("%B %d, %Y, %I:%M %p") #Time in formate of Full month name, day, full year, hour:minute AM/PM https://docs.python.org/3.0/library/time.html newEssay['time'] = localtime db.post_essay(session['username'], newEssay) return redirect('/essays')
def getClassmates(period): index = period - 1 user = db.find_user({'username': session['username']}) course = user['schedule'][index] classmates = db.find_classmates({ 'schedule.' + str(index) : course },'username') return classmates
def display(): if 'username' in session: user = db.find_user({'username': session['username']}) return render_template('display.html', user=user) else: return render_template('display.html')
def GET(self, action): web.header("Content-Type", "application/json") set_no_cache() # check if we have the action if action not in self.GET_ACTIONS: return error.wrong_action() # get the input data if we have the spec if action in self.VALIDATE_SPECS: d = get_input(self.VALIDATE_SPECS[action]) uuid = session.get("uuid", None) if not uuid: return error.not_logged_in() if action == "stream": param = spec.extract(self.EXTRACT_SPECS["stream_request"], d) if param["type"] == "user": if not param["uid"]: raise web.badrequest() elif param["type"] == "list": if not param["list_id"]: raise web.badrequest() ret = db.stream(uuid, **param) if "error" in ret: return jsond(ret) else: return jsond(spec.extract(self.EXTRACT_SPECS["stream_response"], ret)) elif action == "current_user": u = db.get_user(uuid) return jsond(spec.extract(self.EXTRACT_SPECS["current_user"], u)) elif action == "userinfo": u = db.find_user(d.uid) if not u: return error.user_not_found() u["isfollowing"] = bson.objectid.ObjectId(uuid) in u["follower"] return jsond(spec.extract(self.EXTRACT_SPECS["userinfo"], u)) elif action == "get_following": param = spec.extract(self.EXTRACT_SPECS["userlist_request"], d) ret = db.get_following(uuid, **param) new_items = [spec.extract(self.EXTRACT_SPECS["userinfo"], u) for u in ret["items"]] ret["items"] = new_items return jsond(ret) elif action == "get_follower": param = spec.extract(self.EXTRACT_SPECS["userlist_request"], d) ret = db.get_follower(uuid, **param) new_items = [spec.extract(self.EXTRACT_SPECS["userinfo"], u) for u in ret["items"]] ret["items"] = new_items return jsond(ret) elif action == "get_message": ret = db.get_message(uuid, d.msg_id) if "error" in ret: return jsond(ret) else: return jsond(spec.extract(self.EXTRACT_SPECS["stream_response"], ret)) elif action == "validate": act = d.action if act in self.VALIDATE_SPECS: errors = spec.validate(self.VALIDATE_SPECS[act], web.input()) if errors: return jsond(errors) else: return jsond({"success": 1}) else: return error.wrong_action() elif action == "recommend_user": return jsond({"users": [spec.extract(self.EXTRACT_SPECS["userinfo"], u) for u in db.recommend_user(uuid)]}) elif action == "get_lists": ret = db.get_lists(uuid, d.get("uid")) if "error" in ret: return jsond(ret) else: return jsond({"items": [spec.extract(self.EXTRACT_SPECS["listinfo"], l) for l in ret]}) elif action == "get_list_info": ret = db.get_list_info(uuid, d["id"]) if "error" in ret: return jsond(ret) else: return jsond(spec.extract(self.EXTRACT_SPECS["listinfo"], ret)) elif action == "get_list_users": param = spec.extract(self.EXTRACT_SPECS["list_userlist_request"], d) ret = db.get_list_users(uuid, param["id"], param["skip"]) new_items = [spec.extract(self.EXTRACT_SPECS["userinfo"], u) for u in ret["items"]] ret["items"] = new_items return jsond(ret) elif action == "search": req = spec.extract(self.EXTRACT_SPECS["search_request"], d) ret = db.search(uuid, **req) if "error" in ret: return jsond(ret) else: return jsond(spec.extract(self.EXTRACT_SPECS["stream_response"], ret)) return error.not_implemented()
def startpage(username): user_doc = db.find_user(username, strip_id=True) return render_template('startpage.html', user_doc=user_doc, computers=[], username=username)
def user_prefs(username): user = db.find_user(username, strip_id=True) if not user: user = db.base_user_template(username) return jsonify(user_doc=user, html=render_template('user_prefs.html', user_doc=user))
def computers(username): user = db.find_user(username) return jsonify(computers=user['computers'], html=render_template('computers.html', computers=user['computers']))