Flask route from different file is not working

Viewed 1044

I started building an application based on Flask. The idea is to play a little with REST API, without any HTML etc., just simple JSON responses.

Everything seems to work if I have everything in one file.

 tasks = [  # pylint: disable=C0103
    {
        'id': 1,
        'title': 'First',
        'content': u'First task'
    },
    {
        'id': 2,
        'title': 'Second',
        'content': u'Second task'
    }
]
app = Flask(__name__)   

@app.route('/api/v1.0/tasks/', methods=['GET'])
def get_tasks():
    """
    [GET] Retrieves all tasks
    """
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

This works perfectly when I run my flask app. The problem is starting when I want to move it to other file. I just moved get_tasks method to /my_app/views.py and declaration app = Flask(name) into my_app/init.py. Of course I added import in my main app.py file. Server starts normally, but I am not able to get result. When I move back the method to app.py, it works. What am I missing here?

EDIT

app.py

from my_app import app

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

views.py

from flask import jsonify
from my_app import app
@app.route('/api/v1.0/tasks/', methods=['GET'])
def get_tasks():
    """
    [GET] Retrieves all tasks
    """
    tasks = [  # pylint: disable=C0103
        {
            'id': 1,
            'title': 'First',
            'content': u'First task'
        },
        {
            'id': 2,
            'title': 'Second',
            'content': u'Second task'
        }
    ]
    return jsonify({'tasks': tasks})

dir structure:

project_name/
--- my_app/
----- __init__.py
----- views.py
--- app.py

EDIT 2 As I mentioned in comment, I moved everything from init.py into app.py file, and it still don't work, but when I've added in app.py one extra import, after app = Flask(name), it works. Import is

from my_app import views

When I am trying to add this import before, I have circular import

0 Answers
Related