CodeNewbie Community

Brandon Redmond
Brandon Redmond

Posted on

Getting Started with Flask

Introduction

Welcome to my multi-part article on how to build a basic React Application using a Flask API with GraphQL layer in-between.

  • Part 1 will focus on the basics of Python, Flask Web Framework, and how to connect it to a PostgreSQL Database.
  • Part 2, we will step into slightly more advanced Flask concepts and discuss how to use a Large Application File Structure, Flask Blueprints, and Flask Application Factory Format.
  • Part 3, we will build our models and connect our backend to GraphQL. Then we will use a code-first approach to build out our schemas and resolver functions.
  • Part 4, I will talk about how to create a basic React App for our frontend with Webpack5.
  • Part 5, I will talk about how to connect our React App to GraphQL to send data to the Flask API.

I was inspired to write these articles because of the difficulties I faced early in my journey to become a web developer. I was initially trying to build an application using both React and Flask web frameworks when I quickly realized the lack of information that existed on how to connect these two technologies into a single application. Also, I know that I learn best when I am explaining a concept (I used to be a teacher) so I am also using this as an outlet to help me better understand the fundamentals, so please feel free to comment if you have recommendations!

I started out learning how to code in Python and it was also what I used to teach my students when I was a High School Computer Science Teacher, so I wanted to build web applications using a language I was familiar with. Shortly after starting this journey, I understood that if I wanted to build modern and dynamic web applications then I would need Javascript and React. Most of the courses and information I found on these technologies only taught how to use Javascript on the backend using Node.js, so I had a hard time figuring out how to connect to two technologies. After hours of googling, reading through Stack Overflow forums, and simple trial and error, I eventually got the two technologies to talk to each other and successfully built my first React & Flask application. So Let’s get started.

Getting Started with Flask Basics

I will assume some knowledge throughout this article:

  • You should be comfortable with the basics of Python (basic data types, functions, importing files, classes, etc.).
  • I will be using the command line often to run commands for Flask and using the Python Shell to test some of our code. I typically develop on Linux, so I’ll use those commands.
  • Basic SQL, I will be using PostgreSQL (I chose this one because it is what I learned on.).
  • Basic HTML and CSS (I will be using SCSS here, but the syntax is the same as CSS more or less).

CREATING PROJECT DIRECTORY & VIRTUAL ENVIRONMENT

Let’s jump right into it. The first thing we’re going to want to do is create a project directory where we will store all of our files. Being organized is super important as a developer! I typically keep all of my projects in a Development folder inside the Documents folder. I’ll name my folder Flask_Project, but you can name it whatever you’d like.

Open up your terminal and enter the following. You may need to create the Development and Documents folder as well.

cd ~/Documents/Development
mkdir Flask_Project
cd Flask_Project
Enter fullscreen mode Exit fullscreen mode

Next, if you haven’t already, we can install python’s virtual environment package. I think using a virtual environment is very important. Sometimes we use different libraries for different projects that don’t mix well, or we need different versions. I think it’s a good habit to get into and definitely recommend using it. I’ll name my virtual environment flaskenv.

  • Install the venv library
    sudo apt install python3-venv

  • Create the flaskenv environment
    python3 -m venv flaskenv

  • Activate the virtual environment
    source flaskenv/bin/activate

If you want to deactivate your environment, just type deactivate in the terminal.
**On a side note, I typically use python’s virtualenvwrapper. It’s only slightly more difficult to set up, but makes working in virtual environments super easy. Once set up, you just need to type workon <name_of_env> and it’s activated. And it stores all your environments in one directory.

INSTALLING FLASK

Now that our environment is set up we can install Flask.

python3 -m pip3 install flask

We can get into the habit of adding all of our installed packages into a requirements.txt file. This will be useful if something happens to our virtualenv and we need to make another one and won’t have to remember all the libraries we installed.

pip3 freeze > requirements.txt

Now we can verify that Flask was actually installed. In the command line, we will open up the python shell and then import flask.

python3 
import flask
Enter fullscreen mode Exit fullscreen mode

