I've inherited a well established flask-based API service that makes extensive use of mongoengine. We are making this single-database API into a multi-tenant service, and unclear on the best practice. For many reasons, tenant data will be physically segregated into different databases, one db per tenant. (There is also a connection to a 'core' db for some Documents.)
The use case workflow is simple:
- receive a request
- validate the API access token and reconcile a user/tenant
- switch the database connection to the correct tenant db
- do the Document operations
It seems the best way to implement this is to use aliases, but when I context switch I need to disconnect('tenant_db')
then connect(alias='tenant_db')
. This feels wrong.
Regardless, the code actually works, but now I have a unit test issue. When testing, and using the (per documentation) mongomock://localhost
connection, the code actually times out trying to connect to a real mongodb running on localhost. I suspect all this has something to do with the mock connection not having the appropriate scope, but I can't find much documentation about testing using a mock db.
Sorry for two questions in one:
- is the
disconnect
then re-connect
alias pattern the correct approach - are there better practices (or clearer examples) of pytest+mongoengine+mongomock
Not a pro with pytest but also not a novice. Solid with pymongo
but brand new to mongoengine
.
Thanks!