def startpg(message): add_user(message.chat.id) startmenu = types.ReplyKeyboardMarkup(True, False) startmenu.row('Увидеть последние новости') startmenu.row('Подписаться на рассылку') startmenu.row('Отказаться от подписки') bot.send_message(message.chat.id, 'Привет!', reply_markup=startmenu)
def adduser(): if request.method == "GET": username = session.get("name") return render_template("register.html", username=username) #前端post请求,逻辑端通过request.form获取整个表单的值 if request.method == "POST": userlist = dict((k, v[0]) for k, v in dict(request.form).items()) userlist['password'] = hashlib.md5(userlist['password'] + salt).hexdigest() userlist['re_password'] = hashlib.md5(userlist['re_password'] + salt).hexdigest() if userlist["name"] in [n.values()[0] for n in get_userlist(["name"])]: errmsg = "username is exist" return json.dumps({'code': '1', 'errmsg': errmsg}) if not userlist["name"] or not userlist["password"]: errmsg = "username and password is not empty" return json.dumps({'code': '1', 'errmsg': errmsg}) if userlist["password"] != userlist["re_password"]: errmsg = "password is error" return json.dumps({'code': '1', 'errmsg': errmsg}) fields = [ "name", "name_cn", "password", "mobile", "email", "role", "status" ] values = ['%s' % userlist[x] for x in fields] userdict = dict([(k, values[i]) for i, k in enumerate(fields)]) add_user(userdict) return json.dumps({'code': '0', 'result': "register sucess"})
def on_message(message): if message.channel.is_private: if message.content == 'cancel': remove_user(message.author) client.send_message( message.author, 'You have been removed from the alert list.' ) elif any([m == client.user for m in message.mentions]): if 'subscribe' in message.content: add_user(message.author) client.send_message( message.author, dedent( ''' You are now on the alert list. Type "cancel" to remove yourself from the list. ''' ).strip() ) if 'help' in message.content: client.send_message( message.channel, dedent( ''' This bot will PM you when MapleStory is back online. All inquiries should be sent to Reticence via PM. Usage: @Maple Alert subscribe @Maple Alert help ''' ).strip() )
def main(): print("==== Welcome to CRM Application =====") print("[S]how all customers information") print("[A]dd new customer") print("[Q]uit") print("==============================") command = input("Your Command > ") while command != "q": if command == "s": print("顧客一覧を表示します") for user in find_all_users(): name = user[0] age = user[1] print(f"Name: {name} Age: {age}") elif command == "a": print("新規の顧客情報を追加します") name = input("new customer's name ? > ") age = input("new customer's age ? > ") add_user(name, age) print(f"Add new customer {name}") else: print(f"{command}: command not found") command = input("Your Command > ") print("Bye")
def command_handler(message: types.Message): if message.text == '/start': db.add_user(message.from_user.id, message.from_user.first_name) bot.send_sticker( message.chat.id, 'CAACAgEAAxkBAAMaXjnCIjuhV6-wpLsKtDRksUHERd8AAn0AA8WInATR-Nr5m7ajfxgE' ) markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton(answers[0]) item2 = types.KeyboardButton(answers[1]) markup.add(item1, item2) bot.send_message(message.chat.id, 'Evil Morty bot wants to have some fun ...', reply_markup=markup) else: bot.send_message( message.chat.id, """\ Click on "Random 5 movies to watch" button provides you some movies. "Add/Update/Delete/All" button: Add tv show (or anime) to your list in this pattern "title-season-episode" For example: "Rick and Morty-2-5" Update tv show (or anime) to your list in this pattern "title-season-episode" For example: "Rick and Morty-4-4" Delete tv show (or anime) to your list in this pattern "title" For example: "Rick and Morty" All return the whole list of your shows. """)
def index(): action = "Sign Up" # Content for buttons and forms form = SignUpForm() if form.validate_on_submit(): email = form.email.data username = form.username.data password = passwd_hash(form.password.data) try: db.add_user(email, username, password) except IntegrityError: flash("Seems like this account already exists") return render_template("index.html", title=action, form=form, action=action) session['user'] = username # Remember current user return redirect(url_for('search')) return render_template("index.html", title=action, form=form, action=action)
def callback(): # TODO: handle errors auth_code = request.args.get('code') state = request.args.get('state').split(':') scheduling_type = state[0] email = state[1] token_response = requests.post('https://accounts.spotify.com/api/token', headers={ 'Content-Type': 'application/x-www-form-urlencoded' }, params={ 'grant_type': 'authorization_code', 'code': auth_code, 'redirect_uri': config.redirect_uri, 'client_id': config.client_id, 'client_secret': config.client_secret }).json() access_token = token_response['access_token'] refresh_token = token_response['refresh_token'] user_info = requests.get('https://api.spotify.com/v1/me', headers={ 'Authorization': 'Bearer ' + access_token }).json() user_id = user_info['display_name'] db.add_user(user_id, access_token, refresh_token, email, scheduling_type) # redirect to success page here return "success"
def adduser(): if request.method == "GET": username = session.get("name") return render_template("register.html", username=username) #前端post请求,逻辑端通过request.form获取整个表单的值 if request.method == "POST": userlist = dict((k, v[0]) for k, v in dict(request.form).items()) print userlist print[n.values()[0] for n in get_userlist(["name"])] print userlist["name"] if userlist["name"] in [n.values()[0] for n in get_userlist(["name"])]: errmsg = "username is exist" return json.dumps({'code': '1', 'errmsg': errmsg}) if not userlist["name"] or not userlist["password"]: errmsg = "username and password is not empty" return json.dumps({'code': '1', 'errmsg': errmsg}) if userlist["password"] != userlist["re_password"]: errmsg = "password is error" return json.dumps({'code': '1', 'errmsg': errmsg}) fields = [ "name", "name_cn", "password", "mobile", "email", "role", "status" ] values = ['%s' % userlist[x] for x in fields] print values #[u'weixiaobao', u'weixiaobao', u'123', u'123123', u'123113', u'ops', u'0'] userdict = dict([(k, values[i]) for i, k in enumerate(fields)]) print userdict #{'status': u'0', 'name': u'weixiaobao', 'mobile': u'123123', 'name_cn': u'weixiaobao', 'role': u'ops', 'password': u'123', 'email': u'123113'} add_user(userdict) return json.dumps({'code': '0', 'result': "register sucess"})
def adduser(): if request.method =="GET": return render_template("register.html") #前端post请求,逻辑端通过request.form获取整个表单的值 if request.method =="POST": userlist=dict((k,v[0]) for k,v in dict(request.form).items()) if userlist["name"] in [ n.values() for n in get_userlist(["name"]) ]: content = "username is exist" return render_template("register.html",content=content) if not userlist["name"] or not userlist["password"]: content = "username and password is not empty" return render_template("register.html",content=content) if userlist["password"] != userlist["re_password"]: content="password is error" return render_template("register.html",content=content) fields = ["name","name_cn","password","mobile","email","role","status"] values = [ '%s'%userlist[x] for x in fields] print values #[u'weixiaobao', u'weixiaobao', u'123', u'123123', u'123113', u'ops', u'0'] userdict = dict([(k,values[i]) for i,k in enumerate(fields)]) print userdict #{'status': u'0', 'name': u'weixiaobao', 'mobile': u'123123', 'name_cn': u'weixiaobao', 'role': u'ops', 'password': u'123', 'email': u'123113'} add_user(userdict) return redirect("/login")
def on_message(message): if message.channel.is_private: if message.content == 'cancel': remove_user(message.author) client.send_message(message.author, 'You have been removed from the alert list.') elif any([m == client.user for m in message.mentions]): if 'subscribe' in message.content: add_user(message.author) client.send_message( message.author, dedent(''' You are now on the alert list. Type "cancel" to remove yourself from the list. ''').strip()) if 'help' in message.content: client.send_message( message.channel, dedent(''' This bot will PM you when MapleStory is back online. All inquiries should be sent to Reticence via PM. Usage: @Maple Alert subscribe @Maple Alert help ''').strip())
def registration(user_id, text): refcode = rc.generate_code() if rc.has_refcode(text) and db.get_id_by_refcode(rc.extract_refcode(text)): parent_id = db.get_id_by_refcode(rc.extract_refcode(text)) parent_name = db.get_name_by_id(parent_id) bot.send_message(user_id, msgs.hello_ref.format(parent_name, parent_id)) parent_id_2 = db.get_parent_by_id(parent_id) parent_id_3 = db.get_parent_by_id(parent_id_2) for line_n, parent in enumerate([parent_id, parent_id_2, parent_id_3]): if parent is not None: line_c = db.increment_line(line_n, parent) airtabledb.increment_line(line_n, line_c, db.get_at_id(parent)) db.add_user(user_id, refcode, bot_time.get_time(), parent_id, parent_id_2, parent_id_3) intro_1_f(id=user_id) else: parent_id = 398821553 # Айгуль ID parent_id_2 = None parent_id_3 = None for line_n, parent in enumerate([parent_id, parent_id_2, parent_id_3]): if parent is not None: line_c = db.increment_line(line_n, parent) airtabledb.increment_line(line_n, line_c, db.get_at_id(parent)) # parent_name = db.get_name_by_id(parent_id) # bot.send_message(user_id, msgs.hello_ref.format(parent_name, parent_id)) db.add_user(user_id, refcode, bot_time.get_time(), ref_parent=parent_id) intro_1_f(id=user_id)
def SignUp_user(): username_value = username.get() occur = 0 for i in db.get_users( ): # i represents element of info which is list itself if username_value == i[ 0]: #to access the username of the "i" list and compare with the username entered by user occur = 1 # if username already exists in database if occur == 1: messagebox.showerror('Username', "User already exists") SignUp_screen.destroy() else: if (len(username_value) >= 4 and len(username_value) <= 10): password_value = password.get( ) #input password if username doesn't already exists length = len(password_value) # taking the length of password if length >= 5 and length <= 10: #To check all the conditions on the password are satisfied t = (username_value, password_value ) #create a tuple "t" containing name and password db.add_user(t) # add to database messagebox.showinfo('SignUp', "Registration successful!") SignUp_screen.destroy() else: if (length < 5 or length > 10): messagebox.showerror( 'Password', "Your password should have 5-10 characters") else: if (len(username_value) < 4 or len(username_value) > 10): messagebox.showerror('Username', "Username should be 5-10 characters")
async def on_member_join(member): desired_channel = discord.utils.get(member.guild.text_channels, name="general") await desired_channel.send( f"Meow, {member.mention} welcome to the channel *bro*") db.add_user(member.id, member.name, member.joined_at, member.guild.id) print("added {member.name} to db")
def hyvaksyn(update, context): """Conversation handler for when the user accepts terms and conditions.""" user = update.effective_user if update.message.text == "Kyllä": name = "" if user.first_name and user.last_name: name = "{} {}".format(user.first_name, user.last_name) else: name = user.first_name nick = "" if user.username: nick = user.username db.add_user(user.id, nick, name, 30) context.bot.send_message( update.effective_chat.id, "Onneksi olkoon! Sinut on nyt lisätty käyttäjäksi. Kirjoittamalla /piikki_ohje näet mitä kaikkea sähköisellä piikillä voi tehdä.", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END else: context.bot.send_message( update.effective_chat.id, "Ei se mitään, paperinen piikki on myös ihan okei. Minä odottelen täällä jos muutatkin mielesi :)", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def adduser(): if request.method == "GET": return render_template("register.html") #前端post请求,逻辑端通过request.form获取整个表单的值 if request.method == "POST": userlist = dict((k, v[0]) for k, v in dict(request.form).items()) if userlist["name"] in [n.values() for n in get_userlist(["name"])]: content = "username is exist" return render_template("register.html", content=content) if not userlist["name"] or not userlist["password"]: content = "username and password is not empty" return render_template("register.html", content=content) if userlist["password"] != userlist["re_password"]: content = "password is error" return render_template("register.html", content=content) fields = [ "name", "name_cn", "password", "mobile", "email", "role", "status" ] values = ['%s' % userlist[x] for x in fields] print values #[u'weixiaobao', u'weixiaobao', u'123', u'123123', u'123113', u'ops', u'0'] userdict = dict([(k, values[i]) for i, k in enumerate(fields)]) print userdict #{'status': u'0', 'name': u'weixiaobao', 'mobile': u'123123', 'name_cn': u'weixiaobao', 'role': u'ops', 'password': u'123', 'email': u'123113'} add_user(userdict) return redirect("/login")
def register_post(role,token): form = RegistrationForm(role) if form.validate_on_submit(): db.add_user(form.username.data,form.email.data,form.password.data,form.role) db.del_pre_user(role,token) return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def get_userinfo(uid): if not db.is_user_exist(uid): print uid req = urllib2.Request(url='http://weibo.com/'+uid+'/follow',) result = urllib2.urlopen(req) try: text = result.read().decode('utf-8') match = re.compile(u'<title>[\s\S]*?的微博') searchResult = re.search(match, text) nick = searchResult.group(0)[7:-3].encode('utf-8') # 为了拿到总关注数目 和 总粉丝数 # 匹配 <strong node-type=\"follow\">455<\/strong>\r\n\t\t\t<span>关注 <\/span>\r\n\t\t<\/a>\r\n\t<\/li>\r\n\t<li class=\"follower S_line1\">\r\n\t\t<a class=\"S_func1\" name=\"place\" href=\"\/p\/1005051867684872\/follow?relate=fans&from=100505&wvr=5&mod=headfans\">\r\n\t\t\t<strong node-type=\"fans\">760<\/strong>\r\n\t\t\t<span>粉丝 match = re.compile(u'<strong[\s\S]*?>粉丝') searchResult = re.search(match, text) result = searchResult.group(0).encode('utf-8').split('>') follows = result[1].split('<')[0] fans = result[9].split('<')[0] if re.match(r'\d+', fans): db.add_user(uid, nick, follows, fans) return True else: # 有些页面匹配也会出错,先不往数据库中插数据 print '>>>[Error: get_userinfo]', uid, nick, follows, fans # print {}.fromkeys(rawlv2).keys()[0].encode('utf-8') except Exception, e: # 企业版的比较特殊 print '>>>[Error: get_userinfo]', uid, e
def create_account(username, password1, password2): if not username in get_users(): if password1 == password2: add_user(username, hashlib.sha224(password1).hexdigest()) return 0 return 1 return 2
def register_action(): #register the guy... user_name = request.form['login'] password = request.form['password'] db.add_user(user_name, password) return redirect(url_for('static', filename='ecourt_template.html'))
def added(): db.connect() username = request.form['username'] password = request.form['password'] full_name = request.form['full_name'] db.add_user(username, password, full_name) res = db.select_user_info(username, 'users') db.close() return render_template('added.html', user_info=res)
def post_signup(): username = request.form.get('username') password = request.form.get('password') nick_name = request.form.get('nick_name') if find_username(username) == None: add_user(username, nick_name, password) return render_template('index.html') else: return redirect(url_for('get_signup'))
def get_self_weibo_relation(selfUid): req = urllib2.Request(url='http://weibo.com/'+selfUid+'/myfollow',) result = urllib2.urlopen(req) text = result.read().decode('utf-8') # text = result.read() # 为了拿到自己的 昵称 总关注数目 总粉丝数 match = re.compile(u'class="gn_name" target="_top" title="[\s\S]*?"') searchResult = re.search(match, text) selfNick = searchResult.group(0)[37:-1].encode('utf-8') match = re.compile(u'全部关注\(\d+\)') searchResult = re.search(match, text) follows = searchResult.group(0)[5:-1] match = re.compile(u'粉丝\(\d+\)') searchResult = re.search(match, text) fans = searchResult.group(0)[3:-1] # 把自己加到数据库中 db.add_user(selfUid, selfNick, follows, fans) match = re.compile(u'uid=\d+') rawlv2 = re.findall(match, text) uidList = {}.fromkeys(rawlv2).keys() currentPageNum = 1 while len(uidList) < int(follows): print currentPageNum, len(uidList) match = re.compile(u'下一页') rawlv2 = re.findall(match, text) result = {}.fromkeys(rawlv2).keys() if len(result) > 0: currentPageNum += 1 req = urllib2.Request(url='http://weibo.com/'+selfUid+'/myfollow?t=1&page='+str(currentPageNum),) result = urllib2.urlopen(req) text = result.read().decode('utf-8') match = re.compile(u'uid=\d+') rawlv2 = re.findall(match, text) uidList += {}.fromkeys(rawlv2).keys() else: break print 'len(uidList)=',len(uidList) uidList = get_real_uid_list(uidList) uidList = list(set(uidList)) # remove duplicate element if selfUid in uidList: uidList.remove(selfUid) print uidList if len(uidList) > 0: for uid in uidList: db.add_relation(selfUid, uid) get_userinfo(uid) # 更新自己的 db_follows db_follows = db.count_db_follows(selfUid) db.update_user_db_follows(selfUid, db_follows)
def one(update: Update, _: CallbackContext) -> int: query = update.callback_query query.answer() keyboard = [[ InlineKeyboardButton(buttons_EditProfile[0], callback_data=str("name")), InlineKeyboardButton(buttons_EditProfile[1], callback_data=str("phone")), ], [ InlineKeyboardButton(buttons_EditProfile[2], callback_data=str("payment")), ], [ InlineKeyboardButton(BACK, callback_data=str("start")), ]] reply_markup = InlineKeyboardMarkup(keyboard) result = fetch_profile(_.user_data['user']['id']) if (not result): facts = list() facts.append( "Hi! It seems your are new user. Can you help us fill in your profile information?" ) facts.append(f"*{'Name'}*: ") facts.append(f"*{'Phone Number'}*: ") facts.append(f"*{'Preferred Payment Method'}*: ") profilemessage = "\n".join(facts).join(['\n', '\n']) add_user(_.user_data['user']['id']) query.edit_message_text(text=message1 + profilemessage, parse_mode='Markdown', reply_markup=reply_markup) else: facts = list() if (result.get('name')): facts.append(f"*{'Name'}*: {result['name']}") else: facts.append(f"*{'Name'}*:") if (result.get('phone')): facts.append(f"*{'Phone Number'}*: {result['phone']}") else: facts.append(f"*{'Phone Number'}*:") if (result.get('payment')): facts.append( f"*{'Preferred Payment Method'}*: {result['payment']}") else: facts.append(f"*{'Preferred Payment Method'}*:") profilemessage = "\n".join(facts).join(['\n', '\n']) query.edit_message_text(text=message1 + profilemessage, parse_mode='Markdown', reply_markup=reply_markup) return EDIT_PROFILE
def get_user(target_id): response = vk.users.get(user_id = target_id) user = response[0] print(user) db.add_user( name = user['first_name'], surname = user['last_name'], vkID = user['id'] ) return user
def command_subscribe(message: telegram.Message, subcommand): chat_id = message.chat_id user = db.get_user(chat_id) if subcommand == []: if user == None: db.add_user(message.from_user.first_name, chat_id) message.reply_text("You're now subscribed!") else: message.reply_text("You're already subscribed")
def create(): if request.method == "POST": username = request.form["username"] password = request.form["password"] # Whether there is the same user name if db.get_user_by_name(username) is None: db.add_user(username, password) session["username"] = username return render_template("index.html", username=session["username"]) return render_template("create.html")
def finish_handler(bot: Bot, update: Update, user_data: dict): user_data[3] = update.message.text update.message.reply_text(f"Отлично! \n" f"1) {user_data[1]} \n" f"2) {user_data[2]} \n" f"3) {user_data[3]}") add_user(update.message.from_user['username'], user_data[1], user_data[2], user_data[3]) return ConversationHandler.END
def save(self): db.add_user({ "name": self.inputs["name"].get_text(), "last_name_1": self.inputs["last_name_1"].get_text(), "last_name_2": self.inputs["last_name_2"].get_text(), "b_day": self.inputs["b_day"].get_text(), "b_month": self.inputs["b_month"].get_text(), "b_year": self.inputs["b_year"].get_text(), "desc": self.inputs["desc"].get_text(), }) self.controller.show("user_list")
def login(): error = None if request.method == 'POST': username = request.form['username'] if username: db.add_user(username) session['user'] = username return redirect(url_for('admin.dashboard')) else: pass return render_template('admin/login.html', error=error)
def create_user(message): try: name, surname = message.text.split() except ValueError: bot.send_message(message.chat.id, f"Введи через пробіл, наприклад Іван Іванов") bot.register_next_step_handler(message, create_user) db.add_user([message.from_user.id, name, surname, message.chat.username]) kb = types.InlineKeyboardMarkup() kb.add(*course_kb()) bot.send_message(message.chat.id, f"Я тебе запам'ятав, {name}\n Який ти курс?", reply_markup=kb)
def received_password(update, context): password = update.message.text if password != secret.register_password: context.bot.send_message(chat_id=update.message.chat_id, text=messages.wrong_password) else: user = update.effective_user add_user(User(user.id, user.first_name, update.message.chat_id)) context.bot.send_message(chat_id=update.message.chat_id, text=messages.successful_registration.format( user.first_name)) return ConversationHandler.END
def register(): data = request.json email = data["email"] salt = bcrypt.gensalt() passwd = data["password"] uname = data["uname"] hashed = bcrypt.hashpw(str.encode(passwd), salt) hashpass = hashed ipadd = request.remote_addr db.add_user(email,uname,hashpass.decode("utf-8")) resp = Response("user registered", 201) resp.headers['Access-Control-Allow-Origin'] = '*' return resp
def welcome(message): """обработка команды /start""" user_id = message.chat.id if not db.get_user(user_id=user_id): log_msg = LOG_STR_USR + u', запросил регистрацию' logger.info(log_msg.format(user_id)) db.add_user(user_id=user_id) bot.send_message(user_id, "Привет, как дела?\nСписок доступных команд /help") else: logger.info(LOG_STR_USR_DO.format(user_id, '/start', COMMANDS['start'])) bot.send_message(user_id, "Привет, еще раз!")
def register(): if 'usern' in session: return redirect('/') if request.method == 'GET': return render_template('register.html',error="") else: usern = request.form['usern'] passw = request.form['passw'] if db.get_user(usern): return render_template('register.html', error='Username already exists') else: db.add_user(usern, passw) session['usern'] = usern return redirect('/')
def registration(id, nickname): c = db.connect() users = db.select_users(c) check = False for user in users: if user['id_user'] == id: check = True if check == False: db.add_user(c, id, nickname) bot.send_message(id, 'You register ' + nickname, reply_markup=kb.main_menu()) else: bot.send_message(id, 'Hello ' + nickname, reply_markup=kb.main_menu())
def get_myrelation(): db.add_queue(UID) fans = [] for fan in weibo.get_myfans(UID): fans.append(fan['uid']) db.add_user(fan['uid'], fan['nickname'], fan['sex'], fan['address'], fan['info'], fan['face']) db.add_relation(UID, fan['uid']) follow = [] for fo in weibo.get_myfollow(UID): follow.append(fo['uid']) db.add_user(fo['uid'], fo['nickname'], fo['sex'], fo['address'], fo['info'], fo['face']) db.add_relation(fo['uid'], UID) for friend in get_friends(fans, follow): db.add_queue(friend) db.finish_queue(UID)
def get_relation(uid): fans = [] for fan in weibo.get_hisfans(uid): fans.append(fan['uid']) print('User[%s] fan[%s]'%(uid, fan['uid'])) db.add_user(fan['uid'], fan['nickname'], fan['sex'], fan['address'], fan['info'], fan['face']) db.add_relation(uid, fan['uid']) follow = [] for fo in weibo.get_hisfollow(uid): follow.append(fo['uid']) print('User[%s] follow[%s]'%(uid, fo['uid'])) db.add_user(fo['uid'], fo['nickname'], fo['sex'], fo['address'], fo['info'], fo['face']) db.add_relation(fo['uid'], uid) for friend in get_friends(fans, follow): db.add_queue(friend) print('User[%s] fans[%s] follow[%s]'%(uid, len(fans), len(follow))) db.finish_queue(uid)
def facebook_login(signup): if request.method == 'POST': print "request.form = " print request.data # for debugging purposes if request.data: params = request.data.split() return db.add_user(params[0], params[1]) # else we use the normal form if request.form: fb_id = db.get_fbid(request.form['token']) if db.get_user_by_fbid(fb_id) is not None: return db.get_user_by_fbid(fb_id) return db.add_user(request.form['token'], request.form['device_token']) return db.add_user(request.form['token'], request.form['device_token']) else: return utils.to_app_json({"Error lol"})
def func_invite(self, invite_code=None): expire_days = 3 if invite_code: create_time = db.verify_invite_code(invite_code) if create_time and create_time + expire_days * 24 * 3600 > time.time(): db.delete_invite_code(invite_code) if not self._user: db.add_user(self._bare_jid) return u'Your account %s has been added, enjoy using TwiOtaku.' % self._bare_jid else: return u'Invite code is invalid or expired.' elif self._bare_jid in config.ADMIN_USERS: invite_code = generate_invite_code() create_time = int(time.time()) db.add_invite_code(invite_code, create_time) return u'You have generated a new invite code which is available for %d days: %s' % ( expire_days, invite_code)
def authorized(oauth_token): next_url = request.args.get('next') or url_for('index') if oauth_token is None: flash("Authorization failed.") return redirect(next_url) login = tracker.user_for_token(oauth_token) user_id = db.add_user(login, oauth_token) session['user_id'] = user_id return redirect(next_url)
def test3(): print "TEST: dropping all DBs" db.remove_all() print "TEST: adding users" NUM_USERS = 10 users = [str(i) for i in range(NUM_USERS)] add_user_result = reduce(lambda x,y: x and y, [db.add_user(i,"asdasdas","some name"+str(i),[]) for i in users]) if not add_user_result: print "TEST: FAIL: ADD USERS" print "TEST: adding blogs" blogs = ["http://thissongissick.com", "http://eqmusicblog.com",'http://gorillavsbear.net', 'http://potholesinmyblog.com', 'http://prettymuchamazing.com', 'http://disconaivete.com', 'http://doandroidsdance.com', 'http://www.npr.org/blogs/allsongs/','http://blogs.kcrw.com/musicnews/', "http://www.edmsauce.com"] # add sources for i in range(len(blogs)): if not add_blog_source(blogs[i],users[i]): print "TEST: FAIL: ADDING SOURCE TO USER" # add same sources to different users a bunch of times for j in range(7): random.shuffle(users) random.shuffle(blogs) for i in range(len(blogs)): if not add_blog_source(blogs[i],users[i]): print "TEST: FAIL: ADDING SOURCE TO USER" print "TEST: adding new user to test for no sources" db.add_user("some_person","asdasdas","some name",[]) print "TEST: getting recommendations" if not build_recommendations(): print "TEST: FAIL: Could not build recommendations" return "test3 failed" return "test3 passed"
def post(self): valid, data = db.add_user( self.get_argument("name"), self.get_argument("email"), self.get_argument("password") ) if valid: self.set_secure_cookie("session_id", str(data)) self.redirect("/login") else: self.render("signup.html", error_msg=data)
def register(): form = RegisterForm() user = None if form.validate_on_submit(): user = db.add_user( username=form.username.data, password=bcrypt.generate_password_hash(form.password.data), email=form.email.data ) login_user(user) return redirect(url_for('login')) return render_template('register.html', form=form)
def home_newuser(): print "=====================" print "--->NEW USER MENU<---" print "=====================" newfname = raw_input("NEW USER FIRST NAME: ") if newfname == ":EXIT": home() else: pass newlname = raw_input("NEW USER LAST NAME: ") today = raw_input("MARK PRESENT FOR TODAY [Y/N] ") if today in ("Y","y"): db.add_user(newfname,newlname,"1") print "USER ADDED... PRESS [ENTER] TO GOTO HOMESCREEN" raw_input() elif today == ":EXIT": home() else: db.add_user(newfname,newlname,"0") print "USER ADDED... PRESS [ENTER] TO GOTO HOMESCREEN" raw_input() home()
def register(req): ''' Process register request. A successful register includes inserting a record to user table, initializing a session record and setting a cookie. ''' if not req.has_key('username'): util.msg_redirect('/static/register.html', 'username must not empty') return if not req.has_key('password'): util.msg_redirect('/static/register.html', 'password must not empty') return username = req.get('username').value password = req.get('password').value username = username.strip() password = password.strip() if not util.check_username_format(username): util.msg_redirect('/static/register.html', 'username format error') return if not check_username_occupied(username): util.msg_redirect('/static/register.html', 'username occupied') return if not util.check_password_format(password): util.msg_redirect('/static/register.html', 'password format error') return salt = os.urandom(64) password = hashlib.sha256(salt + password).hexdigest() success = db.add_user(username, password, salt) if success: sid = hashlib.md5(str(random.random())).hexdigest() session.add_session(username, sid) data = {} data['sid'] = sid data['cur_user'] = username util.set_cookie(data) util.redirect('/info') return else: util.msg_redirect('/static/register.html', 'register failure')
def rpc_register(self,user,passw,passtwo,email): if passw==passtwo: print user,passw,passtwo,email return db.add_user(user,passw,email)
def create_user(): user = User(id=User.make_id()) db.add_user(user) return user
if not userlist["name"] or not userlist["password"]: errmsg = "username and password is not empty" # return render_template("register.html",content=content) return json.dumps({'code':'1','errmsg':errmsg}) if userlist["password"] != userlist["re_password"]: errmsg="password is error" # return render_template("register.html",content=content) return json.dumps({'code':'1','errmsg':errmsg}) fields = ["name","name_cn","password","mobile","email","role","status"] values = [ '%s'%userlist[x] for x in fields] print values #[u'weixiaobao', u'weixiaobao', u'123', u'123123', u'123113', u'ops', u'0'] userdict = dict([(k,values[i]) for i,k in enumerate(fields)]) print userdict #{'status': u'0', 'name': u'weixiaobao', 'mobile': u'123123', 'name_cn': u'weixiaobao', 'role': u'ops', 'password': u'123', 'email': u'123113'} add_user(userdict) # return redirect("/login") return json.dumps({'code':'0','result':"register sucess"}) @app.route("/deluser") def deluser(): if not session.get('name'): return redirect('/login') #前端get请求,逻辑端通过request.args.get获取参数 uid=request.args.get("uid") print uid del_user(uid) return redirect("/userlist")
def get_user_friends(): if request.method == 'POST': return db.add_user(request.data)
def register_user(name, pubkey): if db.get_user(name) is not None: return False db.add_user(name, pubkey) return True
def add_user(): if request.method == 'POST': user = request.form['user'] db.add_user(user) return Response(status=200)
def add_user(): username = request.args.get('username') password = request.args.get('password') return db.add_user(username, password)