How to create a minimal standalone WEB application with Django

117 Views Asked by At

Using Pyramid framework a minimal standalone (i.e. not using external WEB server) WEB application can be created as follows:

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('Hello World!')

if __name__ == '__main__':
    with Configurator() as config:
        config.add_route('hello', '/')
        config.add_view(hello_world, route_name='hello')
        app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 1234, app)
    server.serve_forever()

How to achieve this with Django framework?

1

There are 1 best solutions below

2
AKX On

As my comment says, Django is not meant for this. However, in the interest of curiosity, this is approximately the smallest two-route Django app-project-amalgam I can think of:

import os

from django.http import HttpResponse
from django.urls import path

os.environ.setdefault("DJANGO_SETTINGS_MODULE", __name__)
ROOT_URLCONF = __name__
urlpatterns = [
    path("honk", lambda request: HttpResponse("Honk!")),
    path("", lambda request: HttpResponse("Hello World!")),
]
if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    from django.core.wsgi import get_wsgi_application

    server = make_server("", 8000, get_wsgi_application())
    server.serve_forever()

You can paste that into a file and run it with e.g. python minimal_django.py, then navigate to http://127.0.0.1:8000/ or http://127.0.0.1:8000/honk. (There is no database, no static file serving, no auto-reload, nothing. Just a hello and a honk.)

But again, Django is not meant for this sort of stuff! Don't do this at home!