Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to develop a web app with angularjs at client-side and flask at backend?

I want to develop a web app with flask(python) at server side and angularjs(javascript) at client side. I checked out the /flask-angular-seed project on github but it is same as the /angular-seed project. It does not contain any support for flask framework. I am new to flask. How to make flask and angular work together as server-client? I know how to create a web service using flask, and also I went through angular tutorial. But I am confused how to make these two work together(like what http request should be called and how flask receives and responds to it).

like image 552
exAres Avatar asked Sep 18 '13 12:09

exAres


1 Answers

The way I do it is to have a single route for the interface (eg /) that will load up the main html template. That template then references the js for your angular app in the static folder.

Then I create routes for the various interaction points (in my case it's rest-y) that angular talks too. I use an angular module called restangular to make that easier / cleaner. My routes return everything in json that can then be directly used.

I also set up and extra route so that /blah/whatever will also route through to the main interface. I ignore the path and once the angular js has loaded, the router (in angular) will look at the path and map it to the correct interface route.

@app.route('/<path:path>')
@app.route('/')
def admin(path=None):
    return render_template('angular_interface.html')

Basically - for the interface I get flask out of the way completely.

EDIT: Folder-wise you might have something like:

__init__.py
api
api/__init__.py
api/resources.py
api/views.py
static/interface/css/style.css
static/interface/js/app.js
static/interface/js/other_modules_etc.js
static/shared/js/angular.js
static/shared/js/restangular.js
templates/interface.html

In my __init__.py I have the routing structure described above (and the Flask app stuff).

My interface.html template looks like the following.

<html>
<head>
  <title>Blah</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='interface/css/style.css') }}"/>
  <script src="{{ url_for('static', filename='shared/js/angular.js') }}"></script>
  <script src="{{ url_for('static', filename='shared/js/restangular.js') }}"></script>
  <script src="{{ url_for('static', filename='interface/js/app.js') }}"></script>
</head>
<body>
  {% raw %}
  <div ng-app="blah" ng-cloak>
    <div ng-controller="BlahCtrl" class="sidebar">
    </div>
  </div>
  {% endraw %}
</body>
</html>
like image 125
Aidan Kane Avatar answered Oct 20 '22 04:10

Aidan Kane