Typical AngularJS workflow and project structure (with Python Flask)

后端 未结 6 2200
梦如初夏
梦如初夏 2020-12-02 03:27

I am pretty new to this whole MV* client-side framework frenzy. It doesn\'t have to be AngularJS, but I picked it because it feels more natural to me than either Knockout, E

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 03:57

    I would start out by organizing the Flask app in the standard structure as follows:

    app
    |-- app.py
    |-- static
        |-- css
        |-- img
        |-- js
    |-- templates
    

    And as btford mentioned, if you are doing an Angular app, you'll want to focus on using Angular client-side templates and stay away from server-side templates. Using render_template('index.html') will cause Flask to interpret your angular templates as jinja templates, so they won't render correctly. Instead, you'll want to do the following:

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

    Note that using send_file() means that the files will be cached, so you might want to use make_response() instead, at least for development:

        return make_response(open('templates/index.html').read())
    

    Afterwards, build out the AngularJS part of your app, modifying the app structure so that it looks like this:

    app
    |-- app.py
    |-- static
        |-- css
        |-- img
        |-- js
            |-- app.js, controllers.js, etc.
        |-- lib
            |-- angular
                |-- angular.js, etc.
        |-- partials
    |-- templates
        |-- index.html
    

    Make sure your index.html includes AngularJS, as well as any other files:

    
    

    At this point, you haven't yet constructed your RESTful API, so you can have your js controllers return predefined sample data (only a temporary setup). When you're ready, implement the RESTful API and hook it up to your angular app with angular-resource.js.

    EDIT: I put together an app template that, though a little more complex that what I've described above, illustrates how one could build an app with AngularJS + Flask, complete with communication between AngularJS and a simple Flask API. Here it is if you want to check it out: https://github.com/rxl/angular-flask

提交回复
热议问题