Why Use a Web Framework
You could write the cookbook site with nothing but Python: read raw request bytes, split out the path, open a database connection, glue strings of HTML together. It would work for a day. Then you would need logins, forms, protection against attacks, and a way to change the database safely, and you would have spent a month rebuilding what every site already needs.
The rule
A framework writes the plumbing every site needs; you write only your site.
Here is a bare-bones Python web app, with no framework at all:
def app(environ, start_response):
if environ["PATH_INFO"] == "/recipes/":
start_response("200 OK", [("Content-Type", "text/html")])
return [b"<h1>Recipes</h1>"]
start_response("404 Not Found", [("Content-Type", "text/html")])
return [b"Not found"]It handles one URL and already looks tangled. Now the Django version of the same idea:
urlpatterns = [path("recipes/", views.recipe_list)]
def recipe_list(request):
return render(request, "recipes/list.html", {"recipes": Recipe.objects.all()})Django took over the jobs that are identical everywhere:
- Routing: match a URL to the right code.
- Database access: the ORM turns Python into safe SQL.
- Templates: build HTML and escape anything a user typed.
- Forms: read, validate and redisplay submitted data.
- Security: CSRF protection, clickjacking headers, password hashing.
- Admin: a ready-made back office for your data.
Django is called batteries included because all of this ships in the box. Smaller "micro" frameworks such as Flask give you routing and let you choose the rest.
There is also a change in who is in charge. You no longer write a main loop that calls your code; Django calls your functions when a matching request arrives. That is called inversion of control.