Deploy Brython code with Django

During the development django-brython can serve any Python code from the $PATH. In the production environment it is not accepted to download any Python files from server. If the DEBUG settings is False, then the Python file serving doesn’t work anymore. Working with Brython in production, you need to bundle the files. django-brython integrates into the Django staticfiles ecosystem. To get things working, you need to setup Brythons static file finder and the main/entry module of your client codes. In the previous examples the frontend application is used as the main module.

# project/settings.py

STATICFILES_FINDERS = [
    ...
    'django_brython.staticfiles.BrythonStaticGenerator',
]

BRYTHON_BUNDLER_MAIN_MODULE = 'frontend'

After this try to use the collectstatic:

python manage.py collectstatic

django-brython generates Brython/Javascript file into your apps static directory:

static/
  frontend/
     js/
       frontent.brython.js

Insert the brython.js into the HTML template, and you’re done:

<head>
    ...
    <script type="text/javascript" src="{% static 'django_brython/js/brython.js' %}"></script>
    <script type="text/javascript" src="{% static 'django_brython/js/brython_stdlib.js' %}"></script>

    {% if debug %}
    <script type="text/python" src="brython/frontend/main.py"></script>
    {% else %}
    <script type="text/javascript" src="{% static 'frontend/js/frontend.brython.js' %}"></script>
    <script type="text/python">
        from frontend import main
        main.display()  # call entry point from main
    </script>
    {% endif %}
</head>

<body onload="brython({% if debug %}{debug: 1, pythonpath: ['/brython/']}{% endif %})">
</body>

The frontend application Python files are bundled into frontend.brython.js, so there is no need to load them separately from server.

Exclude from bundler

In the frontend app there are some files, which the bundler shouldn’t pack into output. For example the unittest files. You can exclude any module, with listing in the BRYTHON_BUNDLER_EXCLUDE settings:

# project/settings.py

BRYTHON_BUNDLER_EXCLUDE = [
    'frontend.apps'  # exclude frontend/apps.py
    'frontend.tests',  # exclude the frontend/tests/*.py
]