def forge(count: int): """Generate fake message.""" from faker import Faker import random fake = Faker() db.drop_all() db.create_all() click.echo("Generating a User...") user = User(username="******") user.set_password("123") for i in range(count): click.echo("Creating the item...") item = Item( user=user, title=fake.sentence(), status=random.randint(0, 1), create_time=fake.date_time_this_year(), ) db.session.add(item) db.session.commit() click.echo(f"Created {count} fake item.")
def register(): form = RegisterForm() if current_user.is_authenticated: return redirect(url_for("todo.index")) if form.validate_on_submit(): user = User(username=form.username.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash("Register success.") return redirect(url_for(".login")) return render_template("register.html", form=form)
def registration(): 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('Congratulations, you are now a registered user!', 'success') return redirect(url_for('users.login')) return render_template('registration.html', title='registration', form=form)
def route_login(request): headers = { 'Content-Type': 'text/html', # 'Set-Cookie': 'height=169; gua=1; pwd=2; Path=/', } # log('login, headers', request.headers) log('login, cookies', request.cookies) username = current_user(request) if request.method == 'POST': form = request.form() u = User.new(form) if u.validate_login(): # 设置一个随机字符串来当令牌使用 session_id = random_str() session[session_id] = u.username headers['Set-Cookie'] = 'user={}'.format(session_id) # 下面是把用户名存入 cookie 中 # headers['Set-Cookie'] = 'user={}'.format(u.username) result = '登录成功' else: result = '用户名或者密码错误' else: result = '' body = template('login.html') body = body.replace('{{result}}', result) body = body.replace('{{username}}', username) header = response_with_headers(headers) r = header + '\r\n' + body log('login 的响应', r) return r.encode(encoding='utf-8')
def post(self): info = register_reqparser.parse_args() status = 0 data = {} user = User.query.filter_by(username=info['username']).first() if user is not None: status = 1 message = "username already exits" else: new_user = User(info['username']) new_user.set_password(info['password']) db.session.add(new_user) db.session.commit() message = 'register succeed' data = {'user_id': new_user.id, 'username': new_user.username} return {'status': status, 'message': message, 'data': data}
def client(): app.config.update( TESTING=True, WTF_CSRF_ENABLED=False, SQLALCHEMY_DATABASE_URI="sqlite:///:memory:", ) user = User(username="******") user.set_password("123") item = Item(title="hello flask", status=1) with app.test_client() as client: with app.test_request_context(): db.create_all() db.session.add_all([user, item]) db.session.commit() yield client db.drop_all(app=app)
def route_register(request): header = 'HTTP/1.1 210 VERY OK\r\nContent-Type: text/html\r\n' if request.method == 'POST': form = request.form() u = User.new(form) if u.validate_register(): u.save() result = '注册成功<br> <pre>{}</pre>'.format(User.all()) else: result = '用户名或者密码长度必须大于2' else: result = '' body = template('register.html') body = body.replace('{{result}}', result) r = header + '\r\n' + body return r.encode(encoding='utf-8')
def create_user(name, email, password, profile_image): db_sess = db_session.create_session() # Генерируем уникальный код пользователя для добавления в друзья code, user_friend_codes = random_with_N_digits(8), db_sess.query(User.friend_code).all() codes = [int(code[0]) for code in user_friend_codes] if user_friend_codes else [] while code in codes: code = random_with_N_digits(8) user = User(name=name, email=email, image_file=profile_image, friend_code=code) user.set_password(password) db_sess.add(user) db_sess.commit()
def init(username: str, password: str): """Initialize a user.""" click.echo("Initializing the database...") db.create_all() user = User.query.first() if user is not None: click.echo("The administrator already exist, updating...") user.username = username user.set_password(password) else: click.echo("Creating the temporary administrator account...") user = User(username=username) user.set_password(password) db.session.add(user) db.session.commit() click.echo("Done.")
def delete_todo(request): uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') # 得到当前编辑的todo的id todo_id = int(request.query.get('id', -1)) t = Todo.find_by(id=todo_id) if t.user_id != u.id: return redirect('/login') if t is not None: t.remove() return redirect('/todo')
def register(): username = fake.user_name() while User.query.filter_by(username=username).first() is not None: username = fake.user_name() password = fake.word() user = User(username=username) user.set_password(password) db.session.add(user) db.session.commit() item = Item(body=_('Witness something truly majestic'), author=user) item2 = Item(body=_('Help a complete stranger'), author=user) item3 = Item(body=_('Drive a motorcycle on the Great Wall of China'), author=user) item4 = Item(body=_('Sit on the Great Egyptian Pyramids'), done=True, author=user) db.session.add_all([item, item2, item3, item4]) db.session.commit() return jsonify(username=username, password=password, message=_('Generate success.'))
def add(request): headers = { 'Content-Type': 'text/html', } uname = current_user(request) u = User.find_by(username=uname) if request.method == 'POST': # 'title=aaa' # {'title': 'aaa'} form = request.form() t = Todo.new(form) t.user_id = u.id t.save() # 浏览器发送数据过来被处理后, 重定向到首页 # 浏览器在请求新首页的时候, 就能看到新增的数据了 return redirect('/todo')
def signup(request): first_name = request.POST.get("first_name", " ") last_name = request.POST.get("last_name", " ") username = request.POST.get("username", " ") password = request.POST.get("password", " ") confirm_password = request.POST.get("confirm_password", " ") if password == confirm_password: user = User.create(username, password, first_name, last_name) user.save() request.session['username'] = username request.session['authorized'] = True else: request.session['authorized'] = False return todolist(request)
def register(): if current_user.is_authenticated: return redirect(url_for("main.home")) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode("utf-8") user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash("Your account has been created! You are now able to log in", "success") return redirect(url_for("users.login")) return render_template("register.html", title="Register", form=form)
def index(request): headers = { 'Content-Type': 'text/html', } uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') todo_list = Todo.find_all(user_id=u.id) todo_html = ''.join( ['<h3>{} : {} </h3>'.format(t.id, t.title) for t in todo_list]) body = template('todo_index.html') body = body.replace('{{todos}}', todo_html) headers = response_with_headers(headers) r = headers + '\r\n' + body return r.encode(encoding='utf-8')
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", "warning") return redirect(url_for("users.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", "success") return redirect(url_for("users.login")) return render_template("reset_token.html", title="Reset Password", form=form)
def update(request): """ 用于增加新todo的路由函数 """ uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') if request.method == 'POST': # 修改并且保存todo form = request.form() print('debug update', form) todo_id = int(form.get('id', -1)) t = Todo.find_by(id=todo_id) t.title = form.get('title', t.title) t.save() # 浏览器发送数据过来被处理后, 重定向到首页 # 浏览器在请求新首页的时候, 就能看到新增的数据了 return redirect('/todo')
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', 'warning') return redirect(url_for('users.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', 'success') return redirect(url_for('users.login')) return render_template('reset_token.html', title='Reset Password', form=form)
def edit(request): headers = { 'Content-Type': 'text/html', } uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') todo_id = int(request.query.get('id', -1)) t = Todo.find_by(id=todo_id) if t.user_id != u.id: return redirect('/login') body = template('todo_edit.html') body = body.replace('{{todo_id}}', str(t.id)) body = body.replace('{{todo_title}}', str(t.title)) # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中 header = response_with_headers(headers) r = header + '\r\n' + body return r.encode(encoding='utf-8')
def f(request): uname = current_user(request) u = User.find_by(username=uname) if u is None: return redirect('/login') return route_function(request)