【发布时间】:2021-12-28 20:06:50
【问题描述】:
我正在使用 sqlite 数据库构建一个基本的 Flask 应用程序。
我无法实现的功能是让用户能够接受或拒绝来自其他用户的联系请求(如好友请求)。
在“/contacts”页面上,您可以毫无问题地看到您从其他用户收到的所有联系请求,但我想添加接受或拒绝它们的选项,这就是我卡住的地方。
通过从数据库中获取当前用户收到的所有联系请求并在页面上显示它们来动态生成表单。
我尝试为每个请求使用两个<input type="submit" name="accept/delete" value="id_of_the_request"> 标签,一个带有accept 选项,另一个带有delete 选项,两者都指向相同的路由,但与其他一些输入类型不同,“value”属性控制什么文本出现在按钮上,所以我不能将其设置为联系请求的 id(我在下面的代码中做了),因为我在页面上看到两个带有数字的按钮。
我想过做相反的事情并将标签的name设置为请求的ID,并将value设置为“删除”或“接受”,但是在服务器端我不知道是什么使用 request.form.get() 获取的名称,因为请求的 id 是根据数据库中的内容在表单中动态生成的。
我觉得我缺少一些基本知识,但做到这一点应该不会太难。
这是我的 html 代码(模板从数据库传递了一个字典(请求)列表,对应于当前用户收到的联系请求列表。每个请求由 3 列组成:request_id、user_email、contact_email。 request_id 是主键,user_email 是发送请求的人的电子邮件,而contact_email 是接收请求的人的电子邮件。):
<form action="/manage_requests" method="post">
<ul>
{% for request in requests %}
<li>{{request.user_email}} sent you a contact request.</li>
<input type="submit" name="accept" value="{{request.r_id}}">
<input type="submit" name="refuse" value="{{request.r_id}}">
{% endfor %}
</ul>
</form>
这是我处理接受或拒绝请求的python代码:
@app.route("/manage_requests", methods = ["POST"])
@login_required
def manage_requests():
acceptedID = int(request.form.get("accept"))
refusedID = int(request.form.get("refuse"))
## Add the user who sent the request as a contact for both them and us, then delete the request.
if acceptedID :
# fetch the info of the request corresponding id from the database requests table
# get the sender's user_email
# insert the data into the database contacts table for both the sender and the receiver (current user)
# delete the request from the requests table in the database
return redirect("/contacts")
## Delete the request
elif refusedID :
# delete the request from the database requests table
return redirect("/contacts")
【问题讨论】: