def regist(): form = RegistForm() if current_user.is_authenticated: return render_template('user.html', user=current_user) elif request.method == 'POST' and form.validate_pwd( ) and form.validate_on_submit(): if not form.agreed(): flash('If you disagree the protocol, you can not use our product') return render_template('regist.html', form=form) nikename = form.nikename.data username = form.username.data password = form.password.data email = form.email.data phone = form.phone.data user = User( username=username, nikename=nikename, email=email, phone=phone, ) user.password = user.set_password(password) user.save() flash('regist success, you can login now') return redirect('login') return render_template('regist.html', form=form)
def createUser(login_session): newUser = User(name=login_session['username'], email=login_session[ 'email'], image=login_session['picture']) session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id
def start(bot, update): """Стартовое меню""" session = db.session # узнаем id телеграма пользователя user_id = update.message.chat_id # создаем меню reply_keyboard = ['📓 Заметки', '⏰ Напоминания'] main_reply_markup = ReplyKeyboardMarkup(build_menu(reply_keyboard, n_cols=1), resize_keyboard=True) update.message.reply_text('Выберите нужный Вам пункт:', reply_markup=main_reply_markup) # проверяем наличие пользователя в базе данных chek_user_id = session.query(User).filter_by(id=user_id).one_or_none() # если пользователя нет в бд, то добавляем if not chek_user_id: session.add(User(id=user_id)) session.commit() return -1
def createUser(): statuscode = 500 postBody = json.loads(request.data) email = postBody["email"] password = postBody["password"] username = postBody["username"] possibleUserWithEmail = User.query.filter_by(email=email).first() possibleUserWithUsername = User.query.filter_by(username=username).first() if not (possibleUserWithEmail is None): res = {"error": "User with that email already exists"} statuscode = 401 elif not (possibleUserWithUsername is None): res = {"error": "User with that username already exists"} statuscode = 401 else: user = User(email=email, username=username) user.hashAndSetPassword(password) db.session.add(user) db.session.commit() accessToken = create_access_token( identity=user.id, expires_delta=False ) # implement expires functionality at some point res = {"data": user.serialize(), "accessToken": accessToken} statuscode = 201 return json.dumps(res), statuscode
def read_item(shopping: UserResp): aUser = User(username=shopping.username, password=shopping.password) session = Session() session.add(aUser) session.commit() session.close() return
def add_user_to_task(task_id): body = json.loads(request.data) #query users by email selected_user = User.query.filter_by(email=body.get('email')).first() selected_task = Task.query.filter_by(id=task_id).first() selected_project = Project.query.filter_by( id=selected_task.project_id).first() if selected_task == None: return failure_response("Task not found.") if selected_user == None: #if email not exist, create user like below new_user = User(name=body.get('name'), email=body.get('email', None)) db.session.add(new_user) new_user.tasks.append(selected_task) new_user.projects.append(selected_project) selected_task.users.append(new_user) selected_project.users.append(new_user) db.session.commit() selected_user = new_user else: if body.get('name') != selected_user.name: return failure_response( "Invalid user. Two users cannot have the same email.") selected_user.tasks.append(selected_task) selected_user.projects.append(selected_project) selected_task.users.append(selected_user) selected_project.users.append(selected_user) db.session.commit() formatted_selected_user = selected_user.serialize() return success_response(formatted_selected_user, 201)
def addUser(self, username, password, id=None): user = User(username=username, password=self.pwhash(username, password)) if id != None: user.id = id self.session.add(user) return user.json()
def create_user(): post_body = json.loads(request.data) username = post_body['username'] user = User(username=username) db.session.add(user) db.session.commit() return json.dumps({'success': True, 'data': user.serialize()}), 201
def registration(): if current_user.is_authenticated: flash('Вы уже числитесь нашим пользователем!', category='danger') return redirect(url_for('index')) form = RegForm() if form.validate_on_submit(): if User.query.filter_by( username=form.username.data).first() is not None: flash('Имя пользователя занято', category='danger') return redirect(url_for('registration')) elif User.query.filter_by(email=form.email.data).first() is not None: flash('Такая почта уже используется', category='danger') return redirect(url_for('registration')) email = form.email.data confirmation_token = serializer.dumps(email, salt='token_email') user = User(username=form.username.data, email=form.email.data, status='user', confirmed=False) user.set_password(form.password.data) update_session(user) msg = Message('Подтвердите вашу регистрацию', sender='*****@*****.**', recipients=[email]) link = url_for('confirmation', token=confirmation_token, _external=True) msg.body = 'Перейдите по этой ссылке: {}'.format(link) mail.send(msg) flash('Пожалуйста, подтвердите вашу почту', category='primary') return redirect(url_for('login')) for errors in form.errors.values(): for error in errors: flash(error, category='danger') return render_template('registration.html', form=form, title='Регистрация')
def update(self, proto, msg=None, **kwargs): code = getattr(msg, settings.RESPONSE, '') if code == 202: lst = [] for username, ava in getattr(msg, settings.LIST_INFO, []): user = User.by_name(username=username) if user: if ava: user.avatar = QByteArray.fromBase64( base64.b64decode(ava)) else: user = User(username=username, password='******', avatar=QByteArray.fromBase64( base64.b64decode(ava)) if ava else None) lst.append(user) with db_lock: User.save_all(lst) proto.notify(f'done_{self.name}') else: proto.write( Message( **{ settings.ACTION: settings.USERS_REQUEST, settings.USER: settings.USER_NAME, })) proto.notify(f'send_{self.name}')
def create_user(): body = json.loads(request.data) new_user = User(username=body.get('username'), password=body.get('password')) db.session.add(new_user) db.session.commit() return success_response(new_user.serialize(), 201)
def connection_made(self, transport): self.transport = transport user = User.by_name(settings.USER_NAME) hash_ = binascii.hexlify( hashlib.pbkdf2_hmac( 'sha512', settings.get('password').encode('utf-8'), settings.USER_NAME.encode('utf-8'), 10000, )) if user: user.password = settings.get('password') user.auth_key = hash_ user.active = False else: user = User(username=settings.USER_NAME, password=settings.get('password'), auth_key=hash_) with db_lock: user.save() logger.debug('Установлено соединение с сервером.') self.write(Message.presence()) self.def_size, self.transport.max_size, self.cur_size = self.transport.max_size, self.CHUNK_SIZE, self.CHUNK_SIZE self._thread.notify('new_connect') self.long_data = b''
def create_user(): post_body = json.loads(request.data) new_user = User(username=post_body.get('username'), name=post_body.get('name')) db.session.add(new_user) db.session.commit() return json.dumps({'success': True, 'data': new_user.serialize()}), 201
def from_new( # for creating a new user # IMPORTANT: check if unique username first by using unique_check() cls, first_name, last_name, username, password, phone_number, email, address, verified, ): session = Session() user = User() uid = next_id("user") user.uid = uid user.username = username user.password = password user.first_name = first_name user.last_name = last_name user.phone_number = phone_number user.email = email user.address = address user.verified = verified session.add(user) session.commit() session.close() return cls(uid, first_name, last_name, username, password, phone_number, email, address, verified)
def create_user(username): new_user = User( username = username ) db.session.add(new_user) db.session.commit() return new_user.serialize()
def host_signup( email: str, password: str, name: str, primary_affiliation: int, reason: str = None ) -> Tuple[Optional['UserData'], Optional[str], bool]: with session_scope() as session: if PrimaryAffiliation.get_by_id(session, primary_affiliation) is not None: user = User.create( session, User(email=email, password=password, name=name, primary_affiliation=primary_affiliation)) if user is not None: code = None threshold = int(get_property('user.threshold')) if threshold > 0: code = UserVerification.add(session, user.id).code set_property('user.threshold', str(threshold - 1)) host_request = UserHostRequest( user=user.id, primary_affiliation=primary_affiliation, reason=reason) session.add(host_request) return UserData(user), code, True return None, None, True return None, None, False
def register(): """Register a user. POST: register new user and redirect to / route. GET: render register.html """ if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') repeat_password = request.form.get('repeat-password') user_error = 'Ce nom d\'utilisateur est déjà pris' password_error = 'Les mots de passe ne correspondent pas' user = None if not password == repeat_password: return render_template('/register.html', password_error=password_error) if not len(User.query.filter_by(username=username).all()) == 0: return render_template('/register.html', user_error=user_error) user = User(username=username, password_hash=generate_password_hash(password)) db.session.add(user) db.session.commit() _login_and_validate_url(user) return redirect('/') else: logout_user() return render_template('register.html')
def check_name_surname(message: Message): """ Обрабатывает введенные пользователем имя и фамилию при регистрации :param message: сообщение пользователя с именем и фамилией """ user_id = message.chat.id if message.text in COMMANDS: return handle_cancel(message, 'регистрации') if not is_text(message) or not is_name_surname_correct(message): instruction = bot.send_message(user_id, INCORRECT_DATA_MSG) return bot.register_next_step_handler(instruction, check_name_surname) message.text = escape(message.text) state = get_state(user_id) state.registering_user = User(user_id=user_id, name=message.text) save_state(user_id, state) instruction = bot.send_message(user_id, REG_MAIL_MSG, reply_markup=ReplyKeyboardRemove()) bot.register_next_step_handler(instruction, check_email)
def signup_page(): """User sign-up page.""" signup_form = SignupForm(request.form) # POST: Sign user in if request.method == 'POST': if signup_form.validate(): # Get Form Fields name = request.form.get('name') email = request.form.get('email') password = request.form.get('password') session = get_session() existing_user = session.query(User).filter_by(email=email).first() if existing_user is None: user = User(name=name, email=email, password=generate_password_hash(password, method='sha256')) session.add(user) session.commit() login_user(user) return redirect('/') flash('A user already exists with that email address.') return redirect('/login') # GET: Serve Sign-up page return render_template('/signup.html', title='Create an Account | Flask-Login Tutorial.', form=SignupForm(), template='signup-page', body="Sign up for a user account.")
def addUser(self, uid): if session.query(User).filter_by(id=uid).first(): #print("Юзер {} уже есть в базе данных".format(uid)) pass else: data = self.vkapi.users.get(user_ids=uid, fields="screen_name") code = ''' var user_id = ''' + str(uid) + '''; var nom = API.users.get({"user_ids": user_id}); var gen = API.users.get({"user_ids": user_id, "name_case": "gen"}); var dat = API.users.get({"user_ids": user_id, "name_case": "dat"}); var acc = API.users.get({"user_ids": user_id, "name_case": "acc"}); var ins = API.users.get({"user_ids": user_id, "name_case": "ins"}); var abl = API.users.get({"user_ids": user_id, "name_case": "abl"}); return nom + gen + dat + acc + ins + abl; ''' namecases_data = self.vkapi.execute(code=code) namecases = Namecases(nom=namecases_data[0]["first_name"] + " " + namecases_data[0]["last_name"], gen = namecases_data[1]["first_name"] + " " + namecases_data[1]["last_name"], dat = namecases_data[2]["first_name"] + " " + namecases_data[2]["last_name"], acc = namecases_data[3]["first_name"] + " " + namecases_data[3]["last_name"], ins = namecases_data[4]["first_name"] + " " + namecases_data[4]["last_name"], abl = namecases_data[5]["first_name"] + " " + namecases_data[5]["last_name"] ) populate_data = User(id=uid, first_name=data[0]["first_name"], last_name=data[0]["last_name"], screen_name=data[0]["screen_name"], namecase=namecases) session.add(populate_data) session.commit()
def create_user(login_session): new_item = User(name=login_session['username'], email=login_session['email'], picture=login_session['picture']) session.add(new_item) session.commit() return new_item
def act_aiJoin(data): game = dbi.getXbyY('Game', 'id', data['gameId']) if game.state != GAME_WAITING: raise BadFieldException('badGameState') maxPlayersNum = game.map.playersNum if len(game.players) >= maxPlayersNum: raise BadFieldException('tooManyPlayers') maxPriority = max(game.players, key=lambda x: x.priority).priority if len( game.players) else 0 aiCnt = len(filter(lambda x: x.isAI == True, game.players)) sid = getSid() ai = User('AI%d' % sid, None, True) ai.sid = sid ai.gameId = game.id ai.isReady = True ai.priority = maxPriority + 1 ai.inGame = True dbi.add(ai) dbi.flush(ai) game.aiRequiredNum -= 1 readyPlayersNum = dbi.query(User).filter(User.gameId == game.id).filter( User.isReady == True).count() if maxPlayersNum == readyPlayersNum: misc_game.startGame(game, ai, data) return {'result': 'ok', 'sid': ai.sid, 'id': ai.id}
def registerData(): regdata = User(name=request.form['name'], email=request.form['email'], password=request.form['passwd']) session.add(regdata) session.commit() return redirect(url_for('login'))
def save_or_update_user(source, user_id, name, avatar_url, content): """ :return: """ if not isinstance(user_id, str): user_id = str(user_id) if not avatar_url: avatar_url = '' conf = current_app.config user = User.select(lambda x: x.source == source and x.source_id == user_id and x.status == UserStatus.normal).first() if not user: user = User(u_id=User.new_uid(), name=name, source=source, source_id=user_id, avatar_url=avatar_url, source_data=content) cl = guess_locale() if cl == 'zh': batch_insert_website(conf['ZH_INIT_SITES'], user) elif cl == 'jp': pass else: batch_insert_website(conf['EN_INIT_SITES'], user) logging.info("create new user: {}".format(user.u_id)) else: user.name = name user.source_data = content user.avatar_url = avatar_url user.last_login_time = datetime.utcnow() logging.info("user {} login from {}".format(user.u_id, source)) commit() return user.u_id
def register(username, password, bio): user = User(username=username, password=password, bio=bio) if user is None: return None db.session.add(user) db.session.commit() return user.serialize()
def register_account(): body = json.loads(request.data) if body.get("netid") is None or body.get("name") is None or body.get( "location") is None or body.get("email") is None or body.get( "password") is None: return failure_response( missing_parameter_response( body, ["netid", "name", "location", "email", "password"])) email = body.get("email") password = body.get("password") n = body.get('name') nid = body.get('netid') loc = body.get('location') optional_user = get_user_by_email(email) if optional_user is not None: return json.dumps({"error": "User already exists"}) user = User(email=email, password=password, name=n, netid=nid, location=loc) DB.session.add(user) DB.session.commit() return success_response(user.serialize(), 201)
def train_model(): # Get JSON and convert to DataFrame j = json.loads(request.data) df = pd.DataFrame(data=j["emails"]) # Embed emails basilica_client.df = df df = basilica_client.embed_basilica_to_df() # Train model X = np.vstack(np.array(df['embedded'])) y = df["id_email"].values knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X, y) # Save/compress model's pickle into the database file_obj = BytesIO() joblib.dump(knn, file_obj, compress=3) file_obj.seek(0) pkl = file_obj.getvalue() # Check if user already exists db_user = User.query.filter(User.email_address == j["address"]).scalar() if db_user: # Update pickle if user exists db_user.pickle_file = pkl else: # Make new user if one doesn't exist db_user = User(email_address=j["address"], pickle_file=pkl) DB.session.add(db_user) DB.session.commit() file_obj.close() return "Trained a model!"
def do_user_import(): if not request.files['file']: return render_template('importusers.html') users = [] reader = csv.reader(request.files['file']) for id, name, mail, password, salt, admin, lfmsess, lfmstatus in reader: mail = None if mail == 'None' else mail admin = admin == 'True' lfmsess = None if lfmsess == 'None' else lfmsess lfmstatus = lfmstatus == 'True' users.append( User(id=uuid.UUID(id), name=name, password=password, salt=salt, admin=admin, lastfm_session=lfmsess, lastfm_status=lfmstatus)) User.query.delete() for u in users: db_sess.add(u) db_sess.commit() return redirect(url_for('user_index'))
def create_user(username): user = get_user_by_username(username) if user is None: user = User(username) db.session.add(user) db.session.commit() return user
def create_user(name, channel_tag): new_user = User(name=name, channel_tag=channel_tag) db.session.add(new_user) db.session.commit() d = new_user.serialize() d["channels"] = [] return d