LucasGob
LucasGob

Reputation: 57

ImportError in Python 3.8.6

I am using python 3.8.6 to build a simple web app with the module Flask and the folder structure looks exactly like this:

web-app
 ├── main.py
 └── site
     ├── __init__.py
     ├── auth.py
     └── models.py

In __init__.py there is a function called create_app() and this function must be accessed by my main.py.

# site/__init__.py
from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config.SECRET_KEY = ""
    return app
enter code here

In my main.py I am importing the create_app() like this:

# main.py
from .site import create_app

app = create_app()

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

But when I try to run my main.py, raises the following error:

Traceback (most recent call last):
  File "c:/Users/User/Desktop/website/main.py", line 1, in <module>
    from .site import create_app
ImportError: attempted relative import with no known parent package

I've already try to import without the dot before the folder's name, like from site import create_app, but that also didn't work, the error message just changes to ImportError: cannot import name 'create_app' from 'site' (C:\Python38\lib\site.py).

Upvotes: 2

Views: 633

Answers (2)

TheEagle
TheEagle

Reputation: 5992

Add a file named __init__.py inside the web-app folder (you can leave it empty). You then should be able to do from .site import create_app

Upvotes: 1

szatkus
szatkus

Reputation: 1395

Change it to:

from web-app.site import create_app

An from a directory one level up run:

python -m web-app.main

There are apparently built-in module named site in Python, so there's a bit of name collision here.

Upvotes: 1

Related Questions