If you haven’t received any error messages, then you know that flask was installed correctly. If you do receive an error message, you may have to uninstall flask and reinstall it, or python was never installed, etc. I’ll leave that to you.

BUILDING A SIMPLE WEB APPLICATION

One of the beautiful things about flask, is that you can have a super simple, functional web application in just 5 lines of code – I’ll show you in a second. It won’t be pretty or anything special, but in 5 lines of code, you have a web application. I’ve used Django before in the past, another python web framework which is also really great, but it has a lot of overhead and a lot of code to get started. Since our goal here is just to build a basic backend API, Flask will serve our needs just fine.

Open up your IDE of choice, I usually use Visual Studio Code, and open it to your project directory: ~/Documents/Development/Flask_Project. If you’re unsure how to do this, you can just go to File -> Open Folder -> Flask_Project. Once you are in your project’s directory, you can create a python file, I’ll call mine flask.py. Here is where I’ll show you how to create a very basic flask application.

In your flask.py file, write the following:

from flask import Flask
app = Flask(__name__)

@app.route( / )
def index():
     return <h1>Hello World!</h1>
Enter fullscreen mode Exit fullscreen mode

And that’s all it takes!

Let’s see if it works by going to the terminal either in VS Code or using whichever terminal you prefer, and make sure we are in our project directory ~/Documents/Development/Flask_Project. If we aren’t in the project directory, the app won’t run! Also, we want to make sure that our virtual env is active. You should see the name of the virtual environment, flaskenv (or whatever you named yours), either to the left or the right of the terminal. If not, you’ll have to activate it again:

source flaskenv/bin/activate

Next, we’ll export our flask.py file to tell the flask server where to look for the file.

export FLASK_APP=flask.py

Make sure you don’t include any spaces, just FLASK_APP=flask.py. Then we can run flask in the terminal.

flask run

You should see something like:

Serving Flask app “flask”
Running on http://127.0.0.1:5000/ (press CTRL + C to quit)
Enter fullscreen mode Exit fullscreen mode

If you encountered an error, it could be a couple things. Most likely you may not be in the project directory in your terminal or you may not have activated your virtual environment properly.

Next, go to any web browser – Chrome or Firefox will suffice – and type in http://localhost:5000/ in the address bar at the top. Hit enter, and you should see Hello World! in big bold letters. Congrats! You build your first flask application.

CREATING A MORE DYNAMIC WEB APP WITH VARIABLES

We can also make our application a bit more dynamic and include a variable we want to be passed to the application. Let’s say we want to collect some user information and add a /users route to our application.

from flask import Flask
app = Flask(__name__)

@app.route( / )
def index():
    return <h1>Hello World!</h1>

# We can add this view function 
# and put our variable brackets 
# like this: <variable> 
@app.route(/users/<name>)
def user(name):
    return f<h1> Hello, {name}!</h1>
Enter fullscreen mode Exit fullscreen mode

Notice that the variable name is the same in the @app.route section, as well as in the function definition and in the return statement. This is important. This will eventually be one of the ways we pass data from the front end to the backend.

Now we can again go to our browser, but this time type in http://localhost:5000/users/Brandon and we should see Hello, Brandon! in big bold letters. Of course you can replace Brandon with whatever name or word you prefer, feel free to play around with it.

One other thing I would like to add is how to activate Debug Mode on the flask server. Right now, the way we ran the server was in production mode when we called flask run. So next time, when we start our server, we can type the following:

export FLASK_APP=flask.py
export FLASK_DEBUG=1
flask run
Enter fullscreen mode Exit fullscreen mode

And this will activate debug mode. This is really helpful because it will display in the web browser any errors that occurred and make it easier for you to see what is going wrong in your application.

** You will have to export both FLASK_APP and FLASK_DEBUG every time you reload your terminal or open your project again. Eventually, you will need to set up environmental variables for your application so you won’t have to do this every time. This is another reason I really like virtualenvwrapper because they have a postactivate hook that will automatically run anytime you start the virtual env and you can place all the env variables there! There are other tools like dot-env for python that you can use. Here's an article on using a .env file.

Next we’re going on to talking about how to install PostgreSQL, flask sqlalchemy, and setting up our database.

