Here i have following directory structure,
src/models/UserModel.py
src/resources/UserResources.py
and UserModel.py contains
from datetime import datetime
from run import db
from passlib.hash import pbkdf2_sha256 as sha256
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, ForeignKey
from flask import jsonify
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(120), unique = True, nullable = False)
password = db.Column(db.String(120), nullable = False)
user_role = db.Column(db.String(10), nullable = False)
access_token = db.Column(db.String(120), unique = True, nullable = True)
refresh_token = db.Column(db.String(120), unique = True, nullable = True)
def save_to_db(self):
db.session.add(self)
db.session.commit()
and UserResources.py file imports UserModel like this from models import UserModel
even though the models directory having the __init__.py file, it raises the following error ImportError: cannot import name 'UserModel' from 'models'
What I'm doing wrong here ?
from src.models import UserModelfrom ..models import UserModelValueError: attempted relative import beyond top-level packageUserResources.py. It may contain a class, but it is also a module, which you appear to be running as a script leading to your errors. Python doesn't require every class to be in it's own file like Java does. So one possible solution to your problem is to move your class elsewhere, if it helps with the import issues you're having.