У меня есть сайт голосования, который использует логин Facebook. Когда пользователь пытается проголосовать, веб-сайт проверяет, есть ли пользователь в базе данных. Если нет, он просит их войти в Facebook, добавить их в базу данных и затем дать им возможность проголосовать.
Отлично работает для пользователей, которые уже находятся в системе. Но если пользователь новый, он успешно добавляет их в базу данных, но не добавляет их голоса. НО, если они тогда go на другую страницу, они могут голосовать просто отлично, потому что они уже были добавлены. Я не понимаю, что происходит, так как проверка / добавление пользователей в базу данных и добавление голосов в базу данных являются отдельными процессами.
Вот единственные места, где код по-разному относится к новым пользователям и существующим пользователям (публикация сообщений весь код, связанный с голосованием, сделал бы этот пост очень длинным, но он не различает guish между этими типами пользователей, поэтому я думаю, что проблема не в этом?)
Javascript в HTML
<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))