我正在使用PostgreSQL数据库在烧瓶中开发一个书评网络应用程序。但是,我停留在如何登录用户和跟踪他们的会话的问题上,一旦用户登录,就必须将他带到html页面,在那里他可以搜索书并添加评论。我知道我们可以在烧瓶中使用sessions
。但是,我对如何做感到很困惑。
application.py
@app.route("/signin",methods=["GET","POST"])
def signin():
if request.method=="GET":
session["user_id"] = user_id #ERROR ON THIS LINE
return render_template("login.html")
else:
return render_template("search.html")
我在数据库中的users
表存储了用户名,密码和user_id
Table "public.users"
Column | Type | Collation | Nullable | Default
----------+-----------------------+-----------+----------+----------------------------------------
username | character varying(30) | | not null | ''::character varying
password | character varying(30) | | not null | ''::character varying
user_id | integer | | not null | nextval('users_user_id_seq'::regclass)
Indexes:
"users_pkey" PRIMARY KEY, btree (user_id)
答案 0 :(得分:1)
我不确定您从何处获取user_id
变量,但是使用会话的语法正确。除了在GET请求中分配session["user_id"]
之外,您还可以在成功发布后分配它,如下所示:
@app.route("/signin",methods=["GET","POST"])
def signin():
if request.method=="GET":
return render_template("login.html")
else:
# assuming you have an html form with <input type="text" name="username"> and <input type="password" name="password">
username = request.form.get("username") # from your login form
password = request.form.get("password")
# verify the username and password here to see if they are in the database then return the id of the person
# if the id is an integer then you can do this:
session["user_id"] = user_id # from the database
#instead of using the same endpoint, I'd suggest redirecting to a different endpoint that renders the search.html while checking the session for the userid
return redirect(url_for("search"))
@app.route("/search")
def search():
if "user_id" in session:
return render_template("search.html")
else:
return redirect(url_for("signin"))