[FIXED] How can I run the main file with flask?

Issue

I am trying to run the server of this repository (it’s about oauth2): https://github.com/lepture/flask-oauthlib/blob/master/tests/oauth2/server.py

The main file looks like this:

if __name__ == '__main__':
    from flask import Flask
    app = Flask(__name__)
    app.debug = True
    app.secret_key = 'development'
    app.config.update({
        'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.sqlite'
    })
    app = create_server(app)
    app.run()

However, I am getting this error:

Error: Failed to find Flask application or factory in module ‘hello’. Use ‘FLASK_APP=hello:name’ to specify one.

I executed the following commands in terminal:

export FLASK_APP=server.py` and 
export FLASK_APP=main.py

After that, I tried rerunning with flask run

Again, I am getting this error:

Error: Failed to find Flask application or factory in module ‘main’. Use ‘FLASK_APP=main:name’ to specify one.

Solution

You should run it directly

python server.py

And if you want to use flask run then you would have to put all (except app.run()) before if __name__ == '__main__': because flask run will import this file and import will skip code inside if __name__ == '__main__':

# ... other code ...

from flask import Flask
app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
app.config.update({
    'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.sqlite'
})
app = create_server(app)

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

And it will need export FLASK_APP=server:app because you want to run file server.py and use instance of Flask() with name app

export FLASK_APP=server:app

flask run

Because code uses standard name app so you could skip it in export

export FLASK_APP=server

flask run

You can also run without export

flask --app server run

Answered By – furas

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published