Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当用户在我的python网站上注册时,他们的第一次投票不会';不算_Javascript_Python_Authentication_Facebook Login - Fatal编程技术网

Javascript 当用户在我的python网站上注册时,他们的第一次投票不会';不算

Javascript 当用户在我的python网站上注册时,他们的第一次投票不会';不算,javascript,python,authentication,facebook-login,Javascript,Python,Authentication,Facebook Login,我有一个使用Facebook登录的投票网站。当用户尝试投票时,网站会检查数据库中是否已有用户。如果没有,它会要求他们登录Facebook,将他们添加到数据库中,然后让他们投票 对于已经在系统中的用户,它可以正常工作。但是如果用户是新用户,它会成功地将他们添加到数据库中,但不会添加他们的投票。但如果他们转到另一个页面,他们可以投票,因为他们已经被添加了。我不明白发生了什么,因为检查/向数据库添加用户和向数据库添加投票是两个独立的过程 这里是代码对新用户和现有用户区别对待的唯一地方(发布所有与投票相

我有一个使用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>
用于添加投票的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))

似乎你遗漏了代码中增加他们投票的部分?应该有另一段代码(可能在“myDialog”组件中?)。如果它在那里,你也可以发布它吗?是的,补充道——它只是引用了“user_id”,它是从表单中获取的。我也会添加表格。看起来你缺少了添加他们投票的代码部分?应该有另一段代码(可能在“myDialog”组件中?)。如果它在那里,你也可以发布它吗?是的,补充道——它只是引用了“user_id”,它是从表单中获取的。我也会添加表单。
@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"
@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))