Table of Contents
Have you ever heard anything about Python? If you're reading this, I bet you do! Python is an interpreted, high-level, general-purpose programming language with an object-oriented approach: it was created by Guido van Rossum in 1991 and constantly updated ever since. It's dynamically typed and supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
Python went through two major upgrades: the first in 2000, with the release of the 2.0 version, which introduced a garbage collection system capable of collecting reference cycles; the second in 2008 with the release of Python 3.0, which was a major revision - mostly backward-incompatible - of the language. Following the Python 3.0 release, most developers chose to stick to the 2.x version, which eventually led to extended support for Python 2.7 (the last release in the 2.x series) up to 2020.
As of today, all the main resources for Python and CPython (an open-source implementation of Python) are maintained and managed by the Python Software Foundation, a non-profit organization.
Python 2 vs Python 3
Python 2 and Python 3 are the two major versions of Python that are still used nowadays. These two versions are quite different: although Python 3 arguably has a better syntax, is more semantically correct and supports newer features, most developers chose to stick with Phyton 2 until recent years thanks to a much wider database of libraries and resources available on the web. Although there still is a bit of a debate in the coding community about which Python version was the best one to learn nowadays (Python 2.7 vs 3.5), there is now a general consensus on considering Python 3 the most appropriate choice for newcomers and also for those who want to update their coding skills.
For this very reason, in this quick tutorial, we're going to use the Python 3 syntax.
Console, Desktop, or Web?
Just like most programming languages, such as Java, C# and so on, Python can be used for a number of different purposes. The most common scenarios are:
- Console Applications: console applications are programs designed to be used via a text-only computer interface, such as a text terminal, the command line interface of some operating systems (Unix, DOS, etc.). Common examples include openssl, ping, telnet, defrag, chkdsk, and the likes.
- Desktop Applications: desktop applications are programs designed to be used via a Graphical User Interface (GUI): such GUI can either be designed by making use of the operating system native libraries or made from scratch using the language native elements (or specifically designed GUI frameworks). Typical examples of desktop applications include Photoshop, Thunderbird, Chrome, and so on. Desktop application development dominated the software world for many years and are still widely used, even if the broadband + Internet combo is making web-based applications more appealing year after year.
- Web Applications: web applications or web apps are client-server computer programs where the client - including the user interface (UI) and the client-side logic - runs in a web browser: common examples include webmail (such as GMail), e-banking websites, and so on. On a more general basis, we could say that most interactive websites can be defined as web applications, from the CMS who can help you to write an essay on time management to more complex, fully packaged products such as WordPress and Joomla.
In this tutorial, for the sake of simplicity, we'll talk about the latter: therefore, our Hello World sample will be a (minimal) Web Application.
Python Web Frameworks
The first thing you have to do before starting is to pick a decent Python Web Frameworks: although you can write Python using any text editor (including Notepad), you should definitely stick with a GUI framework to benefit from very useful features such as syntax highlighting, built-in compiler/debugger, folder tree lists, windows tiling, and so on.
These are the most popular high-level web frameworks for Python available nowadays.
Django
The Web framework for perfectionists (with deadlines). Django makes it easier to build better Web apps more quickly and with less code. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performing, elegant Web applications quickly. Django focuses on automating as much as possible and adhering to the DRY (Don't Repeat Yourself) principle.
TurboGears
The rapid Web development web framework you've been looking for. Combines SQLAlchemy (Model) or Ming (MongoDB Model), Genshi (View), Repoze and Tosca Widgets. Create a database-driven, ready-to-extend application in minutes. All with designer-friendly templates, easy AJAX on the browser side and on the server side, with an incredibly powerful and flexible Object Relational Mapper (ORM), and with code that is as natural as writing a function. After reviewing the Documentation, check out the Tutorials
web2py
All in one package with no further dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface, but not required. web2py has no configuration files, requires no installation, can be run off a USB drive: it uses Python for the Model, View and the Controller. It main features include: a built-in ticketing system to manage errors; internationalization engine and pluralization, caching system; flexible authentication system (LDAP, MySQL, janrain & more); Available for Linux, BSD, Windows, and Mac OSX; works with MySQL, PostgreSQL, SQLite , Firebird, Oracle, MSSQL and the Google App Engine via an ORM abstraction layer.
Hello World in Python
Before installing Django, let’s see how we can generate a sample "Hello World" web page using Python.
From a Linux shell, open your favorite text editor (mine is nano, but you can also use vi or anything else) and type the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#!/usr/bin/env python import textwrap from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class HelloRequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path != '/': self.send_error(404, "Object not found") return self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() response_text = textwrap.dedent('''\ <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, World!</h1> <p>... Here we are!</p> </body> </html> ''') self.wfile.write(response_text.encode('utf-8')) server_address = ('', 8000) httpd = HTTPServer(server_address, HelloRequestHandler) httpd.serve_forever() |
... And that's pretty much it!
This simple program can be executed and then tested by visiting http://localhost:8000/ with any browser.
Hello World with Django
Writing a Hello World sample web page with Django is definitely more difficult than doing it using blue Python... But there's a tremendous advantage in doing that: the scaling factor. If you're dealing with a more complex web application, you won't be able to write it using pure Python without losing control over the code pretty soon. The good thing about Django is that, once you learn the basics, you'll be able to deal with your projects in a comfortable fashion and with a great learning curve.
Installing Django
The first thing to do is to make sure that you have Django installed. Assuming you are using virtualenv, the following command should suffice:
1 |
> pip install django |
Right after that, we need to create a Django project and a Django app:
1 2 3 |
> django-admin startproject hello_world_project > cd hello_world_project > python manage.py startapp hello |
We now have a project called hello_world_project and an app named hello. When we executed python manage.py startapp hello, Django created a folder called hello with several files inside it. In this sample tutorial we won't use most of these files, hence we can delete them: the file that can be deleted are the following:
- hello/admin.py
- hello/models.py
- the whole hello/migrations folder.
Writing the code
Once done, edit the hello/views.py file in the following way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import textwrap from django.http import HttpResponse from django.views.generic.base import View class HomePageView(View): def dispatch(request, *args, **kwargs): response_text = textwrap.dedent('''\ <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, World!</h1> <p>... Here we are!</p> </body> </html> ''') return HttpResponse(response_text) |
As we can see, we have basically created a Python class, which in Django is called a view. More specifically, this will be the class that will output the same HTML snippet we previously wrote using pure Python.
Right after that, create a new hello/urls.py file with the following contents:
1 2 3 4 5 6 7 8 9 |
from django.conf.urls import patterns, url from hello.views import HomePageView urlpatterns = patterns( '', url(r'^$', HomePageView.as_view(), name='home'), ) |
Next, edit the hello_world_project/urls.py file to make it looks like this:
1 2 3 4 5 6 7 |
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'', include('hello.urls')), ) |
As we can see by looking at the code, these urls.py files are the routing system that will be used by Django to understand what view to load whenever a specific URL is requested by a user. In a nutshell, we just told to our main project routing file (hello_world_project/urls.py) to route all the requests pointing to the site root to the app routing file (hello/urls.py), which in turn will point to the HomePageView view, that will then be executed - eventually returning the HTML content.
The last thing we need to do is to edit the hello_world_project/settings.py file and remove some unused stuff that could prevent our sample web application from running.
Around line 30, find a variable called INSTALLED_APPS: remove the first four items of the sequence and add 'hello' to the end.
1 2 3 4 5 |
INSTALLED_APPS = ( 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', ) |
Immediately after these lines, find the MIDDLEWARE_CLASSES variable and remove the line containing SessionAuthenticationMiddleware.
1 2 3 4 5 6 7 8 |
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) |
That's it: our Django web application is ready. You can start it by typing the following:
1 |
> python manage.py runserver |
And then visit http://localhost:8000/ in your browser to see it in action.
Conclusion
That's pretty much about it. If you are interested in Python and you would like to go further, we strongly suggest to visit one of the following resources:
... and so on. See you next time, and... happy coding!