Python Web Development
What is Web Development in Python?
Being a dynamic language for the application of the internet, Python has a lot of web frameworks and tools to help one in the process of making web applications.
Flask Web Development:
Installing Flask:
pip install Flask
Creating a Simple Flask App:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
- Save this code in a file, e.g., app.py.
- Run the app with python app.py.
- Open a web browser and go to http://127.0.0.1:5000/ to see "Hello, World!".
Adding Dynamic Content:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html', name='John')
if __name__ == '__main__':
app.run(debug=True)
- Create an templates folder in the same directory as your app.py.
- Inside templates, create index.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Example</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
Django Web Development:
Installing Django:
pip install Django
Creating a Django Project:
django-admin startproject myproject
Creating a Django App:
cd myproject
python manage.py startapp myapp
Defining Models:
In myapp/models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
def __str__(self):
return self.title
Running Migrations:
python manage.py makemigrations
python manage.py migrate
Creating Views:
In myapp/views.py:
from django.shortcuts import render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'myapp/book_list.html', {'books': books})
Creating Templates:
Create myapp/templates/myapp/book_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Django Example</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }}</li>
{% endfor %}
</ul>
</body>
</html>
Configuring URLs:
In myproject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
In myapp/urls.py:
from django.urls import path
from .views import book_list
urlpatterns = [
path('books/', book_list, name='book_list'),
]
Now, run the development server:
python manage.py runserver
Visit http://127.0.0.1:8000/books/ to see the list of books.
These examples provide a basic introduction to web development with Flask and Django.
Depending on your project requirements, you can choose the framework that best suits your needs.