2

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).

martineau
  • 119,623
  • 25
  • 170
  • 301
LucasGob
  • 57
  • 3
  • Maybe this may help you https://stackoverflow.com/questions/16981921/relative-imports-in-python-3 – Tony Ngo Feb 08 '21 at 01:01
  • Did you try it removing the "." form ```.site``` it seems unlikely it would be there – Yash Feb 08 '21 at 01:01
  • Yeap! As I said, I tried to remove the ".", but the errors changes to ```ImportError: cannot import name 'create_app' from 'site' (C:\Python38\lib\site.py)``` – LucasGob Feb 08 '21 at 01:21

2 Answers2

1

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.

szatkus
  • 1,292
  • 6
  • 14
  • Module names cannot contain minus signs, will raise an SyntaxError. – TheEagle Feb 08 '21 at 01:08
  • Thank you so much! Works perfectly. I changed the name to "webapp" (without the "-"). Just a doubt, there is some way to run inside of the webapp folder? Maybe change some import or anything else? – LucasGob Feb 08 '21 at 01:19
  • 1
    You can change `site` to something else or put it into another module, so you avoid a collision with a built-in module with the same name. – szatkus Feb 08 '21 at 01:20
1

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

TheEagle
  • 5,808
  • 3
  • 11
  • 39