A Brief Look at Web Development in Python

Since 2003, Python has ranked in the top 10 programming languages to learn and its ranking has been consistently improving ever since. According to a statistic, Python is one of the top 5 languages to learn in 2019 and has become an essential part of the programming community, thanks to its simplicity, flexibility, robustness, ease of use, compatibility, speed, and versatility. Furthermore, tech giants like Instagram, Spotify, and Google base, at least in part, their architecture in Python.

In short, Python has become a central component of the programming world with the rise of Silicon Valley and Wall Street poster child: Fintech. The reasons are many, but Python offers the security and scalability sought by the digital-first-approach trend assumed by a considerable portion of the business and financial sectors.

Python can be used to perform a ton of different tasks, ranging from machine learning and data science to robotics and hardware programming. In this article we will focus on how Python can be used for web development.

Web Development Using Python

Python offers something for everyone through its many frameworks and features. A framework is a bundle of packages and modules that provide an abstraction, or generic functionality, that can be selectively changed to create application-specific software.

But how do you know which web framework is right for you? For full-fledged web applications, Django and Pyramid are typically the way to go. For better control and visualization or prototyping an app, Web2py or Flask may have something to offer to your project. CheeryPy is a must for simple, minimalist solutions. Tornado will handle 10,000 or more concurrent connections to your app at the same time while Dash is the perfect choice for analytical applications.

Over the next few sections, we'll provide a brief overview for three of the most popular selections by developers: Django, Pyramid, and Flask. After the overview we'll show the most popular framework, Django, in action through the use of an example login system.

Django

This framework is the embodiment of the "batteries included" phrase. Defined as "the web framework for perfectionists with deadlines". Its built-in features allow for a wide range of web applications, like database applications, chat-bots, IoT solutions, etc. Given it's popularity, you'll often see Django as the topic of a web development course.

Its DRY (Don't Repeat Yourself) philosophy not only allows, but also promotes, the reuse of code, greatly reducing the coding time. Furthermore, its modular/decoupled architecture allows seamless modification of the code components, allowing you to add or remove components as much as needed with little to no effort.

Django also possesses something called an ORM (Object-Relational Mapping), which makes it highly compatible with most of the popular databases, like SQL or Oracle, and also allows it to work with several databases at once.

Finally, Django is SEO (Search Engine Optimization) friendly. For example, it allows the reduction of the page loading time through techniques like caching templates and compressing JavaScript files.

Pyramid

This framework defines itself as "not too small, not too big, just right". Pyramid is a finishing-focused framework with the ability to start small, allowing you to code a solid foundation for your solution, and then to scale it up as needed. It is similar to Django in its compatibility with small and large applications, but sets itself apart from Django in its complexity.

While on its own it can be considered a lean option when compared to other frameworks, Pyramid shines with its plugin system, allowing developers to plug-in whatever is needed, which allows for the implementation of multiple solutions for a given task.

Pyramid is even ideal for single-file applications, flexible authentication, and authorization or apps oriented to view predicates.

Flask

While Pyramid and Django share the same core philosophy, Flask goes in the other direction. If the end goal is something simple, manageable, and customizable, I'd suggest that you always use Flask instead of using an overkill power horse like Django. Flask is heavily based on Jinja 2 templating and the Werkzeug WSGI (Web Server Gateway Interface) toolkit.

Self-defined as a micro-framework, Flask is tailored to small-scale solutions, like simple apps or API's, where lean functionality is a top priority. Flask is also the most used micro-framework for creating prototypes. When building a working application from the ground up in a short amount of time, it takes priority over the management of the said application in the long term.

Simple Login System with Django

In this section, we are going to explain how to create a simple login system with the Django framework. While a lot of things happen "offstage", and many things can be customized to the developers' liking, only the most basic steps will be explained in order to demonstrate how easy it is to develop applications with the Django framework.

Installing Django

For this example, the PIP module needs to be installed. Once that it is done, Django can be installed and a new project can be created as follows:

$ python3 -m venv ~/.virtualenvs/dProject # Creates a virtual environment named dProject
$ source ~/.virtualenvs/dProject/bin/activate # A path is created
(dProject) $ pip install django # Django is installed
(dProject) $ django-admin.py startproject LoginProject_D # The project is created with the name LoginProject_D 
(dProject) $ ./manage.py migrate # Migrate creates a new SQLite database
(dProject) $ ./manage.py runserver # Calls the local server
(dProject) $ ./manage.py startapp dProject # This creates a dedicated app that will allow the making of a view and url registration.

After this is done, the project can be previewed in a browser via the "http://127.0.0.1:8000" address. The Django welcome screen will load in the browser, indicating that installation was a success.

Django's Auth App

When a project is created, Django installs the "auth" app by default. This can be confirmed by checking the file settings.py, which is created automatically with the new project, under the "INSTALLED_APPS" section as follows:

INSTALLED_APPS = [
    …
    'django.contrib.admin',
    'django.contrib.auth', # Here it is! Note that several built-in apps are included in this section.
   …
]

Django-auth, or django.contrib.auth, is the Django framework's built-in authentication system, and contains its default models. This app is responsible for user authentication, permissions, and groups.

In order to use the "auth" app, we need to add it to the project-level file urls.py:

# Importing this module will allow us to set the routes login and logout views
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views 

# This section adds Django site authentication urls (for login, logout, password management)
urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^logout/$', auth_views.logout, name='logout'),
    url(r'^admin/', admin.site.urls),
    path('dProject/', include('django.contrib.auth.urls')),
]

The "auth" app provides us with the following URLs, each one associated with "auth" views, allowing us to use them by simply creating their view templates:

dProject/login/ [name='login']
dProject/logout/ [name='logout']
dProject/password_change/ [name='password_change']
dProject/password_change/done/ [name='password_change_done']
dProject/password_reset/ [name='password_reset']
dProject/password_reset/done/ [name='password_reset_done']
dProject/reset/<uidb64>/<token>/ [name='password_reset_confirm']
dProject/reset/done/ [name='password_reset_complete']

The django.contrib.auth.views.login view will create the registration/login.html template by default. This creates a folder named REGISTRATION with a login.html template within. The following block of code is a basic login template that can be used:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

{% extends 'base.html' %}

{% block title %}Login{% endblock %}

{% block content %}
  <h2>Login</h2>
  <form method="post"> #This is a standard form to send data.
    {% csrf_token %} #Security tag to prevent <a target="_blank" href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)">XSS Attacks</a>, among other concerns.
    {{ form.as_p }} #Outputs the form's contents between paragraph tags.
    <button type="submit">Login</button> #A submit button. 
  </form>
{% endblock %}

Finally, we set the project to look for the "templates" folder through the settings.py file, updating DIRS:

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

Voilà! A simple login page that can correctly authenticate a user through a username and password validation.

Conclusion

Python has been widely used for server-side programming, owing to its dynamic website creation capabilities. This language is widely used for fast prototyping and building highly scalable web applications by technology leaders like Google and even NASA!

Python is, without a doubt, a must when taking a digital-first approach to staying competitive, which is further enhanced by the meteoric rise of the fin-tech industry.

Furthermore, these Python frameworks reduce the development effort through the provision of a variety of built-in functionalities. The only challenge would be which one to use, tailored to specific needs for better results.

Last Updated: July 30th, 2024
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms