I really tried to solve this error with google, but could not find a solution that works. Maybe one of you has an idea.
My structure is this:
app/
|- static/
| |- js/
| `- styles/
|- templates/
|- app.py
|- auth.py
|- db.sqlite
|- main.py
|- models.py
`- requirements.txt
app.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
return app
app = create_app()
models.py:
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
fname = db.Column(db.String(100))
lname = db.Column(db.String(100))
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
As an error i got this one:
File "C:\path\Flask_app\app\models.py", line 2, in <module>
from . import db
ImportError: attempted relative import with no known parent package
I dont know what to change. In main.py i got a notice:
"db" is not accessed
CodePudding user response:
Your missing an __init__.py
to mark your project as a proper python package:
.
├── app
│ ├── app.py
│ ├── auth.py
│ ├── db.sqlite
│ ├── __init__.py
│ ├── main.py
│ ├── models.py
│ ├── static
│ │ ├── js
│ │ └── styles
│ └── templates
└── requirements.txt
works with python -m app.app
or python app/app.py
from the project root. But still, you likely want a setup.py
or a pyproject.toml
, e.g. to actually specify that you want to distribute your static/
files (and from the looks of it a sqlite-database?) with your package.
CodePudding user response:
Create an init.py file inside the app directory.
Then add the following contents inside the init.py
import os, sys;
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
It should solve the error