简体   繁体   中英

python using for loop in def function

I am trying to get documents created in past 7 days in DB collection.

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
for i in range(0, 7):
    target = today - timedelta(days = i)
    week = target.strftime(fmt)
    hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
    print(hot_posts)

this gives me correct document set that I am looking for from DB.

but when I insert this in def function, it doesn't work.

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
@app.route('/api/list/hot', methods=['GET'])
def show_hot():
    for i in range(0, 7):
        target = today - timedelta(days=i)
        week = target.strftime(fmt)
        hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
        return jsonify({'hot_posts': hot_posts})

I don't think I am fully understanding how to use def in correct structure. what is the correct format of using def in python for this case? Do I need to put some variable before for loop and set it like variable=[] to get the result of for loop and put it into the variable that the def function can use? and do I need to put some for loop variable into () of def function?

something like this?

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
@app.route('/api/list/hot', methods=['GET'])
def show_hot(range, list):
    hot_posts = []
    for i in range(0, 7):
        target = today - timedelta(days=i)
        week = target.strftime(fmt)
        hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
    return jsonify({'hot_posts': hot_posts})

You can make a blank dictionary and update keys and values of it on iteration and then return the resultant dictionary. I haven't tested the this code but I think it should work fine.

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
@app.route('/api/list/hot', methods=['GET'])
def show_hot():
    all_hot_posts = {}
    for i in range(0, 7):
        target = today - timedelta(days=i)
        week = target.strftime(fmt)
        hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
        all_hot_posts.update({'hot_posts'+str(i+1): hot_posts})
    return jsonify(all_hot_posts)

In python functions we do not define keywords as arguments. They are interpreted just like normal script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM