I'm building an API with Django, I want to query the Github GraphQL API, and I found this GraphQL client for python that suits my needs.
But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure:
.
├── LICENSE
├── README.md
├── api
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── portfolio
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── requirements.txt
└── setup.py
Thanks in advance!
TLDR: instantiate new client right in the view method = new client for each request. (good option - overriding initial view method). Improve later.
It depends.
If there are no request / user options for the client (= client is the same for every request / user):
import one from submodule as @ElPapi42 suggested (= same as instantiate new client in views.py globally, not as part of method logic)
or instantiate new client right in the view method - new client for each request
If there are request / user specific options (i.e. client need to have request.user specific options / credentials):
Option 1 - Client is instantiated once per worker view. Although it provides some performance benefits they are subtle and obscured:
In reality you may want to connect to github with some current request.user specific options, perform multiple requests (= cookies may be involved and auto-added in subsequent requests => client cannot be shared with multiple users) = at least separate client for each user.
As per definition a graphql client needs it's own configuration, modules and error handling I would suggest you to create a namespace adjacent to your other projects. Django uses the concept of Applications which is providing seperated configuration, logging and error handling for this case. You define additional Applications in your project in your settings.py in INSTALLED_APPS (Docs). Your project structure would then look smth like:
.
├── LICENSE
├── README.md
├── graphql-client
│ ├── __init__.py
│ ├── main.py
│ ├── client.py
│ ├── ressources
│ │ ├── __init__.py
│ ├── ├── repository.py
│ │ └── user.py
│ ├── settings.py
│ └── views.py
├── api
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── portfolio
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── requirements.txt
└── setup.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With