A Brief Look at Web Development in Python

Introduction

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 figure of the programming and business 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.

Though Python can be used to perform a variety of tasks ranging from machine learning and data science to robotics and hardware programming, in this article we will study how Python can be used for web development.

Web Development Using Python

Python offers something for everyone through its many frameworks. 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 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.

In this article, we will provide a brief overview for three of the most popular selections by developers and programming companies alike: 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 such as database applications, chat-bots, GPS solutions, etc.

Its DRY (Don't Repeat Yourself) philosophy not only allows, but also promotes, the reuse of code, slicing the coding time in half. 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 not only highly compatible with most of the popular databases like SQL or Oracle but 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/features like caching templates and compressing JavaScript.

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.

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:

{% 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 %}
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!

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: September 13th, 2023
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.

Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms