Python run connexion based application inside functions or methods only

230 Views Asked by At

I have an application that uses connexion and swagger andd is quite large already. Just like in examples of this framework, the connections to database are created outside of any function, or class. I find this approach as a really poor design, and I really feel like there should be one place (e.g. main()), where all the objects necessary are created and some .run() method is called on them.

The minimum I want is to have at least functions that are registered in swagger.yaml as endpoint handlers, to accept the database connection I provide, not one that has to be created on application start-up and available to all the functions.

Is there a way to achieve something like this, or do I have to make peace with having database connection created in one file and all the other files import it and use it?

1

There are 1 best solutions below

1
On BEST ANSWER

In the example you cited, I view it as regrettable that we call orm.init_db('sqlite:///:memory:') outside the If Main. In the example it is harmless, but consider related cases like

  1. sqlite:////tmp/pets.db or
  2. TCP connection to DB server

The file cannot be safely imported due to side effects -- it leaves behind a .db file or it perhaps dies with connect error if we lack creds or network connectivity. This affects e.g. $ python -m doctest. So I prefer to defer creating the connection until we actually need it, which a singleton getter can easily do. (Or have a class __init__() create the connection.)


For your app, rather than passing around global or parameter connection, consider passing around a function object which can get the connection as needed. It gives you a level of indirection, and admits of conditional processing.