# How to create a single-file Django server

**URL:** <https://forum.codeselfstudy.com/t/how-to-create-a-single-file-django-server/2491>\
**Category:** General Discussion\
**Tags:** python\
**Created:** [November 10, 2020, 9:02pm UTC](https://forum.codeselfstudy.com/t/how-to-create-a-single-file-django-server/2491 "2020-11-10T21:02:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Josh](https://forum.codeselfstudy.com/user_avatar/forum.codeselfstudy.com/josh/32/4_2.png) [@Josh](https://forum.codeselfstudy.com/u/Josh)\
**Post date:** [November 10, 2020, 9:02pm UTC](https://forum.codeselfstudy.com/t/how-to-create-a-single-file-django-server/2491/1 "2020-11-10T21:02:15Z")

</div>

I’ve been working on a couple of Django sites over the past week, so I went back to browse through my Django books to look things up.

There’s an interesting book called [_Lightweight Django_](https://www.oreilly.com/library/view/lightweight-django/9781491946275/) that shows how to create a minimal Django website with only one file. I wouldn’t build a site this way, but it’s an interesting experiment.

It only takes about 50 lines of code:

```python
import os
import sys

from django.conf import settings
from django.conf.urls import url
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse

# This loads environment variables from a .env file.
# See the .env-example file for instructions on how to create one.
from dotenv import load_dotenv
load_dotenv()

DEBUG = bool(os.environ.get("DEBUG", False))

SECRET_KEY = os.environ.get("SECRET_KEY")
if not SECRET_KEY:
    print("please add a secret key to your .env file")
    sys.exit()

ALLOWED_HOSTS = []

settings.configure(
    DEBUG=DEBUG,
    SECRET_KEY=SECRET_KEY,
    ALLOWED_HOSTS=ALLOWED_HOSTS,
    ROOT_URLCONF= __name__ ,
    MIDDLEWARE_CLASSES=(
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ),
)

def index(request):
    """This is a Django view that takes a request and sends a response.

    A Django "view" is equivalent to a "controller" in some other popular
    frameworks.
    """
    return HttpResponse("hello world")

# This is the router
urlpatterns = (
    url(r"^$", index),
)

application = get_wsgi_application()
if __name__ == " __main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

```

If anyone is interested, I put some instructions on how to run it in the README on Github:

> **[j127/single\_file\_django\_app](https://github.com/j127/single_file_django_app)**
>
> A single file Django site. Contribute to j127/single\_file\_django\_app development by creating an account on GitHub.

I’ve also been reading through some sections of [_Pro Django_](https://www.apress.com/us/book/9781430258094) which is useful.
