basic web app with flask angularjs

Setting up a Basic Web App with Flask and AngularJS

Ben by

AngularJS is a really powerful and extensible Javascript library that can be used for all number of applications. Team that up with Flask and you’ve got a great foundation for building web apps.

Getting started with Flask and AngularJS can seem like a daunting task at first, reading through page after page of documentation just to get a basic project running certainly isn’t how I’d like to spend my time.

But after you’ve read through this guide, you will have a basic web app using Flask and AngularJS that you can build upon.

This tutorial will walk you through setting up a basic full stack application with Flask acting as our back-end and AngularJS as our front end.

Download Project Source


Before We Start

Before we jump in and start creating our web app, you’ll need to make sure that you’ve already installed Flask on your server. If you haven’t done so already, you’ll need to go and do that now.

I’m also going to assume that you’ve got a least a basic knowledge of HTML, Javascript and Python.

Now that we’ve got everything that we need setup, we can start building our application.

Step 1: Project Structure

To get an overview of how Flask and Angular integrate and work together, we’re first going to take a look at our project’s structure.

Here’s an overview of what our basic example app is going to look like when we’re finished:

example_project/
    app.py - Our main app
    static/ - Static files
        css/
            style.css
        img/
            angularjs.png
        js/
            app.js - Main angular file
        partials/
            index.html - Homepage partial/template
            about.html - About partial/template
    templates/
        index.html - Basic index template

You’ll want to create a new project and create all the files and folders above.

App.py

Your app.py module is going to be the brains of your Flask back-end.

Here we’ll define our basic Flask application and the URL route for our apps index or homepage.

Since we’re going to be doing all of our URL routing in Angular, we’ll only need to serve a static template for our homepage.

All of our actual pages within the app will be held in partials, which Angular will then display based the page URL.

Static Directory

Any static files that you need to be served, like CSS, Javascript, Images and our Partials will need to be kept inside of our static folder.

All of these files will then be available at /static/.

Partials

Partials are where we’re going to hold all of the data for each page. A good way to think of them is as templates.

Angular will load our partials based on our URL routes, so that all of the pages of our app can be served from a single page.

Template Directory

The template directory is going to hold all of our static templates.

In our case, we’re only going to need a static template for our homepage.

This will take care of loading Angular and displaying our partials.

Step 2: Setting up Flask

Now that we have a basic structure for our project, we can begin working on setting up Flask as the back-end.

As we’ll be doing most of the URL routing and displaying of data in Angular, we don’t need that much code to get everything setup.

Open up your app.py file and paste in the following:

from flask import Flask, send_file

app = Flask(__name__)

@app.route("/")
def index():
    return send_file("templates/index.html")
	
if __name__ == "__main__":
    app.run(host='0.0.0.0')

As you can see, it’s just a very basic Flask application. However, there are a few lines of code here that are important and worth explaining in further detail.

@app.route("/")
def index():
    return send_file("templates/index.html")

Here we’re defining the URL routing in Flask. When the user visits the homepage (“/”) we will return our index.html template.

if __name__ == "__main__":
    app.run(host='0.0.0.0')

Another thing worth mentioning is that in this example I have changed the host to 0.0.0.0

This is because Flask will automatically only run the server on localhost or 127.0.0.1 which is useless if you want to access the app from another computer.

To fix this, we set the host as 0.0.0.0 which will allow all incoming connections to the web server.

Step 3: Adding an Index Template

Our Flask backend is now complete and it should now be serving a static index template if we try to visit it.

But it’s not much use yet as we don’t have a static template to work with. So we’re going to have to create one.

Go into your templates directory and open/create index.html, you’ll then want to paste in the following:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
		<script src="http://code.angularjs.org/1.5.3/angular-route.min.js"></script>
		<script src="/static/js/app.js?x49983"></script>
		<link rel="stylesheet" href="/static/css/style.css?x49983" />
    </head>
    <body ng-app="myApp">
				
				<img src="static/img/angularjs.png" />
				
				<hr/>
			 
			 <div ng-view></div>
    </body>
</html>

This is going to be our basic template. All it needs to do for us is initialize Angular and allow us to load our pages, which we’ll be storing and loading as partials.

It’s worth noting that our entire app will be run from this single page, so any CSS or JS files that you need should be called here.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="http://code.angularjs.org/1.5.3/angular-route.min.js"></script>

Make sure that you are calling AngularJS, as well as Angular-Route as this is what will be powering our front-end.

<script src="/static/js/app.js?x49983"></script>

Load your custom script, which will be the brains of our Angular front-end.

Make sure to prefix your URLs with /static/ as Flask will only publicly serve the static directory.

<body ng-app="myApp">

It’s important to declare ng-app as the name of your Angular app, you will also need to declare this in your app.js file later on so keep an eye out for typos!

<div ng-view></div>

Finally, the ng-view tag defines a div that Angular will use to load our partials.

This will change based on our URL routing that we will define in our app.js file later on.

Step 4: Setting up Angular

Now that our Flask back-end and basic template are all setup, now it’s time to start working on our Angular code.

This is what will handle our URL routing and will display the correct page within the app based on it’s URL.

