0

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 ?

9
  • have you tried from src.models import UserModel Commented Sep 15, 2019 at 5:26
  • yeah but it also gives the same error Commented Sep 15, 2019 at 5:27
  • How about from ..models import UserModel Commented Sep 15, 2019 at 5:29
  • @whydoubt then ValueError: attempted relative import beyond top-level package Commented Sep 15, 2019 at 5:32
  • 1
    I think there's a confusion of terminology here. You've described a module UserResources.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. Commented Sep 15, 2019 at 5:43

1 Answer 1

1

Try using:

from src.models.UserModel import UserModel
Sign up to request clarification or add additional context in comments.

1 Comment

got it Thanks :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.