Create a new Django project in a single Python file

When creating a new Django project, django-admin startproject xxxthe command to generate a Django project directory

If you want to experience Django in a single file like Flask, or just want to build a minimal Django project separately for testing a certain function

This article provides a code template that does not use django-adminthe command to generate Django project files, and directly writes the configuration, routing and views of the Django project in a single Python source file

Create a new single.py file and fill in the following content

import sys

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

settings.configure(ALLOWED_HOSTS='*', ROOT_URLCONF=__name__)

django.setup()


def index(request):
    return HttpResponse("Hi!")


urlpatterns = [path('', index)]

app = get_wsgi_application()

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

Start the Django server on the command line

$ python3 single.py runserver
Performing system checks...

System check identified no issues (0 silenced).
September 30, 2022 - 10:39:46
Django version 3.2, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Then you can access 127.0.0.1:8000 in the browser

2022-09-30_10-40.png

Guess you like

Origin blog.csdn.net/jiang_huixin/article/details/127119877