I have a question regarding Flask SQLAlchemy.

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

First of all, the logic to be implemented is to read the time value (data) stored in the DB through the datetime module When I display it on the web after processing it once, I want to print it out in the following way.

The logic below is implemented as a separate function, so to be exact, DB data is imported into the for statement and then called the function below We have returned the processed value after processing it.


item = testdb.query.order_by(idx.desc())
for datas in item:
        save_time = return_time(datas.time)

(Logic Processing Function)

if (result < 60):
    return_time = "Just now"
elif(result >= 60 and result < 3600):
    return_time = floor(result/60)
elif(result >= 3600 and result < 86400):
    return_time = floor(result/3600)
elif(result >= 86400 and result < 2419200):
    return_time = fllor(result/86400)
    return_time = result.strftime('%Y-%m-%d')

However, after processing it like this, use the render_template function to hand it over like time=str(save_time)) If so, only one value comes in and I tried to list the for statement, but it didn't print well in the desired direction.

Output example)

Just now | (Title)

5 minutes ago | (Title)

1 hour ago | (Title)

I'm going to film it like this.

item=item, time=str(save_time) When you turn over the print on the web, you try to turn it over separately

It's not working well, I may not have enough code, but please give me feedback.

python sqlalchemy flask

2022-09-20 16:28

1 Answers

I think the questionnaire has nothing to do with SQLalchemy.

If you want a specific answer, I think you should check the logic and template

  from flask import flask, render template string.
import datetime

index = '''<html>
{% for i in datas %}
<p> {{i[1]}} | {{i[0]}} </p>
{% endfor %}
app = Flask(__name__)

def return_time(time):
    now = round(datetime.datetime.now().timestamp())
    r = []
    for i in time:
        t = round(datetime.datetime.strptime(i, '%Y-%m-%d %H:%M').timestamp())
        if now - t < 360:
            r.append ("5 minutes ago")
        elif now - t < 1800:
            r.append ("30 minutes ago")
    return r

def main():
    db_data = ['subject1','subject2','subject3']
    db_date = ['2021-05-11 16:00','2021-05-11 15:50','2021-05-10 15:35']
    db_date = return_time(db_date)
    return render_template_string(index, datas=zip(db_data,db_date))

if __name__ == '__main__':
5 minutes ago | subject1

30 minutes ago | subject2

2021-05-10 15:35 | subject3

2022-09-20 16:28

If you have any answers or tips

© 2022 pinfo. All rights reserved.