Home > Enterprise >  Flask in VS Code: No module named website.__main__; 'website' is a package and cannot be d
Flask in VS Code: No module named website.__main__; 'website' is a package and cannot be d

Time:01-07

I have a very basic flask website, as shown below in the file website.py. Everything works, unless I set debug=True and then set a breakpoint in visual studio, then I get the above error.

from flask import Flask, render_template, request, redirect, url_for, flash

app = Flask(__name__)

@app.route('/')
def home():
    return 'hi'
    
if __name__ == "__main__":
    app.run(debug=True)

CodePudding user response:

Flask recommends running the application by using flask run command. See the Quick start documentation on Flask website. To run the application using debug mode, set FLASK_ENV environment variable to development.

website.py:

from flask import Flask, render_template, request, redirect, url_for, flash

app = Flask(__name__)

@app.route('/')
def home():
    return 'hi'

If you are using Linux/Mac:

export FLASK_APP=website
export FLASK_ENV=development
flask run

If you are using Windows:

set FLASK_APP=website
set FLASK_ENV=development
flask run

References:

CodePudding user response:

You need to create a debug configuration for your flask python file:

In the launch.json file click Add Configuration -> select Python -> select Flask.

And remember to rename the app.py to website.py

Or you can copy this in your launch.json file directly, and select this as the configuration for your debugging:

{
  "name": "Python: Flask",
  "type": "python",
  "request": "launch",
  "module": "flask",
  "env": { "FLASK_APP": "website.py", "FLASK_ENV": "development" },
  "args": ["run", "--no-debugger"],
  "jinja": true
},

And you can have a look at the official docs for more details.

  •  Tags:  
  • Related