def add_user(obj_response, user_main_add_form): ''' Let WTForm perform the form validations ''' # pass the dictionary to the form form = UserMaintenanceForm(data=user_main_add_form) # validate the form form.validate() # run action to perform if not form.errors.items(): if check_user := User.query.filter_by( username=form.username.data).first(): flash(u'Username is aready taken!', 'danger') else: # instantiate new_user = User() # Copies matching attributes from form onto user form.populate_obj(new_user) # genereate new uuid new_user.uuid = str(uuid.uuid4()) new_user.hash_password(password=new_user.password) # save changes to db db.session.add(new_user) db.session.commit() form = UserMaintenanceForm() flash( u'<a href="javascript:;" onclick="javascript:UpdateUser(' + "'" + str(new_user.uuid) + "'" + ');"><strong>New User</strong></a> has been saved! The form is now back to add mode.', 'success')
def set(): click.echo('设定管理员……') admin_user = User(email='*****@*****.**', name='管理员', username='******') admin_user.set_password('admin') admin_user.set_role_by_role_name('Administrator') ''' click.echo('设定用户……') normal_user = User(email='*****@*****.**', name='用户', username='******') # 若想 role_id=4,则需注释掉 models/user.py self.set_role_by_role_name() normal_user.set_password('user') click.echo('设定审核者一……') ins_user = User(email='*****@*****.**', name='审核者一', username='******') ins_user.set_password('ins') ins_user.set_role_by_role_name('Inspector') click.echo('设定审核者二……') mod_user = User(email='*****@*****.**', name='审核者二', username='******') mod_user.set_password('mod') mod_user.set_role_by_role_name('Moderator') db.session.add_all([admin_user, normal_user, ins_user, mod_user]) ''' db.session.add(admin_user) db.session.commit() click.echo('设定完成!')
def db_populate_users(): """Add test users to db""" test_user_dicts = ( { "username": "******", "password": "******", "name": "Main Tester" }, { "username": "******", "password": "******" }, ) for user_dict in test_user_dicts: password_hash = bcrypt.hashpw(user_dict["password"].encode("utf-8"), bcrypt.gensalt(8)) data = user_dict.copy() data.pop("password") data["password_hash"] = password_hash user = User(**data) db.session.add(user) db.session.commit() return test_user_dicts
def setUp(self): app = create_app('testing') self.context = app.test_request_context() self.context.push() self.client = app.test_client() self.runner = app.test_cli_runner() db.create_all() Role.init_role() admin_user = User(email='*****@*****.**', name='管理员', username='******') admin_user.set_password('150402207') normal_user = User(email='*****@*****.**', name='远哥制造', username='******') normal_user.set_password('yuangezhizao') db.session.add_all([admin_user, normal_user]) db.session.commit()
def setup_user(session, email=None, password='******', name='Testing User'): """Set up a mock account""" if email is None: email = random_email() user = User(name=name, email=email, password=password) session.add(user) session.commit() return user
def test_user_create_errors(db_populate_users, users_in_db_getter): """Test that invalid users are not created""" users_before = users_in_db_getter() with pytest.raises(IntegrityError): duplicate_username = User(username=users_before[0].username, password_hash="passwordhash") duplicate_username.save() with pytest.raises(IntegrityError): missing_username = User(password_hash="passwordhash") missing_username.save() with pytest.raises(IntegrityError): missing_password_hash = User(username="******") missing_password_hash.save() users_after = users_in_db_getter() assert len(users_after) == len(users_before)
def subscription(): con=None if request.method=='POST': if request.form['submit']=="S'abonner": try : register_user=False id="usr"+time_number() name= request.form.get('name') last_name=request.form.get('last_name') email=request.form.get('email') tel=request.form.get('phone') user_name=request.form.get('user_name') password=request.form.get('password') user_type=request.form.get('user_type') user=User( name=name, last_name=last_name, email=email, tel=tel, id=id, user_name=user_name, password=password, user_type=user_type) except Exception as error: print(error) abort(400) try: con=postgres_connetion( host_postgres, db_name_postgres, db_user_postgres, db_password_postgres) cur=con.cursor() create_user(user,con,cur) register_user=True except (Exception, psycopg2.Error) as error: print(error) if isinstance(error,UniqueViolation): flash('Les informations choisies existent déjà') else: abort(422) finally: if con is not None: cur.close() con.close() if register_user==True: flash('Utilisateur répertorié avec succès') return render_template("user/subscription_user.html")
def create_user(*, username: str, password_hash: str, name: Optional[str] = None) -> User: """Create and save an user into database, then return the user""" user = get_user_by_username(username) if user: raise BadRequestError("Username already exists") user = User(username=username, password_hash=password_hash, name=name) user.save() return user
def register_new_user(**kwargs): args = kwargs['args'] email = args['email'] if User.get_user_by_email(email) is not None: raise Error(StatusCode.BAD_REQUEST, 'This email has been registered before') user = User(**args, status=UserStatus.ACTIVE, online=0) db.session.add(user) db.session.commit() return jsonify({ 'message': 'Your account was created successfully', 'data': UserSchema().dump(user).data }), 200
def test_user_create(db_populate_users, users_in_db_getter): """Test that valid users are created correctly""" users_before = users_in_db_getter() new_user = User(username="******", password_hash="abcde12345") new_user.save() users_after = users_in_db_getter() new_user_in_db = [ user for user in users_after if user not in users_before ][0] assert len(users_after) == len(users_before) + 1 assert new_user_in_db.username == new_user.username assert new_user_in_db.password_hash == new_user.password_hash assert new_user_in_db.name == new_user.name
def signup(**kwargs): email = kwargs.get('email', None) password = kwargs.get('password', None) if User.exists(email): return ERROR_USER_EMAIL_EXISTS.get_response() user_info = User(**kwargs) db.session.add(user_info) db.session.commit() try: email_sender.sendmail(user_info.email, SignupCheck(user_info)) except Exception as e: return ERROR_SEND_MAIL.get_response() return SUCCESS_SIGNUP.get_response()
def setUp(self): app = create_app('testing') self.context = app.test_request_context() self.context.push() self.client = app.test_client() self.runner = app.test_cli_runner() db.create_all() Role.init_roles() Depart.init_departs() Task.init_tasks() admin_user = User(email='*****@*****.**', name='管理员', username='******') admin_user.set_password('admin') admin_user.set_role_by_role_name('Administrator') normal_user = User(email='*****@*****.**', name='用户', username='******') normal_user.set_password('user') ins_user = User(email='*****@*****.**', name='审核者一', username='******') ins_user.set_password('ins') admin_user.set_role_by_role_name('Inspector') mod_user = User(email='*****@*****.**', name='审核者二', username='******') mod_user.set_password('mod') admin_user.set_role_by_role_name('Moderator') db.session.add_all([admin_user, normal_user, ins_user, mod_user]) db.session.commit()
def register(): if request.method == 'POST': depart_name = request.form.get('depart_name') role_name = request.form.get('role_name') email = request.form.get('email') about_me = request.form.get('about_me') username = request.form.get('username') name = request.form.get('name') password = request.form.get('password') user = User(email=email, username=username, name=name, about_me=about_me) user.set_password(password) user.set_role_by_role_name(role_name) user.set_depart_by_depart_name(depart_name) db.session.add(user) db.session.commit() flash(f'新用户注册成功,邮箱:{email},用户名:{username},昵称:{name}', 'info') return redirect(request.url) departs_list = Depart.query.all() # TODO:这咋分页? return render_template('admin/register.html', departs_list=departs_list)
def handle_message(event): if event.type == "message" and event.message.type == "text": if event.message.text == "show": messages = [] contents = db.session.query(User).filter_by(user_id=event.source.user_id).all() for content in contents: messages.append(TextSendMessage(content.content)) line_bot_api.reply_message(event.reply_token, messages[-5:]) elif event.message.text == "画像": main_image_path = "static/images/hina.jpg" preview_image_path = "static/images/hina.jpg" image_message = ImageSendMessage( original_content_url=f"https://tetsupy.herokuapp.com/{main_image_path}", preview_image_url=f"https://tetsupy.herokuapp.com/{preview_image_path}", ) line_bot_api.reply_message(event.reply_token, image_message) elif event.message.text == "動画": main_video_path = "static/videos/hina.MP4" preview_video_path = "static/videos/hina.MP4" video_message = VideoSendMessage( original_content_url=f"https://tetsupy.herokuapp.com/{main_video_path}", preview_image_url=f"https://tetsupy.herokuapp.com/{preview_video_path}", ) line_bot_api.reply_message(event.reply_token, video_message) else: #データベースに追加 user = User(event.source.user_id, event.message.text) db.session.add(user) db.session.commit() line_bot_api.reply_message(event.reply_token,TextSendMessage("記憶しました"))
from main.models.company import Company from main.models.sequence import Sequence import uuid from main.models.loan import Loan from main.models.loan_detail import LoanDetail from main.models.contribution import Contribution from main.models.member import Member from main.models.borrower import Borrower app.config.from_object('config.DevConfig') get_user = User.query.filter_by(username='******').first() if not get_user: dev_user = User(username='******', password='******', display_name='Developer') dev_user.uuid = str(uuid.uuid4()) dev_user.hash_password(password=dev_user.password) db.session.add(dev_user) db.session.commit() get_company = Company.query.first() if not get_company: company = Company(company_name='Hello Cooperative', address='Novaliches Quezon City', phone='1234-123', mobile='09321234567', total_fund=0, available_fund=0, lended_fund=0, total_profit=0,
def set_user_info(stu_id, stu_name): if not is_user_exists(stu_id, stu_name): user_mod = User(stu_id=stu_id, stu_name=stu_name) user_mod.save() return True