create a web app in python

There are several ways to create web applications in Python. Two popular frameworks are Flask and Django.

Flask:

Flask is a lightweight web framework that is easy to learn and use. To create a simple web app using Flask, follow these steps:

  1. Install Flask using pip:

    main.py
    pip install Flask
    
    18 chars
    2 lines
  2. Create a new Python file and import the Flask module:

    main.py
    from flask import Flask
    app = Flask(__name__)
    
    46 chars
    3 lines
  3. Define the routes of your web app using the @app.route decorator:

    main.py
    @app.route('/')
    def home():
        return 'Hello, World!'
    
    55 chars
    4 lines
  4. Run the app using the app.run method:

    main.py
    if __name__ == '__main__':
        app.run()
    
    41 chars
    3 lines
  5. Navigate to http://localhost:5000/ in your web browser to see the "Hello, World!" message.

Django

Django is a more robust web framework that provides many features out of the box. To create a simple web app using Django, follow these steps:

  1. Install Django using pip:

    main.py
    pip install django
    
    19 chars
    2 lines
  2. Create a new Django project:

    main.py
    django-admin startproject projectname
    
    38 chars
    2 lines
  3. Create a new Django app:

    main.py
    python manage.py startapp appname
    
    34 chars
    2 lines
  4. Define the views of your web app in the app's views.py file:

    main.py
    from django.http import HttpResponse
    
    def home(request):
        return HttpResponse("Hello, World!")
    
    98 chars
    5 lines
  5. Define the URL patterns for your web app in the app's urls.py file:

    main.py
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.home, name='home'),
    ]
    
    107 chars
    7 lines
  6. Run the app using the Django development server:

    main.py
    python manage.py runserver
    
    27 chars
    2 lines
  7. Navigate to http://localhost:8000/ in your web browser to see the "Hello, World!" message.

gistlibby LogSnag