0

so i'm creating simple web page using Flask, just for practice and i have this little problem. i want to count how many times i've reloaded page. for example:

count = 0
@app.route("/")
def home():
    print(count)
    count += 1
    return "testing"

but this doesn't work. if you guys know anything about it please help. <3 Thanks!

Varsima
  • 31
  • 1
  • 6
  • You could check how many requests you are getting from a particular ip address. However, a front end approach shown here https://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript might be better, then you could send a request to the server whenever the browser detects the reload. This might not be easier than the IP address method, but might make users feel more "safe" – rishi Mar 10 '22 at 10:45
  • https://stackoverflow.com/questions/32815451/are-global-variables-thread-safe-in-flask-how-do-i-share-data-between-requests could help – Learning is a mess Mar 10 '22 at 10:46
  • in that code i have a list. and i want to print next item from list, everytime user reloads the page. and i thougt i would use counter and maybe use that as index of list <3 i hope i understand it well :D <3 – Varsima Mar 10 '22 at 10:48

2 Answers2

0

the above code will work, but since you are trying to access the count variable from a function, you need to declare in the function that its a global:

count = 0
@app.route("/")
def home():
    global count
    print(count)
    count += 1
    return "testing"

more info on global variables here

ilias-sp
  • 6,135
  • 4
  • 28
  • 41
-1

This isn't the problem related to the flask. It's related to the python global variable. You just need to access your global variable declared globally inside the function using the global variable. Check here for more details related to python variable types.

The code can be updated as

count = 0
@app.route("/")
def home():
    global count
    print(count)
    count += 1
    return "testing"

Note: The best practice for concurrent users is to avoid using the global variable. Instead, use python multiprocessing.Value as mentioned here

Shubhank Gupta
  • 705
  • 2
  • 10
  • 27