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
- I recommend you use a virtualenv for this project
- Install flask
pip install flask
- 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:
- Start Flask and the hello.py Python script
python hello.py
- In your browser, go to http://127.0.0.1:5000/. This should show
“Hello world!”
Show the Angular page from step 1
- In hello.py, add
from flask import render_template
- hello() function, replace last line with
return render_template('helloworld.html')
- Move helloworld.html to (project root)/templates
- 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
- Create (project root)/static. This is where Flask will be looking for anything in (url)/static, without doing any further processing
- Move /external to /static. You should now have /static/external, containing angular.js and moment.js
- In templates/helloworld.html, change the link from “external/angular.js” to “static/external/angular.js”
- Do the same for moment.js
- 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:
- In helloworld.html, after the line “angular.module(‘HelloWorldApp’, [])”, add:
.config(function($interpolateProvider){ $interpolateProvider.startSymbol('[[').endSymbol(']]'); })
- And replace the {{ }} brackets with [[ ]]:
Welcome, today is [[ dateToday ]]
- Test this. You should now see
Welcome, today is June 7th 2016
Going live
- I used the instructions from http://joaoventura.net/blog/2016/flask-webfaction/ to put the site live.
Done
- See the result at http://cm-demo.com/namepy_step2/
- The source code is at https://github.com/CoachCoen/namepy/tree/step2
Next
Continue to Step 3 – Adding in Highcharts