To be more specific, I have created a custom Redis module: MyRedis
MyRedis.py
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
def get_func(k):
""" A custom get function """
return r.get(k)
# ...
# more functions ...
# ...
Note that the connection is established when the module is loaded.
My question is:
Is this the correct way to write the module, or should I include the r = redis.StrictRedis(...) connection establishing line within each function, like so:
def get_func(k):
""" A custom get function """
r = redis.StrictRedis(host='localhost', port=6379, db=0)
return r.get(k)
In a web app, is a module loaded only once, as in a “regular” backend app? Or is it loaded once per connection?
If it’s loaded only once, this means that if the Redis server crashes for some reason, once it’s started again there will be no connections, which suggests the second snippet is the correct one.
So how do python modules behave in a web app?
However the SAPI behaves. If it’s CGI, it’s loaded for each request. For mod_wsgi, it’s loaded once for each process. For others, see their documentation.