def user(db): """ Creates a user without a profile. """ from my_app.models import User user = User(firstname="Person", lastname='One', email='*****@*****.**') user.set_password('password1') db.session.add(user) db.session.commit() return user
def get(self, id=None): if id: try: user = User.objects(id=id).first() except MongoValidationError as error: abort(400, f"{error}") return UserSchema().dump(user) else: users = User.objects() return UserSchema().dump(users, many=True)
def register(): if current_user.is_authenticated: return redirect(url_for("main.index")) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash("Successfully Registerd...") return redirect(url_for("auth.login")) return render_template("register.html", form=form)
def upload_to_db(cls): # external api can generate max 10 users. To generate 100 users, i had to make a loop for _ in range(10): test_data = cls._take_data_from_external_api() for user in test_data: User(name=fake.name_male(), **user).save() time.sleep(0.5)
def user_with_profile(db): """ Creates a user with a profile with a username and bio """ from my_app.models import User, Profile user = User(firstname='Person', lastname='Three', email='*****@*****.**') user.profile = Profile(username='******', bio="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ac tempor metus. " "Aenean mattis, tortor fringilla iaculis pharetra, dui justo imperdiet turpis, " "at faucibus risus eros vitae dui. Nam finibus, nibh eu imperdiet feugiat, nisl lacus " "porta tellus, a tincidunt nibh enim in urna. Aliquam commodo volutpat ligula at " "tempor. In risus mauris, commodo id mi non, feugiat convallis ex. Nam non odio dolor. " "Cras egestas mollis feugiat. Morbi ornare laoreet varius. Pellentesque fringilla " "convallis risus, sit amet laoreet metus interdum et.") user.set_password('password3') db.session.add(user) db.session.commit() return user
def put(self, id): try: data = UserSchema().load(request.get_json()) update_user(data, id) # method to update fields except (MarshmallowValidationError, MongoValidationError) as error: abort(400, f"{error}") new_user = User.objects(id=id) return UserSchema().dump(new_user, many=True)
def signup(): form = SignupForm(request.form) if form.validate_on_submit(): user = User(firstname=form.first_name.data, lastname=form.last_name.data, email=form.email.data) user.set_password(form.password.data) try: db.session.add(user) db.session.commit() flash( f"Hello, {user.firstname} {user.lastname}. You are signed up.") except IntegrityError: db.session.rollback() flash(f'Error, unable to register {form.email.data}. ', 'error') return redirect(url_for('auth.signup')) return redirect(url_for('main.index')) return render_template('signup.html', title='Sign Up', form=form)
def _add_root(): root_pwd = UserService.generate_pwd('123456') root_user = User(username='******', password=root_pwd, email='*****@*****.**', role=UserRole.ADMIN) tr = TeamUserRelationship(isLeader=True) tr.team = Team(title='root_team') root_user.teams.append(tr) db.session.add(root_user) db.session.commit() UserService(db).add_user_dir(root_user.id)
def reset_password(token): if current_user.is_authenticated: return redirect(url_for('main.index')) user = User.verify_reset_password_token(token) if not user: return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): user.set_password(form.password.data) db.session.commit() flash('Your password has been reset.') return redirect(url_for('auth.login')) return render_template('reset_password.html', form=form)
def setUp(self): db.session.commit() db.drop_all() db.create_all() # Add the local authority data to the database (this is a workaround you don't need this for your coursework!) csv_file = Path(__file__).parent.parent.joinpath( "data/household_recycling.csv") df = pd.read_csv(csv_file, usecols=['Code', 'Area']) df.drop_duplicates(inplace=True) df.set_index('Code', inplace=True) df.to_sql('area', db.engine, if_exists='replace') # Add a user and profile to the database u = User(firstname='TestFirstname1', lastname='TestLastname1', email='*****@*****.**') u.set_password('test1') p = Profile(username='******', bio='Something about test1.', area='Barnet', user_id=u.id) u.profiles.append(p) db.session.add(u) db.session.commit()
def test_follow(self): u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') db.session.add(u1) db.session.add(u2) db.session.commit() self.assertEqual(u1.followed.all(), []) self.assertEqual(u1.followers.all(), []) u1.follow(u2) db.session.commit() self.assertTrue(u1.is_following(u2)) self.assertEqual(u1.followed.count(), 1) self.assertEqual(u1.followed.first().username, 'susan') self.assertEqual(u2.followers.count(), 1) self.assertEqual(u2.followers.first().username, 'john') u1.unfollow(u2) db.session.commit() self.assertFalse(u1.is_following(u2)) self.assertEqual(u1.followed.count(), 0) self.assertEqual(u2.followers.count(), 0)
def reset_token(token): if current_user.is_authenticated: return redirect(url_for('main.home')) user = User.verify_reset_token(token) if user is None: flash('That is an invalid or expired token') return redirect(url_for('main.reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() flash('Your password has been updated! You are now able to log in') return redirect(url_for('main.login')) return render_template('reset_token.html', title='Reset Password', form=form)
def post(self): args = register_parser.parse_args() username = args.get('username') password = UserService.generate_pwd(args.get('password')) email = args.get('email') if exists_query(User.query.filter_by(username=username)): return "ERROR_DUPLICATE_USER_NAME" user = User( username=username, password=password, email=email, pending=0, ) db.session.add(user) db.session.commit() new_user = UserService(db).get_user_by_name(username) UserService(db).add_user_dir(new_user.id) login_user(new_user, remember=False) return redirect(url_for('Auth.login'))
def post(self): user = request.json['user'] surname = request.json['Surname'] email = request.json['Email'] firstname = request.json['Firstname'] password = request.json['Password'] #To confirm if all the required info is submitted if not user or not surname or not email or not firstname or not password: return jsonify({"message": "Missing information about the user"}) else: existing_user = User.query.filter_by(user=user).first() existing_email = User.query.filter_by(email=email).first() if existing_email is None and existing_user is None: #New user to be registered newUser = User(user, surname, firstname, email, password) db.session.add(newUser) db.session.commit() return jsonify({'message': 'User created'}) else: return jsonify({'message': "User exists"})
def add_user(): if request.method == "POST": info = request.get_json() statusGood = False if info['first'] != "" and info['last'] != "" and info[ 'dob'] != "" and info['county'] != "": statusGood = check_status.check_status(first_initial=info['first'], last_name=info['last'], DOB=info['dob'], county=info['county']) if statusGood: new_user = User(first=info['first'], last=info['last'], dob=info['dob'], county=info['county'], email=info['email']) db.session.add(new_user) db.session.commit() return "yes" else: return "no"
def test_follow_posts(self): # create four users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create four posts now = datetime.utcnow() p1 = Post(body="post from john", author=u1, timestamp=now + timedelta(seconds=1)) p2 = Post(body="post from susan", author=u2, timestamp=now + timedelta(seconds=4)) p3 = Post(body="post from mary", author=u3, timestamp=now + timedelta(seconds=3)) p4 = Post(body="post from david", author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def create_app(config_classname): """ Initialise and configure the Flask application. :type config_classname: Specifies the configuration class :rtype: Returns a configured Flask object """ app = Flask(__name__) app.config.from_object(config_classname) db.init_app(app) login_manager.login_view = 'auth.login' login_manager.init_app(app) #csrf.init_app(app) configure_uploads(app, photos) with app.app_context(): from my_app.models import User, Profile, Area db.create_all() # Add the local authority data to the database (this is a workaround you don't need this for your coursework!) csv_file = Path(__file__).parent.parent.joinpath( "data/household_recycling.csv") df = pd.read_csv(csv_file, usecols=['Code', 'Area']) df.drop_duplicates(inplace=True) df.set_index('Code', inplace=True) df.to_sql('area', db.engine, if_exists='replace') # Add sample data for the REST API exercise u = User.query.first() if u is None: p1 = Profile(username='******', bio='something about me', area='Barnet') p2 = Profile(username='******', bio='something interesting', area='Barnet') u1 = User(firstname='Jo', lastname='Bloggs', email='*****@*****.**', profiles=[p1]) u2 = User(firstname='Fred', lastname='Smith', email='*****@*****.**', profiles=[p2]) u3 = User(firstname='Santa', lastname='Claus', email='*****@*****.**') u4 = User(firstname='Robert', lastname='Plant', email='*****@*****.**') u1.set_password('test') u2.set_password('test') u3.set_password('test') u4.set_password('test') db.session.add_all([u1, u2, u3, u4]) db.session.commit() from dash_app.dash import init_dashboard app = init_dashboard(app) from my_app.main.routes import main_bp app.register_blueprint(main_bp) from my_app.community.routes import community_bp app.register_blueprint(community_bp) from my_app.auth.routes import auth_bp app.register_blueprint(auth_bp) from my_app.api.routes import api_bp app.register_blueprint(api_bp) return app
def test_avatar(self): u = User(username='******', email='*****@*****.**') self.assertEqual(u.avatar(128), ('https://www.gravatar.com/avatar/' 'd4c74594d841139328695756648b6bd6' '?d=identicon&s=128'))
def test_password_hashing(self): u = User(username='******') u.set_password('cat') self.assertFalse(u.check_password('dog')) self.assertTrue(u.check_password('cat'))
from my_app import db from my_app.models import User from random import randint db.create_all() for i in range(0,10): u = 'User' + str((randint(1,10000))) g = 'Guest' + str((randint(1,10000))) admin = User(username=u, email='*****@*****.**') guest = User(username=g, email='*****@*****.**') db.session.add(admin) db.session.add(guest) db.session.commit() for user in User.query.all(): print (user)
def user(): user = User(username='******', email='*****@*****.**') return user