w3resource

Create a Basic Web Server Project in Python: Flask vs. Django

Simple Web Server:

Build a basic web server using Flask or Django.

Input values:
None (Automated process to start the "web server").

Output value:
The output indicates the URL where the web server is accessible.

Example:

Input values:
None
Output value:
Web server started at http://127.0.0.1:5000/

Solution 1: Using Flask

Flask is a lightweight web framework that's easy to set up and perfect for building simple web servers.

Flask Setup Instructions

  • Install Flask using pip:
  • pip install flask
    
  • Create a file named web_app.py and add the following code:

Code:

# Solution 1: Simple Web Server Using Flask

from flask import Flask  # Import the Flask class from the flask module

# Create an instance of the Flask class
app = Flask(__name__)

# Define a route for the home page ('/') that will display a welcome message
@app.route('/')
def home():
    """Handle requests to the home page and return a welcome message."""
    return "Welcome to the Flask web server!"

# Main entry point to start the web server
if __name__ == "__main__":
    # Run the Flask web server on the default port 5000
    print("Web server started at http://127.0.0.1:5000/")
    app.run()

Run the Flask Web Server

To start the web server, run the following command in your terminal or command prompt:

python web_app.py

Output:

(base) C:\Users\ME>python web_app.py
Web server started at http://127.0.0.1:5000/
  • Serving Flask app 'web_app'
  • Debug mode: off
  • WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

  • Running on http://127.0.0.1:5000

Press CTRL+C to quit

Python: Flask web server.

Explanation:

  • Flask Setup: The 'Flask' class is imported to create a web server instance.
  • Route Definition: '@app.route('/')' decorator defines the route for the home page ('/'). The home function returns a welcome message when the home page is accessed.
  • Server Start: 'app.run()' starts the Flask web server on the default port ('5000').

Solution 2: Using Django

(base) C:\Users\ME>pip install django
Collecting django
  Downloading Django-5.1-py3-none-any.whl.metadata (4.2 kB)
Collecting asgiref<4,>=3.8.1 (from django)
  Downloading asgiref-3.8.1-py3-none-any.whl.metadata (9.3 kB)
Collecting sqlparse>=0.3.1 (from django)
  Downloading sqlparse-0.5.1-py3-none-any.whl.metadata (3.9 kB)
Requirement already satisfied: tzdata in i:\users\me\anaconda3\lib\site-packages (from django) (2023.3)
Downloading Django-5.1-py3-none-any.whl (8.2 MB)
8.2/8.2 MB 6.1 MB/s eta 0:00:00
Downloading asgiref-3.8.1-py3-none-any.whl (23 kB)
Downloading sqlparse-0.5.1-py3-none-any.whl (44 kB)
44.2/44.2 kB 2.3 MB/s eta 0:00:00
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.8.1 django-5.1 sqlparse-0.5.1
(base) C:\Users\ME>django-admin startproject myproject

(base) C:\Users\ME>cd myproject

(base) C:\Users\ME\myproject>python manage.py startapp myapp

(base) C:\Users\ME\myproject>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
September 01, 2024 - 18:55:42
Django version 5.1, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

Code(myproject/settings.py):

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',  # Add the new app to the installed apps
]

Code(myapp/views.py):

# Solution 2: Simple Web Server Using Django

from django.http import HttpResponse  # Import HttpResponse to return an HTTP response

# Define a view for the home page that returns a welcome message
def home(request):
    """Handle requests to the home page and return a welcome message."""
    return HttpResponse("Welcome to the Django web server!")

Code (myproject/urls.py):

from django.contrib import admin
from django.urls import path
from myapp.views import home  # Import the home view

urlpatterns = [
    path('admin/', admin.site.urls),  # Admin route
    path('', home),  # Home page route
]

Output:

Python: django.

Explanation:

  • Django Project and App Setup: Create a Django project and app using Django's command-line tools.
  • View Definition: The home function in myapp/views.py handles requests to the home page and returns a welcome message using HttpResponse.
  • URL Mapping: In myproject/urls.py, the URL pattern for the home page ('') is mapped to the home view.
  • Server Start: python manage.py runserver starts the Django development server on the default port (8000).

Summary of Differences

  • Flask Solution
    • Simple and Lightweight: Uses Flask, a lightweight web framework, ideal for small web servers or simple projects.
    • Minimal Setup: Requires only a single file (app.py) and minimal code to define routes and start the server.
    • Faster Start: Easier to set up and run quickly for basic use cases.
  • Django Solution
    • Full-Featured Framework: Uses Django, a robust web framework with built-in features like admin panel, authentication, etc.
    • More Setup Required: Involves creating a project and an app, adding views, and configuring URLs.
    • Scalability and Extensibility: Suitable for larger projects that require a more structured approach and additional features.

Note:
Both solutions effectively create a simple web server, with Flask being more suitable for quick and lightweight tasks, and Django offering a comprehensive structure for more complex applications.



Become a Patron!

Follow us on Facebook and Twitter for latest update.