Source code for duck.backend.django.bridge
"""
This module acts as a bridge between a Django server and a Duck server. It allows Django to handle requests that are originally meant for the Duck server.
Here's how it works:
1. **Client sends a request:** The client initiates a request to the Duck server.
2. **Duck server receives request:** The Duck server receives the request first.
3. **Request forwarded to Django:** The Duck server forwards the request to the Django server on the same network.
4. **Django processes request:** Django handles the request as if the route was defined within Duck urls.py or in Django itself.
5. **Response sent to client:** The response generated by Django is sent back to the client.
"""
import os
from duck.settings import SETTINGS
from duck.logging import logger
from duck.utils.importer import import_module_once
from duck.backend.django.utils import run_django_command, run_from_command_line
# Attempt to import the local Django duck app module
try:
django_settings_module = import_module_once(SETTINGS['DJANGO_SETTINGS_MODULE'])
except (ImportError, KeyError, ModuleNotFoundError):
raise ImportError(
"Please make sure that the Django project structure for Duck is correct and DUCK_SETTINGS_MODULE is set correctly."
)
[docs]
def run_django_app_commands():
"""
Executes essential Django management commands, usually makemigrations, migrate, and collectstatic.
This function ensures that the Django application is properly set up with
the latest database schema and static files.
"""
commands = SETTINGS["DJANGO_COMMANDS_ON_STARTUP"]
if not commands:
return
# Log something first.
logger.log(f"Running Django commands\n └── {commands} \n", level=logger.DEBUG)
for command in commands:
command = command.strip()
if command.startswith("collectstatic"):
if command != "collectstatic --noinput":
command = "collectstatic --noinput"
logger.log(
"WARNING: collectstatic command should be run with --noinput flag. Running collectstatic "
"--noinput instead.",
level=logger.WARNING,
)
# Log something to console.
logger.log(f"Running command: {command}", level=logger.DEBUG) # log command being run
run_from_command_line("manage.py " + command if not command.startswith("manage.py") else command)
logger.log_raw("\n")
[docs]
def start_django_server(host_addr: str, port: int, uses_ipv6: bool = False):
"""
Starts the Django application server.
Args:
host_addr (str): The host address to bind the server to.
port (int): The port to bind the server to.
uses_ipv6 (bool): Whether host on ipv6 address
"""
# Hide development server warning
# https://docs.djangoproject.com/en/stable/ref/django-admin/#envvar-DJANGO_RUNSERVER_HIDE_WARNING
os.environ['DJANGO_RUNSERVER_HIDE_WARNING'] = "true"
if uses_ipv6:
host_addr = f"[{host_addr}]"
# Run the django runserver command.
run_django_command("runserver", f"{host_addr}:{port}", noreload=True, use_reloader=False)