Setting up PostgreSQL Database

You will need to install PostgreSQL, or any other SQL database, onto your machine where you are running your flask web server. Since the focus of this article is mostly to talk about flask, I will link a few articles on how to get Postgres setup on your machine. I use postgres because that is what I learned on, but any other SQL database will work just fine. If you already have one installed on your machine, then skip ahead to the next section about Flask-SQLAlchemy.

Once you’ve installed Postgres correctly, you can verify that it’s working by typing psql in the command line and hitting enter. You should see something like postgres=# or something similar, maybe the name you used to set it up, but you shouldn’t see an invalid command error. If so, then you need to review your installation.

Inside of our psql shell, we’re going to create a database for our project. We will use the CREATE DATABASE command for psql to create a database called flaskapp

    postgres=# CREATE DATABASE flaskapp;
Enter fullscreen mode Exit fullscreen mode

Don’t forget the semi-colon at the end or it will think that you are entering more information. It should say CREATE DATABASE after you’ve done it correctly. We can check that it’s been added by typing backslash and lower case L to list the databases ( “\l” without the quotes). Once there, you should see the name flaskapp written in a table under NAME. Now you can hit lower case Q and it will leave the screen. Then backslash q to quit out of psql.

This is most of what we will have to do with postgres directly, moving forward we will use a flask library called flask-sqlalchemy that will help us deal with all database related material. Flask-SQLAlchemy works with SQL databases like Postgres, MySql, SQLite, etc. So if you are not using Postgres, the rest of this tutorial will still work just fine.

Using Flask-SQLAlchemy to Connect to PostegreSQL

Next we are going to install Flask-SQLAlchemy. This works seamlessly with the SQL databases. Again, I will be using Postgres for this tutorial, but any popular SQL database will be just fine, you may need to slightly alter a line or two of code in our configuration, but the rest will be the same. I’ll try to highlight where those differences are as well.

In our terminal, let’s again make sure we are in our project directory. Also, that we are in our virtual environment. See above if you forgot how to access those.

    python3 -m pip3 install flask-sqlalchemy
    python3 -m pip3 install psycopg2-binary
Enter fullscreen mode Exit fullscreen mode

After that installs, again, let’s verify that it’s installed correctly by going into our python shell and importing it. When we import SQLAlchemy, we need to make sure we use an underscore instead of a dash, like we used to install it.

    python3
    import flask_sqlalchemy
Enter fullscreen mode Exit fullscreen mode

If no errors come up, we’re good to go and we can move on. Otherwise, you may need to reinstall flask sqlalchemy, or check that you’re in the right directory or the virtual environment.

Now let’s set up the configuration in our flask app to talk to the database. Let’s open up our flask.py file and add a couple lines of code. As a reminder, this is what we should have already as a minimum:

from flask import Flask
app = Flask(__name__)

@app.route( / )
def index():
    return <h1>Hello World!</h1>
Enter fullscreen mode Exit fullscreen mode

Now we can add the following lines of code.
** if you are using a different database, your app.config line will be different **

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config[SQLALCHEMY_DATABASE_URL] = postgresql://username:password@localhost:5432/flaskapp

db = SQLAlchemy(app)

@app.route( / )
def index():
    return <h1>Hello World!</h1>
Enter fullscreen mode Exit fullscreen mode

So if you are using a different database, your postgresql://username line will look slightly different. A quick google search will tell you what you need to put. Or leave a comment and I’ll try to help. Also, where I wrote username:password you will have to use the username and password for your psql database that you are using. I believe the default username is postgres and so is the password, or the password is an empty string.

To review, we discussed:

  • Installing Flask
  • Building a simple Flask web application
  • Set up PostgreSQL Database
  • Installed Flask SQLAlchemy to be able to communicate with our database

In the next part of this series, we will discuss how to structure your application so it is flexible and able to scale if the application grows, building an application factory, using Flask Blueprints, creating a config.py file, and creating an application script to run all of our code. See you then!

CREDIT:
A lot of how I learned flask was from the man himself -- Miguel Grinberg. He basically wrote the book on flask. Check it out! Also he has a great blog!

Discussion (0)