Adding Docker to your Python andFlaskdevelopment environmentcan be confusing when you are just getting started with containers. Let'squickly get Docker installed and configured for developing Flask webapplications on your local system.
Set an environment variable for FLASKAPP. On Linux and macOS, use export set FLASKAPP=webapp; on Windows use set FLASKAPP=webapp. Navigate into the helloapp folder, then launch the program using python3 -m flask run (Linux/macOS) or python -m flask run (Windows). Create a container for a Flask app using the Docker extension.
Uses the app2 Flask instance in hello. FLASKAPP='hello:createapp('dev')' The createapp factory in hello is called with the string 'dev' as the argument. If FLASKAPP is not set, the command will try to import “app” or “wsgi” (as a “.py” file, or package) and try to detect an application instance or factory. Flask makes it possible for developers to build an API for whatever use case they might have. In this tutorial, we’ll learn how to set up Google Cloud, Cloud SQL, and App Engine to build a Flask API. Basically, the Flask app is pulling a Bokeh session, that’s running on the same machine, and serving it to the web. The problem is that the Bokeh app is served with ‘http’ and not ‘https’, which causes the browser to reject it. I assume that the solution lies in the Nginx config file, or the Flask app itself. Check out our new article: Flask Auth in One Line of Code! Flask is an awesome web framework for Python. It’s minimal, it’s simple, and best of all: easy to learn. Today I’m going to walk you through a tutorial for building your very first Flask web app! Just like the official Flask tutorial, you’ll be building your very own micro blog.
Our Tools
This tutorial is written for Python 3. It will work withPython 2 but I have not tested it with thesoon-to-be deprecated 2.7 version.
Docker for Mac is necessary.I recommend the stable release unless you have an explicit purpose for the edgechannel.
Within the Docker container we will use:
- Python 3, specifically theslim-3.6.5 versionfrom Docker Hub
- Flask version 1.0.2
All of the code for the Dockerfile and the Flask app are available open sourceunder the MIT license on GitHub under thedocker-flask-mac directoryof theblog-code-examplesrepository. Use the code for your own purposes as much as you like.
Installing Docker on macOS
Crypto portfolio app. We need to install Docker before we can spin up our Docker containers. If youalready have Docker for Mac installed and working, feel free to jump to thenext section.
On your Mac,download the Docker Community Edition (CE) for Macinstaller.
Find the newly-downloaded install within Finder and double click on the file.Follow the installation process, which includes granting administrative privilegesto the installer.
Open Terminal when the installer is done. Test your Docker installation with the
--version
flag:If Docker is installed correctly you should see the following output:
Note that Docker runs through a system agent you can find in the menu bar.
I have found the Docker agent to take up some precious battery lifeon my Macbook Pro. If I am not developing and need to max battery time I willclose down the agent and start it back up again when I am ready to code.
Now that Docker is installed let's get to running a container and writingour Flask application.
Dockerfile
Docker needs to know what we want in a container, which is where the
Dockerfile
comes in. Save the Dockerfile so that we can run our next command with the completedcontents of the file. On the commandline run:
The above
docker build
file uses the -t
flag to tag the image withthe name of flaskdock
.If the build worked successfully we can see the image in with the
docker image ls
command. Give that a try now:We should then see our tag name in the images list:
Our image is ready to load up as a container so we can write a quickFlask app that we will use to test our environment by running it withinthe container.
Coding A Simple Flask app
Time to put together a super simple 'Hello, World!' Flask web app to testrunning Python code within our Docker container. Within the currentproject directory, create a file named
app.py
with the following contents:The above 7 lines of code (not counting blank PEP8-compliant lines) inapp.pyallow our application to return a simple message when run with theFlask development server.
![Flask Flask](/uploads/1/3/4/1/134110910/553853105.jpg)
We need just one more file to specify our
Flask
dependency. Createa requirements.txt
file within the same directory as app.py
:Make sure both the
app.py
and requirements.txt
file are saved thenwe can give the code a try.Running the Container
Now that we have our image in hand along with the Python code in a filewe can run the image as a container with the
docker run
command. Executethe following command, making sure to replace the absolute path for thevolume to your own directory.If you receive the error
python: can't open file 'app.py': [Errno 2] No such file or directory
thenyou likely forgot to chance /Users/matt/devel/py/flaskdocker
to thedirectory where your project files, especially app.py
, are located.Everything worked when you see a simple text-based HTTP response like whatis shown above in the screenshot of my Chrome browser.
What's Next?
We just installed Docker and configured a Flask application to run inside acontainer. That is just the beginning of how you can integrate Docker intoyour workflow. I strongly recommend reading theDjango with PostgreSQL quickstartthat will introduce you to Docker Swarm as well as the core Docker containerservice.
Next up take a look at the Docker anddeployment pages for more related tutorials.
Questions? Let me know via a GitHubissue ticket on the Full Stack Python repository,on Twitter@fullstackpythonor @mattmakai.
Do you see a typo, syntax issue or just something that's confusing in thisblog post? Best music notation app. Forkthis page's source on GitHuband submit a pull request with a fix orfile an issue ticket on GitHub.
To add database functionality to a Flask app, we will use SQLAlchemy.
SQLAlchemy is a Python SQL toolkit and object relational mapper (ORM) that enables Python to communicate with the SQL database system you prefer: MySQL, PostgreSQL, SQLite, and others. An ORM converts data between incompatible systems (object structure in Python, table structure in SQL database). SQLAlchemy is basically a bridge between Python and a SQL database.
Flask-SQLAlchemy is an extension for Flask that adds SQLAlchemy to your Flask app.
Setup: Flask-SQLAlchemy¶
Set Flask App Mac Free
We will install the Flask-SQLAlchemy extension to enable us to work with a SQL database in Flask. There are many extensions for Flask; each one adds a different set of functions and capabilities. See the list of Flask extensions for more.
In Terminal, change into your Flask projects folder and activate your virtual environment there. Then install the extension at the command prompt — where you see
$
(Mac) or C:Usersyourname>
(Windows) --We will use SQLite for database examples here. Although it’s not necessary to use SQLAlchemy to interact with a SQLite database, learning to use SQLAlchemy gives you a skill set that can be applied to any SQL database system.
SQLAlchemy can bridge between Python and various different SQL database systems — some of which need an additional module, or library, to be installed. SQLite does not require an additional module — the
sqlite3
module is included in Python 3.x.Important
If you’re using a MySQL or PostgreSQL database, you will need to install a DBAPI module such as
psycopg2
(PostgreSQL) or PyMySQL
(MySQL).Basics of using a database with Flask¶
You’ll connect your Flask app to an existing SQL database. Connecting will require your own database username and database password, unless using SQLite.
Note
You can create the SQL database using Python, but that is not required. If you already have a database, all you need to worry about is how to connect it. If you do use Python to create a SQL database (and that’s an “if,” not a necessity), you will only do it once. You don’t create the same database again and again. Yes, this seems like a no-brainer — but you need to think about what your code is doing.
Your database may have one table, or more than one table. That depends on what you need, or the structure of the existing SQL database. You’ll need to know the table name(s). You’ll need to know the field names (column headings) in each table.
Your app might only read from your SQL database. You can write SQL queries to accomplish this — using Flask-SQLAlchemy commands to do so. Note that you won’t write a straightforward SQL query. Here is an example of Flask-SQLAlchemy syntax:
The Flask-SQLAlchemy statement to the right of the equals sign, above, is equivalent to this standard SQL statement:
It is assumed you are familiar with how to write basic SQL queries.
In addition to reading from your SQL database, your Flask app might allow people to write to the database. In that case, you will probably want people to log in securely. Alternatively, you might set up a Python script that updates your database on a regular schedule (e.g., writing in new records from a monthly data dump).
You might write a Python script to populate your database from the contents of a CSV file. This would be fairly simple if you only need to run it once. If you need to add records repeatedly (say, once per month) to an existing database, you might need to check whether you are duplicating records that are already there. If you need to check for existing records and update them, that’s more challenging. You can handle each of these tasks within Flask, using route functions.
If people are writing into your database, you will want to give them a web form, or forms, for doing so. See Flask: Web Forms if you need to create a web form in your Flask app.
You will not necessarily need forms if your app only reads from the database, but it is possible you’ll want to allow people to search for content, or to choose content from a menu using a
<select>
element in a form that queries the database. Then a form or forms will be required. Again, you will handle these tasks within Flask, using route functions.Of course, you’ll be using templates and all the other aspects of Flask covered in previous chapters here.
This overview should get you thinking about what you will need your Flask app to do, and how you will be querying the database, inserting new records, etc.
For all Python and SQL commands, refer to the links listed under “User’s Guide” in the Flask-SQLAlchemy documentation.
How to connect a database to a Flask app¶
The first step, assuming you have a database, is getting your app (or a starter script for your app) to connect to the database. Do this first.
Here’s a starter script for testing whether you can connect:
./python_code_examples/flask/databases/test_local_sqlite_db.py¶
The script above assumes that a SQLite database file (see filename on line 14) is in the same directory as the
.py
file. The script will work with any SQLite database file.- Starter scripts for a MySQL database connection are here. More about this below.
Note that line 16 is the key to the connection — it contains the database connection string, which will be different depending on which SQL database system you are connecting to. The SQLite connection string is simpler than the others, so be sure to read on if you’re using MySQL, PostgreSQL, or another system.
Run the script above:
Set Flask App Mac Pro
Open
http://localhost:5000
in your web browser. If you see the text “It works.” — then all is well. Otherwise, you’ll see an error message that should enable you to resolve the problem.SQLite resources¶
SQLite is a SQL database engine that is especially easy to work with because the database — regardless of its size or how many tables it might include — is in a single
.db
file. You can copy the file, upload it to a server, and so on — it is a standalone file.Unlike other database systems, a SQLite database does not have a username or password for access to the database itself.
Set Flask App Mac Download
- Download and install SQLite for your operating system (note: MacOS already has SQLite)
- Download the free DB Browser for SQLite (you can easily create tables by importing CSV files) — use this to create a new database, add tables, set data types for columns, etc.
- SQLite can be used without SQLAlchemy: Using SQLite3 with Flask
Connecting to a MySQL database¶
Two scripts are provided to test a connection to a MySQL database. They are here. An additional Python module must be installed — PyMySQL — and a username and password must be included in the connection string (even an empty password has a place).
In addition, when running the MySQL database locally, a socket string must be included. This string will be very different on MacOS and Windows.
If you do not want to run the database locally, but instead you have the database on a remote server — while you are writing your Flask app (and testing it) on your own computer — you will need to remotely connect to your MySQL database.
The connection string¶
The database connection string requires a strict syntax, or it will not work. The SQLite string is by far the simplest:
That assumes the
.db
file is adjacent to your .py
file. If not, write the path as needed.For other database systems, the connection string will be more complex:
Note, that example is for MySQL only; the protocol will be different for, say, PostgreSQL.
Setting environment variables¶
Instead of including username, password, and the whole database connection string within a Python script, you can set the complete string as an environment variable. Note that the connection string must be complete and correct for your configuration, as discussed in the previous section.
If you set an environment variable for the connection string, then add the following lines near the top of your script:
Eliminate all lines that refer to username, password, server, and database name.
Change the
app.config
statement to this:Look up how to set an environment variable for your operating system.
Note
os
is a built-in Python module.When setting up a Flask app on a server, there will be an option to set environment variables there. The lines in the Flask script referring to the environment variable will not change.
Important
Only one environment variable on your computer, or in an app, can be named
DATABASE_URL
— it’s a variable name, so you can change the string to something else, and you can set as many different variables as you need.Note
If you’re using a SQLite database, don’t bother with environment variables.
What could go wrong?¶
If you cannot get your Flask app to connect to your database, check the following:
- You forgot to install something (Flask-SQLAlchemy, or PyMySQL, etc.) in your Python virtual environment.
- Your virtual environment has not been activated.
- Your username and/or password for the database are wrong.
- Your database name is incorrect.
- On a remote server, permissions for the database user are not set correctly.
- For a local database, the socket does not match what you need on your computer.
- For a local MySQL database, you have not started the MySQL server.
Summary¶
This has been a basic introduction to getting started with Flask-SQLAlchemy and databases in Flask. The first step is to make sure you are able to connect successfully to the database you want to use.
A successful connection depends on which type of SQL system your database was built in. In this chapter, SQLite and MySQL are covered. PostgreSQL is another popular option but not covered here.
Creating a database from scratch is not covered here.
The following two chapters cover reading from or writing to the database.
.