11

Creating a Simple Flask Web Application

 3 years ago
source link: https://www.patricksoftwareblog.com/creating-a-simple-flask-web-application/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Overview

This blog posts is the first in a series of posts illustrating how I created my Kennedy Family Recipes application using the Flask framework.  This post will show you how to create a simple Flask web application, including setting up a virtual environment, getting the “Hello World!” to display, and getting slightly more advanced with HTML/CSS.

Virtual Environment

I’ve always found it really beneficial to create separate virtual environments for each of the Python projects that I’m working on.  Using the ‘virtualenvwrapper’ package just makes using virtual environments so easy… check out my blog post on Virtual Environments for how to setup ‘virtualenvwrapper’.

To get started, create a new directory in the workspace that you use for developing Python projects:

$ mkdir flask_family_recipe_project

Next, navigate into that directory and determine where your installation of python3 is located (yes, please use python3! The end of life (EOL) for python2 is rapidly approaching in 2020):

$ which python3
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3

With this information in hand, create a new virtual environment (named ffr_env, as a shortcut for Flask Family Recipes environment) with python3 specified as the version of python to use:

$ cd flask_family_recipe_project
$ mkvirtualenv --python=/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 ffr_env
Running virtualenv with interpreter /Library/Frameworks/Python.framework/Versions/3.4/bin/python3
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.4'
New python executable in ffr_env/bin/python3
Also creating executable in ffr_env/bin/python
Installing setuptools, pip, wheel...done.

Let’s double-check that python3 is actually the default python interpreter in our virtual environment:

(ffr_env) $ python --version
Python 3.4.3

You should now see the ‘ffr_env’ tag to the left of your prompt, which indicates that you are working within the newly created virtual environment:

(ffr_env) $

Since we’re going to be using the Flask framework, it’s a good idea to install the Flask package for the Python Package Index (PyPI) using pip:

(ffr_env) $ pip install flask

This command will install a number of additional packages that Flask is dependent on.  Since we’ve got a decent collection of packages installed, now is a good time to save the configuration of all the Python packages:

(ffr_env) $ pip freeze > requirements.txt

This command saves the exact version of each installed Python package to a simple text file.  This is so powerful when you decide to install this project on a production server or if you add a collaborator(s) to your project.  Here’s an example of what my requirements.txt file looks like:

click==6.6
Flask==0.11.1
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.11.10

Directory/File Structure

Here is the structure of our project that we will be starting off with:

$ tree
.
├── project
│   ├── __init__.py
│   ├── static
│   ├── templates
│   └── views.py
├── requirements.txt
└── run.py

The ‘project’ directory will be used to store most of the functionality of the application at this point in the development (we’ll be switching to use Blueprints very soon).  The ‘__init__.py’ file in this directory not only indicates to the Python interpreter that this directory is a Python package, but it also creates the instance of the Flask module:

#################
#### imports ####
#################
from flask import Flask
################
#### config ####
################
app = Flask(__name__)
from . import views

The ‘views.py’ file in the ‘project’ directory is used to store the initial routes for our web application.  This is one of the great parts of Flask; you can easily see how a address for a webpage is linked directly to a function within your application.  To get started, here’s a simple function that just returns the famous “Hello World!” when the user goes to the main address of the site (i.e., ‘/’):

from . import app
@app.route('/')
def index():
return "Hello World!”

Finally, the ‘run.py’ file in the top-level directory simply calls the run() method for the instance of the Flask module that was created in the ‘__init__.py’ file:

# run.py
# Add your settings here... this is a temporary location, as the settings for a Flask app
# should be stored separate from your main program.
DEBUG = True
from project import app
if __name__ == "__main__":
app.run()

That’s it!  You’ve got everything you need to run a simple Flask web application.  Flask provides a really nice development server to allow you to test your application on your local machine.  Make sure you are in your top-level directory and run the ‘run.py’ file:

$ pwd
.../flask_family_recipe_project
$ python run.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

You can now open your favorite web browser (Chrome, Safari, etc.) and navigate to either http://127.0.0.1:5000/ or localhost:5000/ (equivalent addresses) to see the “Hello World!” display.

For extra credit, check out what gets written to the console after you navigate to the site:

127.0.0.1 – – [16/Jun/2016 22:13:28] “GET / HTTP/1.1” 200 –

This is showing that you’re executing a HTTP GET request to your web application, which makes sense as you’re getting the “Hello World!” response defined by the index() function in “views.py”.  The console output provides a nice check of what your application is doing at a high-level as you start adding more and more complexity into your application.

Adding HTML/CSS Files

Having the index() function return “Hello World!” is a nice example to get started, but it is unrealistic to have a function return actual text to display…. this process should utilize HTML and CSS files.  If you are unfamiliar with HTML and/or CSS, then I’d highly recommend the HTML/CSS course from Codecademy.  I am still shocked by how much HTML (and to a lesser degree CSS) that I’ve had to written for a web application that I thought I was going to be writing in Python!

In the directory structure from above, I already had the ‘static’ directory listed for storing CSS files and the ‘templates’ directory for storing the HTML-ish files.  The ‘templates’ directory is not called ‘HTML’ as you will actually be creating template files that are based on HTML but can also include Python code.  These template files are then processed by the Jinja2 templating engine to generate the HTML that is sent to the user.  If you check the ‘requirements.txt’ file, you’ll see that Flask includes the Jinja2 module as a dependency as this is a core piece of the Flask framework.

For the first HTML file to create a simple site, create a new file called ‘index.html’ in the templates directory with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Kennedy Family Recipe App">
<meta name="author" content="Patrick Kennedy">
<title>Kennedy Family Recipe App</title>
<!-- styles -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
</head>
<body>
<h1>Welcome to the Kennedy Family Recipe App!</h1>
This site describes our favorite family recipes!
<h2>Breakfast Recipes</h2>
<h2>Lunch Recipes</h2>
<h2>Dinner Recipes</h2>
<h2>Dessert Recipes</h2>
</body>
</html>

Feel free to change the name of your site to something more applicable to you!  While this looks like a standard HTML file, check out the one line that links in the stylesheet:

This is the first example of including some Python code (the function url_for()) to enhance a basic HTML file for our web application.  The url_for() function provides the URL address for the specified directory/file and the Jinja2 templating engine will use this to generate a standard HTML file.

Just to get started with a simple CSS file, create a new file called ‘main.css’ in the ‘./project/static/css’ folder:

body {
padding: 60px 0;
background: #ffffff;
}

Now that we have the HTML/CSS files in place, we need to update the ‘views.py’ file to actually utilize these files.  The ‘views.py’ file should be changed to:

from . import app
from flask import render_template
@app.route('/')
def index():
return render_template('index.html’)

Instead of just returning “Hello World!”, the index() function is now rendering a HTML page based on the ‘index.html’ template.

As before, make sure you are in your top-level directory and run the ‘run.py’ file:

$ pwd
.../flask_family_recipe_project
$ python run.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

You should see the following in your web browser when you navigate to http://127.0.0.1:5000/ or localhost:5000/ (refresh the page if you already navigated to here!):

Great first step!

Conclusion

This post illustrated how to set up a virtual environment for a Python project, install the Flask module, get the “Hello World!” application working, and expand to actually utilize HTML/CSS files for generating a page. This is a great start to a Flask web application and we’ll continue to expand on this project in this series.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK