Tips and tricks¶
This part is dedicated to some code organisation within your application.
The examples are more focused on the Esmerald as the author is the same but again, you can do the same in your favourite framework.
Placing your connection in a centralised place¶
This is probably what you would like to do in your application since you don't want to declare over and over again the same variables.
The main reason for that is the fact that every time you declare a registry, in fact you are generating a new object and this is not great if you need to access the documents used with the main registry, right?
Place the connection details inside a global settings file¶
This is probably the easiest way to place the connection details and particulary for Esmerald since it comes with a simple and easy way of accesing the settings anywhere in the code.
Something simple like this:
"""
Generated by 'esmerald createproject'
"""
from functools import cached_property
from typing import Optional
from esmerald.conf.enums import EnvironmentType
from esmerald.conf.global_settings import EsmeraldAPISettings
from mongoz import Registry
class AppSettings(EsmeraldAPISettings):
app_name: str = "My application in production mode."
environment: Optional[str] = EnvironmentType.PRODUCTION
secret_key: str = "esmerald-insecure-h35r*b9$+hw-x2hnt5c)vva=!zn$*a7#" # auto generated
@cached_property
def db_connection(self) -> Registry:
"""
To make sure the registry and the database connection remains the same
all the time, always use the cached_property.
"""
database = "mongodb://root:mongoadmin@localhost:27017"
return Registry(database=database)
As you can see, now you have the db_connection
in one place and easy to access from anywhere in
your code. In the case of Esmerald:
from esmerald.conf import settings
registry = settings.db_connection
But is this enough? No.
As mentioned before, when assigning or creating a variable, python itself generates a new object
with a different id
which can differ from each time you need to import the settings into the
needed places.
We won't talk about this pythonic trick as there is plenty of documentation on the web and better suited for that same purpose.
How do we solve this issue? Enters lru_cache.
The LRU cache¶
LRU extends for least recently used.
A very common technique that aims to help caching certain pieces of functionality within your codebase and making sure you do not generate extra objects and this is exactly what we need.
Use the example above, let us now create a new file called utils.py
where we will be applying
the lru_cache
technique for our db_connection
.
from functools import lru_cache
from esmerald.conf import settings
@lru_cache()
def get_db_connection():
registry = settings.db_connection
return registry
This will make sure that from now on you will always use the same connection and registry within
your appliction by importing the get_db_connection()
anywhere is needed.
Pratical example¶
For this example we will have the following structure (we won't be use using all of the files). We won't be creating views as this is not the purpose of the example.
.
└── myproject
├── __init__.py
├── apps
│ ├── __init__.py
│ └── accounts
│ ├── __init__.py
│ ├── tests.py
│ └── v1
│ ├── __init__.py
│ ├── schemas.py
│ ├── urls.py
│ └── views.py
├── configs
│ ├── __init__.py
│ ├── development
│ │ ├── __init__.py
│ │ └── settings.py
│ ├── settings.py
│ └── testing
│ ├── __init__.py
│ └── settings.py
├── main.py
├── serve.py
├── utils.py
├── tests
│ ├── __init__.py
│ └── test_app.py
└── urls.py
This structure is generated by using the Esmerald directives
The settings¶
As mentioned before we will have a settings file with database connection properties assembled.
"""
Generated by 'esmerald createproject'
"""
from functools import cached_property
from typing import Optional
from esmerald.conf.enums import EnvironmentType
from esmerald.conf.global_settings import EsmeraldAPISettings
from mongoz import Registry
class AppSettings(EsmeraldAPISettings):
app_name: str = "My application in production mode."
environment: Optional[str] = EnvironmentType.PRODUCTION
secret_key: str = "esmerald-insecure-h35r*b9$+hw-x2hnt5c)vva=!zn$*a7#" # auto generated
@cached_property
def db_connection(self) -> Registry:
"""
To make sure the registry and the database connection remains the same
all the time, always use the cached_property.
"""
database = "mongodb://root:mongoadmin@localhost:27017"
return Registry(database=database)
The utils¶
Now we create the utils.py
where we appy the LRU technique.
from functools import lru_cache
from esmerald.conf import settings
@lru_cache()
def get_db_connection():
registry = settings.db_connection
return registry
The documents¶
We can now start creating our documents and making sure we keep them always in the same registry
from datetime import datetime
from my_project.utils import get_db_connection
import mongoz
registry = get_db_connection()
class BaseDocument(mongoz.Document):
class Meta:
abstract = True
registry = registry
database = "my_db"
class User(BaseDocument):
"""
Base document for a user
"""
first_name: str = mongoz.String(max_length=150)
last_name: str = mongoz.String(max_length=150)
username: str = mongoz.String(max_length=150, unique=True)
email: str = mongoz.Email(max_length=120, unique=True)
password: str = mongoz.String(max_length=128)
last_login: datetime = mongoz.DateTime(null=True)
is_active: bool = mongoz.Boolean(default=True)
is_staff: bool = mongoz.Boolean(default=False)
is_superuser: bool = mongoz.Boolean(default=False)
Here applied the inheritance to make it clean and more readable in case we want even more documents.
As you could also notice, we are importing the get_db_connection()
previously created. This is
now what we will be using everywhere.
Notes¶
The above example shows how you could take leverage of a centralised place to manage your connections and then use it across your application keeping your code always clean not redundant and beautiful.
This example is applied to any of your favourite frameworks and you can use as many and different techniques as the ones you see fit for your own purposes.
Mongoz is framework agnostic.