def register(): """注册 """ if request.method == "POST": username = request.form["username"] password = request.form["password"] # 建立数据库连接 db = get_db() error = None # 检查用户名和密码是否为空 if not username: error = "Username is required." elif not password: error = "Password is required." # 检查是否已注册 elif (db.execute("SELECT id FROM user WHERE username = ?", (username, )).fetchone() is not None): error = f"User {username} is already registered." # 是合法的注册 if error is None: # 将数据插入数据库表 db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash(password)), ) # 提交事务 db.commit() # 重定向到注册页 return redirect(url_for("auth.login")) flash(error) return render_template("auth/register.html")
def login(): """登录 把登录的信息加到session里 """ if request.method == "POST": username = request.form["username"] password = request.form["password"] # 建立数据库连接 db = get_db() error = None user = db.execute("SELECT * FROM user WHERE username = ?", (username, )).fetchone() if user is None: error = "Incorrect username." elif not check_password_hash(user["password"], password): error = "Incorrect password." if error is None: # 刷新session,存储uid session.clear() session["user_id"] = user["id"] # 重定向到index页 return redirect(url_for("index")) flash(error) return render_template("auth/login.html")
def index(): """Show all the posts, most recent first.""" db = get_db() posts = db.execute("SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN user u ON p.author_id = u.id" " ORDER BY created DESC").fetchall() return render_template("blog/index.html", posts=posts)
def get_post(id, check_author=True): """Get a post and its author by id. Checks that the id exists and optionally that the current user is the author. :param id: id of post to get :param check_author: require the current user to be the author :return: the post with author information :raise 404: if a post with the given id doesn't exist :raise 403: if the current user isn't the author """ post = (get_db().execute( "SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN user u ON p.author_id = u.id" " WHERE p.id = ?", (id, ), ).fetchone()) if post is None: abort(404, f"Post id {id} doesn't exist.") if check_author and post["author_id"] != g.user["id"]: abort(403) return post
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute( #username通过查询数据库并检查是否返回结果来验证尚未注册的内容。 #对任何用户输入db.execute采用带?占位符的SQL查询,并使用替换占位符的值元组。数据库库将负责转义值,因此您不容易受到 SQL注入攻击。 'SELECT id FROM user WHERE username = ?', (username,) ).fetchone() is not None: error = 'User {} is already registered.'.format(username) if error is None: db.execute( 'INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone()
def test_delete(client, auth, app): auth.login() response = client.post('/1/delete') assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post is None
def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={'title': 'created', 'body': ''}) with app.app_context(): db = get_db() count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0] assert count == 2
def test_update(client, auth, app): auth.login() assert client.get('/1/update').status_code == 200 client.post('/1/update', data={'title': 'updated', 'body': ''}) with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post['title'] == 'updated'
def load_logged_in_user(): """在每次request视图开始前执行 查询用户是否登录,若登录,则记录用户信息在g里 """ user_id = session.get("user_id") if user_id is None: g.user = None else: g.user = (get_db().execute("SELECT * FROM user WHERE id = ?", (user_id, )).fetchone())
def app(): #创建并打开一个临时文件, #返回文件对象及其路径。该DATABASE路径被覆盖,使其指向这个临时路径,而不是实例文件夹。设置路径后, #将创建数据库表并插入测试数据。测试结束后,临时文件将被关闭并删除。 db_fd, db_path = tempfile.mkstemp() app = create_app({ #告诉Flask应用程序处于测试模式。Flask更改了一些内部行为, #因此更容易测试,而其他扩展也可以使用该标志来更轻松地测试它们。 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): init_db() get_db().executescript(_data_sql) yield app os.close(db_fd) os.unlink(db_path)
def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_db() db.execute('UPDATE post SET author_id = 2 WHERE id = 1') db.commit() auth.login() # current user can't modify other user's post assert client.post('/1/update').status_code == 403 assert client.post('/1/delete').status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get('/').data
def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) #该check_author参数定义,这样的功能可以被用来获取post不检查的作者。如果您编写了一个视图来显示页面上的单个帖子,用户无关紧要,因为他们没有修改帖子,这将非常有用。 return post
def test_register(client, app): #client.get()发出GET请求并返回ResponseFlask 返回的对象。同样, client.post()发出POST 请求,将datadict转换为表单数据。 #要测试页面呈现成功,会发出一个简单的请求并检查a 。 #如果渲染失败,Flask将返回一个 代码。200 OK status_code500 Internal Server Error assert client.get('/auth/register').status_code == 200 response = client.post('/auth/register', data={ 'username': '******', 'password': '******' }) #headersLocation当注册视图重定向到登录视图时,将具有带登录URL 的标头。 assert 'http://localhost/auth/login' == response.headers['Location'] with app.app_context(): assert get_db().execute( "select * from user where username = '******'", ).fetchone() is not None
def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id'])) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html')
def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute('UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id)) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id, )) db.commit() return redirect(url_for('blog.index'))
def index(): db = get_db() posts = db.execute('SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC').fetchall() return render_template('blog/index.html', posts=posts)