Skip to content
Snippets Groups Projects
Select Git revision
  • 8384adc01a51c0313dfd6938cba4d9e242aa5e0d
  • master default protected
  • date-parsing
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.0.0
  • v0.1.0
8 results

postgrestutils

beckerfy's avatar
Fynn Becker authored
8384adc0
History

postgrestutils

A very basic POSTGREST client and utils

Setup

Django
  • add "postgrestutils" to your INSTALLED_APPS setting
  • add POSTGREST_UTILS_BASE_URI (should default to the most frequently used POSTGREST instance in the future) and POSTGREST_UTILS_JWT to your project settings
from postgrestutils.client import pgrest_client

payload = {
    "select": "id,forename",
    "forename": "eq.Jebediah"
}

# this will send a request to 'POSTGREST_UTILS_BASE_URI/kerbals?select=id,forename&forename=eq.Jebediah'
res = pgrest_client.get("kerbals", params=payload)
Other projects
from postgrestutils import settings

settings.BASE_URI = "http://localhost:3000"
settings.JWT = ""

from postgrestutils.client import pgrest_client

payload = {
    "select": "id,forename"
}
res = pgrest_client.get("kerbals", params=payload)

Filtering

http://postgrest.org/en/stable/api.html

Django helpers

custom user_account_fetched signal

postgrestutils provides a custom signal called user_account_fetched which provides the current request and the account of the current user on login. To use this feature (and you really should 99.9% of the time) configure your settings accordingly by specifying the columns you need from the account endpoint:

# settings.py
POSTGREST_UTILS_AUTOFETCH = 'person_id,email'  # comma-separated string

When connecting to the signal you will have to provide a callback function. That function is a great place for your custom logic to fetch and store additional information your app frequently needs into the session. You can connect to it like so:

# apps.py
from django.apps import AppConfig
from postgrestutils.signals import user_account_fetched
from your_app.utils import your_callback_func


class YourAppConfig(AppConfig):
    def ready(self, *args, **kwargs):
        super().ready(*args, **kwargs)
        user_account_fetched.connect(your_callback_func)

Your callback function could look something like this:

# utils.py
from postgrestutils.client import pgrest_client


def your_callback_func(sender, **kwargs):
    request = kwargs['request']
    account = kwargs['account']
    # fetching some addtional data your project needs frequently using the pgrest_client (person, memberships etc.)

    # 'caching' that data in the session
    request.session['account'] = account
    request.session['person'] = person
    request.session['memberships'] = memberships

For more information on signals refer to the django docs. They are great. Really.