0

Need to get the same values on each request in my views file. Instead of getting them on every request, I used before_request function and added them to global dict:

options = {}
@app.before_request
def before_request():
    options['ip'] = request.remote_addr
    options['useragent'] = request.user_agent.string

Is it a good solution or not? What can you recommend?

asyndrige
  • 572
  • 6
  • 23

2 Answers2

1

No, this is a very bad idea. Although the request is a thread-local, so you can access it everywhere, your options dict is not; it is not threadsafe, and will therefore be shared across all requests.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

The correct answer to this is to use Flask's g object. You can read about this here: http://flask.pocoo.org/docs/0.10/api/#flask.g

Ryan O'Donnell
  • 617
  • 6
  • 14