3

I have a Flask application where I initialize a connection to a device upon server startup. In other words, I initialize this connection in the same file as I call app.run. This connection comes in the form of an object that calls functions on this device, using the established connection. I want this connection to persist throughout the lifetime of the server, and I would ideally like this object to persist throughout the lifetime of the server. Since Flask could potentially start multiple threads to handle requests to the server.

Where and how is the best way to initialize such an object such that it's

  • initialized exactly once

  • able to be accessed in multiple Blueprints

Perhaps I'm looking for something like a Singleton?

Thanks!

Carpetfizz
  • 8,707
  • 22
  • 85
  • 146

1 Answers1

1

If you know your app will only run in one process with multiple threads (which is probably not the case in most production WSGI servers), one approach is to pair the resource with a threading.Lock, encapsulating both in a class. Then 'pass' a (single) instance of that class to the app via the config. Within the encapsulating class, guard access to the resource.

The Flask side might do

@app.route('/something')
def something():
    app.config['RESOURCE'].action(...)
    ...

which calls a method that locks access to the resource and delegates the call.

def action(self, ...):
    with self.lock:
        self.resource.action(...)

Locking in this way will block other Flask threads that might want simultaneous access to resource.

There's a working example you can crib from here. Look at control.py, and ignore the part about running Flask in a separate thread.

This works fine in the dev server. All bets are off if you deploy under uwsgi/gunicorn.

davidism
  • 121,510
  • 29
  • 395
  • 339
Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46