Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: attempted relative import with no known parent package in flask

folder structure

.
├── myapp
│   ├── api
│   │   └── routes.py
│   ├── app.py
│   |
│   └── site
│       └── routes.py

app.py is in myapp folder outside of api folder and site folder

api/routes.py

from flask import Blueprint
api = Blueprint('api',__name__,url_prefix='api')

@api.route('/userlist/')
def user():
  return { 1: 'user1', 2:'user2'}

site/routes.py

from flask import Blueprint

site = Blueprint('site',__name__)

@site.route('/')
def index():
  return 'Welcome to the Home page'

app.py

from flask import Flask
from .site.routes import site
from .api.routes import api

def create_app():
  app = Flask(__name__)
  app.register_blueprint(api)
  app.register_blueprint(site)
  return app

i got this error while running flask application using 'flask run' command in terminal

Traceback (most recent call last):
 File "app.py", line 2, in <module>
  from .site.routes import site
ImportError: attempted relative import with no known parent package

i don't understand how to solve this problem. thanks in advance :)

like image 372
M_x Avatar asked Sep 04 '25 16:09

M_x


2 Answers

I believe Python thinks the dot of your import is a relative import(which it obviously cannot find).

Try to import with the following: (if app.py is in above your myapp folder)

from myapp.site.routes import site

Try to import with the following: (if app.py is in your myapp folder)

from site.routes import site
like image 155
Cribber Avatar answered Sep 07 '25 18:09

Cribber


Please add empty __init__.py in each folder: myapp, api, site

and then try to import from myapp.site.routes import site

like image 39
Олег Гребчук Avatar answered Sep 07 '25 17:09

Олег Гребчук