Namepy step 2 – Flask and Angular

(This is part of the namepy project. Start at Namepy – on the shoulders of giants)

We’re going to need some server-side processing, for which I’ll be using Python and the Flask micro framework

  1. I recommend you use a virtualenv for this project
  2. Install flask
    pip install flask
    
  3. Create /hello.py
    from flask import Flask
    app = Flask(__name___)
    app.config['DEBUG'] = True
    
    @app.route("/")
    def hello():
        return "Hello world!"
    
    if __name__ == "__main__":
        app.run()
    

Test this:

  1. Start Flask and the hello.py Python script
    python hello.py
  2. In your browser, go to http://127.0.0.1:5000/. This should show

    “Hello world!”

Show the Angular page from step 1

  1. In hello.py, add
    from flask import render_template
  2. hello() function, replace last line with
    return render_template('helloworld.html')
  3. Move helloworld.html to (project root)/templates
  4. Test this (see above). This will bring up

    Welcome, today is {{ dateToday }}

As you can see, this isn’t quite right. If you open up the browser’s console (e.g. ctrl-shift-j in Google Chrome) you’ll see that the browser can’t find the external files (AngularJS and MomentJS). Let’s fix this first

  1. Create (project root)/static. This is where Flask will be looking for anything in (url)/static, without doing any further processing
  2. Move /external to /static. You should now have /static/external, containing angular.js and moment.js
  3. In templates/helloworld.html, change the link from “external/angular.js” to “static/external/angular.js”
  4. Do the same for moment.js
  5. Test this again. This will show

    Welcome, today is

Almost there. If you check in your console you’ll see that the error messages are no longer there. However, the {{ dateToday }} has disappeared. If you view the web page’s source code you’ll see that the line has been replaced with “<p>Welcome, today is </p>”. This is because the Jinja template engine used by Flask also uses double curly brackets {{ }}, just like Angular. Jinja processes (and removes) the double curly brackets before it gets to Angular. There are a number of solutions for this, such as telling Angular to use double square brackets [[ ]] instead:

  1. In helloworld.html, after the line “angular.module(‘HelloWorldApp’, [])”, add:
        .config(function($interpolateProvider){
            $interpolateProvider.startSymbol('[[').endSymbol(']]');
        })
    
  2. And replace the {{ }} brackets with [[ ]]:
    
    
    Welcome, today is [[ dateToday ]]
    
    
  3. Test this. You should now see

    Welcome, today is June 7th 2016

Going live

Done

Next

Continue to Step 3 – Adding in Highcharts