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

Question:

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 🙂

Asked By: M_x

||

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
Answered By: Cribber

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

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

Just make a minor change.
old code:

api = Blueprint('api',__name__,url_prefix='api')

new code:

api = Blueprint('api',__name__,url_prefix='/api')
Answered By: Manthan Trivedi

[Running] python -u "c:UserslenovoDesktopOFFICE28 septflask_auth_scotch-masterprojectauth.py"
Traceback (most recent call last):
File "c:UserslenovoDesktopOFFICE28 septflask_auth_scotch-masterprojectauth.py", line 6, in
from .models import User
ImportError: attempted relative import with no known parent package

Answered By: vedsingh bairwa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.