javascript - 当用户在我的 python 网站上注册时,他们的第一票不算数
问题描述
我有一个使用 Facebook 登录的投票网站。当用户尝试投票时,网站会检查用户是否已经在数据库中。如果没有,它会要求他们登录 Facebook,将他们添加到数据库中,然后让他们投票。
它适用于已经在系统中的用户。但是如果用户是新用户,它会成功地将他们添加到数据库中,但不会添加他们的投票。但是,如果他们然后转到另一个页面,他们可以投票就好了,因为他们已经被添加了。我不明白发生了什么,因为检查/向数据库添加用户和向数据库添加投票是单独的过程。
这里是代码区别对待新用户和现有用户的唯一地方(发布所有与投票相关的代码会使这篇文章变得超长,但它不区分这些类型的用户,所以我认为这不是问题出在哪里?)
HTML 中的 JavaScript
<script>
var person = { userID: "", name: "", accessToken: "", picture: ""}
window.fbAsyncInit = function() {
FB.init({
appId : '1936452948301234',
autoLogAppEvents : true,
xfbml : true,
version : 'v5.0'
});
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status !== 'connected') {
document.getElementById("myDialog").showModal();
} else {
addHiddenInput(response.authResponse.userID)
person.accessToken = response.authResponse.accessToken;
person.userID = response.authResponse.userID;
FB.api('/me?fields=id,name,picture.type(large)', function (userData) {
console.log(userData);
person.name = userData.name;
person.picture = userData.picture.data.url;
$.ajax({
type: 'POST',
url: 'https://mywebsite.com/fbuser',
data: person,
datatype: 'text',
success: function myFunction(data) {
console.log("fb data sent");
}
})
});
}
});
};
function hideDialogAfterLogin () {
document.getElementById("myDialog").close();
FB.getLoginStatus(function(response) {
addHiddenInput(response.authResponse.userID)
});
}
function addHiddenInput (userID) {
var hiddenInput = document.getElementById("user_id")
hiddenInput.value = userID
}
</script>
之后
<form action = "/insert_vote" method = "post" onsubmit="">
<div id="vote-form" action = "/insert_vote" method = "post" onsubmit="">
<div class="smalltext">
{% for dict_item in vote_choices %}
<input type="radio" name="options" padding="10px" margin="10px" id="{{ dict_item['id'] }}"
value="{{ dict_item['id'] }}"> {{ dict_item['choice'] }} </input><br>
{% endfor %}
</div>
<br>
<div class="mediumlefttext">
Why did you make that choice?
</div>
<!-- <input type="text" name="comments" id="comments" placeholder="The article said only 10% of poodles are evil geniuses. It says it got its information from a new White House report, but when I got to www.whitehouse.gov, I find the report (www.whitehouse.gov/report.html), and it says 80% of poodles are evil." style="height:150px"> </input> <br>-->
<textarea name="comments" id="comments"></textarea>
<!--<button onclick="javascript:login();" size="large" type="submit" value="Submit" scope="public_profile,email" returnscopes="true" onlogin="checkLoginState();">Submit</button>-->
<input type="text" name="user_id" id="user_id" style="display:none;">
<Script>console.log("here comes the user id from the html");</Script>
<Script>console.log(user_id);</Script>
<input type="text" name="article_id" id="article_id" value="{{ article_id }}" style="display:none;">
<!-- <input type="text" name="user_id" id="user_id" style="display:none;">-->
<!-- <input type="text" name="article_id" id="article_id" style="display:none;">-->
<input type="submit" value="Submit">
</div>
</form>
面向用户的 Python
@application.route('/fbuser', methods=['POST'])
def fbuser():
print("this is version 1.1")
# global user_id
# request.form is the data from facebook, includes userID, picture, name
person = request.form
print("FBUSER", person)
print("ID", person.get("userID"))
# user = person.get("userID")
# we check the db for the user, if they exist we are done
maybe_existing_user = User.query.filter_by(fb_id=person.get("userID")).first()
# check if user is in db, if so, set ID...
if(maybe_existing_user):
fb_user_id = maybe_existing_user.id
return "exists"
else:
new_user = User(int(person.get("userID")), person.get("picture"), person.get("name"), 5)
db.session.add(new_user)
try:
db.session.commit()
print("success sql")
now_existing_user = User.query.filter_by(fb_id=int(person.get("userID"))).first()
# if(now_existing_user is None) Error
fb_user_id = now_existing_user.id
return "created"
except exc.SQLAlchemyError as e:
print(e)
flash('Article url already exists, failed to post new user')
print("sql fail")
return "failed to create"
用于添加投票的 Python
@application.route('/insert_vote', methods=['GET', 'POST'])
def insert_vote():
posted = 1
if request.method == 'POST' or request.method == 'GET':
if not request.form['options']:
flash('Please enter all the fields', 'error')
else:
rate = 0 # rate of votes protection against no votes
vote_choice_id = int(request.form['options'])
comments = request.form['comments']
article_id = int(request.form['article_id'])
user_id = request.form['user_id']
print(user_id)
fb_user_id = int(user_id)
av_obj = ArticleVote(fb_user_id, article_id, vote_choice_id, comments)
db.session.add(av_obj)
try:
db.session.commit()
except exc.SQLAlchemyError as e:
print("user has already voted before")
posted = 0
if posted == 1:
print("posted ==1 after")
flash('Record was successfully added')
else:
db.session.rollback()
a_obj = Article.query.filter_by(id=article_id).first()
# this is the current global article
avs_obj = retrieve_article_vote_summary(
a_obj.id) # vote_summary is a list of [tuples('True', numOfTrue), etc]
total_votes = avs_obj.getTotalVotes()
print("here's the object ", a_obj.id)
print("this is the total votes ", total_votes)
vote_choice_list = VoteChoice.getVoteChoiceList()
vote_choices = []
for item in vote_choice_list: # looping over VoteChoice objects
num = avs_obj.getVoteCount(item.choice)
if total_votes > 0:
rate = num / total_votes
vote_choices.append([item.choice, item.color, num, rate * 100, total_votes])
print("a_obj", a_obj)
details = avs_obj.getVoteDetails() # 10/02 - retrieve array of tuples [(user, VoteChoice, Comments)]
details_count = 0
for detail in details:
print(detail)
details_count += 1
return redirect('/results/' + str(a_obj.id))
解决方案
推荐阅读
- java - JAVA 错误:React 本机基本项目在 android studio 中不起作用
- javascript - discord.js 如何删除所有频道中包含黑名单的消息
- c++ - 如何使内部增强已弃用消息静音
- php - 如何用php从这个字符串中回显数据
- python - 获取 spacy PhraseMatcher 的模式
- sql - 如何使用派生列将字符串转换为 SSIS 中的小数?
- amazon-web-services - AWS:在 ECS 上运行的 EC2 容器的重要性顺序
- python-3.x - Sage 给了我一个线性拟阵错误等级的基础,或者,我做错了什么?
- javascript - 在 Vanilla JS 中计算产品的折扣百分比
- selenium-webdriver - 放心不返回任何数据