Return陈述式会列印第一个迭代,而Print会列印所有迭代-Python

时间:2019-01-23 00:58:04

标签: python python-2.7 flask flask-sqlalchemy

我正在用这个头撞墙:

我使用print语句测试了以下代码部分,它按预期输出所有迭代。但是,当我在实际程序中使用return(与flask进行交互以发布到网页)时,它仅输出第一次迭代。

此:

# Setting up cursor so we can parse results. 
cur = db.cursor()

cur.execute("SELECT user from users")
user_table = cur.fetchall()

for u in user_table:
    cur.execute("SELECT date from mood WHERE user='{}'".format(u[0]))
    user_dates = cur.fetchall()
    n = (len(user_dates) - 1) # Using this to call indexes later so need to throw away last number
    u_streak = 1
    dte_list = [ ]
    t = timedelta(days=1)
    u_streak = 1
    streak_list = [ ]
    streak_dict = {}
    sm_list = [ ]
    for dte in user_dates:
        dte_list.append(dte[0])
        dte_list = sorted(dte_list)
    for i in range(n):
        if (dte_list[i] + t) == dte_list[(i + 1)]:
            u_streak += 1
        else:
            streak_list.append(u_streak)
            u_streak = 1

    print u[0], streak_list

输出:

codestardust [1, 1, 3]
pippen [2, 2, 5, 4]
samwise [4, 1, 1, 1]

与此同时:

@app.route('/mood',methods=['GET', 'POST'])
def mood():
    if request.method == 'POST':
        user = session['username']
        mymood = request.form['mymood']
        d = datetime.today().strftime('%Y-%m-%d')

        # Confirm user is logged in
        if user and mymood:
            cur.execute("INSERT INTO mood SET mood ='{}', date = '{}', user='{}'"\
            .format(mymood,d,user) )

           # Begin streak calculation
            t = timedelta(days=1)

            cur.execute("SELECT user from users")
            user_table = cur.fetchall()


            for u in user_table:
                cur.execute("SELECT date from mood WHERE user='{}'".format(u[0]))
                user_dates = cur.fetchall()
                n = (len(user_dates) - 1) # Using this to call indexes later so need to throw away last number
                u_streak = 1
                dte_list = [ ]
                u_streak = 1
                streak_list = [ ]
                streak_dict = {}
                sm_list = [ ]
                for dte in user_dates:
                    dte_list.append(dte[0])
                    dte_list = sorted(dte_list)
                for i in range(n):
                    if (dte_list[i] + t) == dte_list[(i + 1)]:
                        u_streak += 1
                    else:
                        streak_list.append(u_streak)
                        u_streak = 1

                return jsonify([u[0], streak_list])

输出以下内容:

["codestardust", [1, 1, 3, 4]]

在我对if语句的理解有误的情况下,我已经包含了实际程序中的整个功能以提供嵌套上下文。抱歉,太冗长了。

我看到一堆this one之类的不赞成票,并且已经彻底检查了缩进错误等。我还对herehereforif语句进行了广泛的研究。

据我所知,由于return语句嵌套在for u in user_table:中,因此它应该遍历用户的所有迭代。我整天都在这里,看不到我想念的东西。任何帮助深表感谢! (我也知道我拼错了“ pippen”大声笑)

1 个答案:

答案 0 :(得分:1)

在第一个代码示例中,您只是在每次迭代的末尾进行打印,但是在烧瓶示例中,您将返回该代码。 Return停止执行它所在的函数,返回一个值(如果未指定,则为None),然后继续。您应该将这些值聚合到一个列表中或进行设置,然后将其返回给调用方进行解析。