Go ahead and open up your app.js file and paste in the following:

'use strict';   // See note about 'use strict'; below

var myApp = angular.module('myApp', [
 'ngRoute',
]);

myApp.config(['$routeProvider',
     function($routeProvider) {
         $routeProvider.
             when('/', {
                 templateUrl: '/static/partials/index.html',
             }).
             when('/about', {
                 templateUrl: '../static/partials/about.html',
             }).
             otherwise({
                 redirectTo: '/'
             });
    }]);

I won’t go into too much detail about why I’ve added ‘use strict’ at the top of the file, but if you’d like to learn a little more there’s a great answer on StackOverflow as to the reason why it’s useful.

var myApp = angular.module('myApp', [
 'ngRoute',
]);

Here we’re just defining our Angular app name as an angular module.

Make sure that the app name that you use here is the same as the one that you defined in your index.html template we created earlier.

myApp.config(['$routeProvider',
     function($routeProvider) {
         $routeProvider.
             when('/', {
                 templateUrl: '/static/partials/index.html',
             }).
             when('/about', {
                 templateUrl: '../static/partials/about.html',
             }).
             otherwise({
                 redirectTo: '/'
             });
    }]);

Then we declare the URL routes within the application.

Angular will take care of this for us, so that when the user visits the about page (/about) they will be returned the about.html partial.

Finally, we say that otherwise redirect to the homepage.

This way if there are any broken links or the visitor uses an incorrect URL, instead of returning a 404 or (worse) breaking the app, they’re just redirected to the app’s homepage.

Step 5: Creating Partials

So we’ve setup our Flask back-end, we’ve built our index template and we’ve just setup Angular.

Now it’s time to get stuck in with partials.

Since our example web app is running from a single page, our Angular front-end will take care of which URL a visitor is requesting and then return them a partial for that page.

The partial will then be displayed inside the ng-view div that we defined in our index template.

Partials can be as simple or as complex as you’d like. They can just be static HTML, or you can use Angular to display content in real-time.

Go head an open up index.html in your /static/partials directory and paste in the following:

<h1>Home Page</h1>

<p>You should head over to the <a href="/#/about">about page</a>.</p>

<h2>Here's an Angular Demo:</h2>

<div>
    <input type="text" ng-model="yourName" placeholder="Enter a name here">
    <hr>
    <h1>Hello {{ yourName }}</h1>
</div>

In this example I’ve included the basic Angular demo to show you how Angular components can be displayed within a partial.

We’ll also add a nice and simple, static about page.

Go head and paste the following into your about.html file:

<h1>About</h1>

<p>Hmm, not much here.</p>
<p>Best get back to the <a href="/#/">home page</a>.</p>

<p>Tip: going to an incorrect URL will take you to the homepage, <a href="/#/404">Try it!</a></p>

This time I’ve just made a simple about page with some links to other pages within the app.

Linking

You’ve probably noticed that the links that I included on the index and about page are a little strange.

<a href="/#/">home page</a>

So what’s with the /#/ prefixing each URL?

Since this is a single page web application, all of the links that you create will need to be inside that webpage to be picked up by Angular’s URL routing.

This is why we add the /#/ prefix the each URL, because we’re not actually leaving the page.

If you try linking without it, you’ll find you just get either a 404 error or an internal server error.

Step 6: Testing Your Web App

Now we’re almost finished, all that we need to do now is test our application.

Head over to your command prompt and run the app:

cd /directory-where-you-saved-the-app
python app.py

Flask will let you know that it’s running and ready to accept some incoming connections.

flask angularjs test console

If you fire up your servers IP in your browser then you should be greeted with a fully working single page web application.

flask angularjs test page

And that’s all you need to setup a very basic web app with Flask and AngularJS.

In our next tutorial we will outline how you can use AngularJS to fetch data from a Flask back-end.

You may also like

  • Dhruv Srivastav

    Where is the next part..?

    • Ben

      Hi there Dhruv, I’ll be writing the next post in the series soon!

  • Kanika Murarka

    Nice post, thankyou 🙂

    • Ben

      No problem thanks for the feedback 🙂

  • Ben

    Thanks for the heads up Oziel!

    For this example I was trying to crease a one page application so that it would hopefully make it a little easier to understand.

    I’ll work on a follow up which utilizes multiple pages

  • Ben

    Hi tooki,

    Apologies it’s been so long!

    I’m currently working on a followup tutorial which should be up within the next week or so.

    If you’re on twitter or have email I’d be happy to send you the link when the post is live.

  • Ben

    No problem Andre glad you found it useful 🙂

  • Anton

    I wish there some data going from Flask -> Angular, otherwise it’s doesn’t make a representative example, as the integral part of “Flask & Angular” interaction is omitted!

    • Ben

      Hi Anton,

      I understand the frustration – I’m in the process of writing the follow up article, which is pulling data from Flask into Angular and then pushing data from Angular back into Flask.

  • Michael VdV

    Hey man great tutorial!
    When will there be a next part?
    Anyway, keep up the good work!

  • Eric Parsons

    Is there another part still coming?