
Hi and welcome to “From Zero to Flask”. My name is Jorge Escobar and I have been building professional Python applications for the last 10 years and now want to teach you, from scratch, how to build Flask applications using the techniques used in real world tech companies.
In this course you will learn the fundamentals of Flask, how to isolate your dependencies using virtual environments, then we’ll go over routing, templates, sessions and database migrations with a simple page counter application.
We will then build a blog application with author registration, login, post blog articles, adding photos, pagination and editing and deleting posts.
In every step of the way, we will be writing units tests for each of the blog features, just like professional developers do.
Like I mentioned earlier, we have two options to setup our Python Flask Development Environment.
The first is to install Flask locally in your computer. That means you have administrator access and can install packages.
The second is to use an online python development environment. Here you will sign up to a cloud-based service where you can code from anywhere you like, your home, work computer or even an internet cafe. There’s no installation required.
My favorite package manager for the Mac is Homebrew and that’s what we’ll use to install Python 3.
My favorite package manager for Windows is [Chocolatey] and that’s what we’ll use to install Python 3.
I’m constantly searching for the best Python cloud development environment and I keep coming back to PythonAnywhere. They are completely free but have really good plans, they have amazing customer service and they have MySQL and Postgres support built in.
Think of a virtual environment as an enclosure in your computer where you can install Python and additional libraries, as well as your own code, without interfering with your computer in general as well as with other projects. So each project you work on is going to have its own virtual environment.
One thing that I recommend is that you put all your projects in one folder in your computer. It’s not a good practice to just have projects lying around in different folders in your computer.
Because PythonAnywhere has restrictions on the user’s permissions, we’ll need to create our directory using PythonAnyhwere’s custom setup.
For your virtualenv to be _active_ you need to type a command to _activate_ it. Activating it makes the computer think that the “main” folder to install things in is our `venv` folder and not the root computer’s folder.
It’s time to install Flask for our project. Since we don’t want Flask to be installed system-wide, we’ll use our virtualenv.
We’re finally ready to build our first Flask application. Well, it’s not going to be technically an application, but it will introduce us to some fundamental concepts, so that we’re ready to start building real applications.
So let’s create a file inside our `simple_flask_app` folder. But first, we need to activate our virtual environments.
Let’s see how we run the application on Windows or Mac.
To run our application on PythonAnywhere, we need to register a web app on their system.
One of the things you’ll spend the most time on as a software developer will be finding issues with your and your team’s code, also known as “bugs”.
Open your terminal, activate your environment and do the following.
To turn on debugging mode in PythonAnywhere, you need to edit the WSGI file on the Web > Code section of the dashboard, and set the `app.debug` setting on line 8 of the file to “True”.
When you reload the page, you’ll see something like this.
The method of sending users to a specific part of the code based on the URL is called “routing”.
As you build your application, the pages we return to the user will start getting more and more complicated. It would get pretty messy if you had each function with a return variable several dozen lines long.
One thing you will do often in your templates and controllers will be to put links to other pages.
There are certain files that don’t need to be processed by our controller, because they’re always the same. The majority of these are presentation-centric files, like CSS or JavaScript files that improve the user interaction.
If you’re still on the index page of the application and click on the “Hello” link, you’ll notice our “Hello” page’s title didn’t change to red like the one on `index.html`.
One of the main functionalities an application has is the ability to receive input from its users.
HTTP is called a “stateless protocol” because the server only sees each individual page hit as a stand alone operation. There’s no “history” of where the user was before.
As you continue building applications you will quickly learn that the settings required to develop in your laptop are different from the ones used in the server that actually runs your site to the world. Typically these different states of the app are called _environments_.
So first, we need to install `python-dotenv`, so add it to the `requirements.txt` file.
So first, we need to install `python-dotenv`, so add it to the `requirements.txt` file.
Like we saw on our lesson on cookies and sessions, HTTP is a stateless protocol that doesn’t save anything between sessions. With cookies, we’re able to keep a pointer to a specific user but there’s a limit on how much information we can store in them.
It’s time to install MySQL. As usual, if you’re using PythonAnywhere, the flow is a little different. So skip to the lesson that applies to you.
Thanks to Homebrew installing MySQL on the Mac is pretty simple. Just do the following:
`brew install -y mysql`
Thanks to Chocolatey, installing MySQL on Windows is pretty simple. We will install the MariaDB package which works exactly like MySQL. Open a PowerShell as an administrator and type:
`choco install -y mariadb`
If you are using PythonAnywhere, MySQL is already built in, so you don’t need to install it manually.
Before we start building our first database driven application, I wanted to introduce you to the concept of the _Object Relational Mapper_ or ORM.
We will be taking a big step in our development road, creating our first database driven Flask application.
We will be creating a brand new directory for our visitor counter application, and this process will show you how to setup a brand new Flask application with all we know now.
We will be creating a brand new directory for our visitor counter application, and this process will show you how to setup a brand new Flask application with all we know now.
So let’s go over the requirements.txt libraries to get a better understanding of what we’re including and why.
Now we need to work on the environment settings of our application. So let’s create our `.flaskenv` file and we’ll explain what they are.
In our “Hello World” application, our `hello.py` file had everything contained in it: the application setup, the routes and it was expected to be run by itself.
We are now going to see how we continue building our application in a modular way and that’s by using Flask’s blueprints.
So let’s build our first blueprint module. This module will make sure that every time we load the page, we increment the counter in the database by one.
Now we need to build our Counter app’s model, where we will define this module’s schema. The model can have multiple related classes and each class represents a table in the database.
As our application evolves, the database models will grow as well. But just as we have Git to record the history of our code and have the ability to “undo” things if we messed up, migrations is the same concept applied to our data models.
One of the things I like to do before writing code that reads or writes objects on the application is to test them on the Python Flask shell.
The first iteration of our application will be just to measure how many times the home page has been loaded.
Professional developers integrate testing early on to their development flow and my intention is to teach you how a professional developer works, so let’s write a testing suite for this application.
So far we have just setup our test class and we’re itching to write our first test. So let’s do it.
We’re going to now build a personal blogging application where we will learn a lot of the concepts that a professional developer would use.
We will be creating a brand new directory for our blogging application, so do the following.
We will be creating a brand new directory for our blogging application.
Once again let’s go over the requirements.txt libraries to get a better understanding of what we’re including and why.
Let’s setup the core application quickly. If you don’t want to type all this, you can download a zip file of this branch of the Flogger repository.
As you probably expect, we have two flows to setup the database. One for Windows and Mac and the other for PythonAnywhere. Since we’ve done this before, I’ll go quickly through this for both.
So the first thing we’ll tackle is the creation of the authentication flow for the Blog’s author.
Let’s start working on the Author model. Create a `models.py` file on the `author` folder, and let’s add the following.
Remember what I told you about migrations and the path to models in the previous section? Right now there’s no path to the `models.py` from the `application.py`, since there’s no mention of `author.models` in our `author.views`. If the migrations doesn’t see the file, it won’t create the proper migrations.
After applying the migration, it’s a good practice to test if the table was setup properly in the shell.
We will now create our very first form that will allow our Authors to register.
We are now going to see how to render the form we just created into an author register template. The `RegisterForm` class allows us to create a WTForms instance that we can pass directly to a template.
When you submit the form, WTForm exposes a method called `validate_on_submit` that’s available on the `form` object. Let’s add that do the `author.views` file.
In this lesson we’ll put a slightly better look and feel to our application using the Bootstrap library. We’ll also setup a `base.html` template that will be the master template for all of the pages in our application.
So let’s see how we actually create the author record on the database with the information we input on the register form.
We can quickly check the record on the database using the Flask shell. Go ahead and stop the Flask server, and type on the terminal `flask shell`. If you are in Python Anywhere, remember to have your virtualenv activated.
If you are on Windows, Mac or Linux, you can also use another method to check if the record is being stored in the database or if there are any errors, and that’s using the Python Debugger or PDB. Unfortunately this doesn’t work on PythonAnyhwere, as there’s no Flask terminal available, but stick around just so you see how this works.
To pick up where we left off, we have found a potential issue with our Author registration function. To trigger the error, register two authors with the same email. The second registration throws a database error and halts our application.
Now that we have an author in the database, we’re going to build the functionality to log them into the system.
Of course it’s not good anyone can login to the application, so let’s actually check the credentials in the database.
When you login to a website or application, you need to set some sort of cookie so that other pages that the logged in user loads receive the user’s information and prevent him from seeing pages he’s not supposed to, as well as keep out unlogged users. The most secure way to do that is by using Flask sessions.
If we have a login method, we should certainly have a logout method as well. It’s pretty straightforward, we just need to delete the session cookie.
The last thing we’ll do in this lesson will be to improve the communication with the user and notify him that actions he has taken have been successfully completed and for that we’ll use Flask’s flash messages.
We have done quite a bit of the Author app and we don’t want to continue building our application before we add testing for this piece. Always build features with their corresponding tests and you will be liked by your bosses and your co-developers.
Now we’re going to write some tests for the login functionality. We’ll create a brand new test case, so that the database is clear.
Before we start working on the blog posting feature, we’re going to create a navigation bar so that users can easily go to the different areas of the app and login or logout.
The first thing we’ll do in our blog app is to create a temporary blog index template and even though it won’t render any posts, at least it will have a proper structure and nav bar.
We’re now ready to start our Blog Post Form.
We’re now going to develop the template that will allow us to publish a new blog post. So create a new file called `post.html` inside the templates blog folder, and then write this in it.
We’re now going to take the author’s blog post data and save it on the database.
When we want to restrict a specific route unless a certain condition is met, a useful feature to use is called a decorator.
We now want to be able to display posts to our blog visitors, and we’ll do that using an article view and template.
We have written enough code for us to think about adding some tests, so let’s start writing the Blog tests for what we have so far.
Before we start the blog home page, let’s add an option to post new articles on our nav bar. So open the `nav.html` file and add the following item on line twelve.
In order for us to upload images, we need to do some changes on some existing areas of our code.
Everybody makes mistakes and blog authors are not the exception. So we want to add functionality to edit our blog posts.
Along with the editing function, we should also have the ability to delete posts. We will be using the `live` flag on the model, since we never want to really delete anything, but rather hide it from the user. That way we can restore posts that we accidentally erased as well as conserve all the data, which is really cheap today with low storage costs.
We’re now going to implement a feature that requires a new kind of database relationship. Until now, we’ve seen one type of relationship. The “one to many” which is the relationship between author and posts, since one author can have many posts. Similarly we have the post to category one to many relationship.
The last thing we’ll do is to enable users to see articles related to a category or a tag. We’ll put hyperlinks whenever we display them, so that the user can see posts related to that tag or category.
There’s only one way to learn something really good and that’s by doing something by ourselves. You have now been exposed to a number of techniques and so I want to challenge you to add a new feature to your blog without looking at me type it and hopefully without copying it from somewhere else.
Congratulations on finishing the course! You have taken a huge step in learning how to build a complex Flask web application using best practices. Check out the bonus content at the end to learn how to get the companion book for this course as well as discount coupons for my other courses.
*** Learn Flask Development using the latest Flask version 1.0.2 ***
This course will teach you, assuming no prior coding knowledge, how to develop back end web applications the way professional coders do in the top internet startups. How do I know this? Because I’ve been leading tech teams in both large enterprise as well as startup companies in New York City for the past 15 years.
I have seen a lot of courses and free tutorials and I can tell you 90% of them just teach bad habits while promising to turn you into a real “web developer”.
This course doesn’t promise to turn you into a professional back end developer after you complete it -- it takes much more than the 4 hours of of this course (and probably hundreds of hours of self-practicing) to do that, but it will give you a solid foundation from where to start and continue your training, knowing the right path to become a real professional backend web applications developer using Python.
The course goes through a step by step process of setting up your environment, introducing Flask. It then moves to explore SQL databases, using MySQL and finally showing you how to develop a blogging application using all these learnings.
Best of all, you don’t need to own a computer to take this course, if you don’t own one. You can complete this course from an internet or cyber cafe, as we teach how to to use both locally installed files or an online coding platform.
At the end of the course students will be challenged with a final project where all the course material will need to be used to complete it. Students that finish the final project will be eligible for special future promotions.
If you are interested in learning how to code from zero and without prior knowledge, but do it using best industry practices towards becoming a professional backend web developer, this is the course for you.
The course is divided in 7 sections:
Introduction
Your Development Environment
Say Hello World
Setting up our Database
A Visitor Counter
Flogger: A Personal Blog Application
Final Project
The course has more than 4 hours of video tutorials as well as the source code of all the lessons, so that you can see exactly what the whole project looks like in each stage.
The course can take anywhere from 7 days to a month to complete based on how much material the student completes daily.
Additionally we’re constantly updating the course, adding contents thanks to the feedback of our students.
So stop looking around and start the right path to becoming a professional Python backend web developer with this course!