Book Image

Flask By Example

By : Gareth Dwyer
Book Image

Flask By Example

By: Gareth Dwyer

Overview of this book

This book will take you on a journey from learning about web development using Flask to building fully functional web applications. In the first major project, we develop a dynamic Headlines application that displays the latest news headlines along with up-to-date currency and weather information. In project two, we build a Crime Map application that is backed by a MySQL database, allowing users to submit information on and the location of crimes in order to plot danger zones and other crime trends within an area. In the final project, we combine Flask with more modern technologies, such as Twitter's Bootstrap and the NoSQL database MongoDB, to create a Waiter Caller application that allows restaurant patrons to easily call a waiter to their table. This pragmatic tutorial will keep you engaged as you learn the crux of Flask by working on challenging real-world applications.
Table of Contents (20 chapters)
Flask By Example
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Writing "Hello, World!"


Now, we'll create a basic web page and serve it using Flask's built-in server to localhost. This means that we'll run a web server on our local machine that we can easily make requests to from our local machine. This is very useful for development but not suited for production applications. Later on, we'll take a look at how to serve Flask web applications using the popular Apache web server.

Writing the code

Our application will be a single Python file. Create a directory in your home directory called firstapp and a file inside this called hello.py. In the hello.py file, we'll write code to serve a web page comprising the static string "Hello, World!". The code looks as follows:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(port=5000, debug=True)

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

Let's break down what this does. The first line should be familiar; it simply imports Flask from the package flask. The second line creates an instance of the Flask object using our module's name as a parameter. Flask uses this to resolve resources, and in complex cases, one can use something other than __name__ here. For our purposes, we'll always use __name__, which links our module to the Flask object.

Line 3 is a Python decorator. Flask uses decorators for URL routing, so this line of code means that the function directly below it should be called whenever a user visits the main root page of our web application (which is defined by the single forward slash). If you are not familiar with decorators, these are beautiful Python shortcuts that seem a bit like black magic at first. In essence, they call a function that takes the function defined under the decorator (in our case, index()) and returns a modified function.

The next two lines should also seem familiar. They define a very simple function that returns our message. As this function is called by Flask when a user visits our application, the return value of this will be what is sent in response to a user who requests our landing page.

Line 6 is a Python idiom with which you are probably familiar. This is a simple conditional statement that evaluates to True if our application is run directly. It is used to prevent Python scripts from being unintentionally run when they are imported into other Python files.

The final line kicks off Flask's development server on our local machine. We set it to run on port 5000 (we'll use port 80 for production) and set debug to True, which will help us see detailed errors directly in our web browser.

Running the code

To run our development web server, simply fire up a terminal and run the hello.py file. If you used the same structure outlined in the previous section, the commands will be as follows:

cd firstapp/hello
python hello.py

You should get an output similar to that in the following screenshot:

Also, you should see the process continue to run. This is our web server listening for requests. So, let's make a request!

Fire up a web browser—I use Firefox, which comes packaged with Ubuntu—and navigate to localhost:5000.

The localhost part of the URL is a shortcut to the loopback address, usually 127.0.0.1, which asks your computer to make the web request to itself. The number after the colon (5000) is the port it should make the request to. By default, all HTTP (web) traffic is carried over port 80. For now, we'll use 5000 as it is unlikely to conflict with any existing services, but we'll change over to port 80 in production, which is conventional, so that you won't have to worry about the colon.

You should see the "Hello, World!" string displayed in your browser as in the following screenshot. Congratulations, you've built your first web application using Flask!