从Flask项目相同目录中的__init__导入

时间:2019-10-16 11:02:10

标签: python flask import module init

init .py和models.py位于同一目录(myproject)

myproject
 |
 -- __init__.py
 -- models.py
 |
 app.py

当我尝试从init导入models.py内的内容时,我得到:

ModuleNotFoundError: No module named 'myproject'

我尝试什么:

from myproject import db,login_manager

当它与另一个.py文件位于同一目录中时,如何从init(例如数据库)中导入内容?

内部初始化:

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager


login_manager = LoginManager()

app = Flask(__name__)

app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 
os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
Migrate(app,db)

login_manager.init_app(app)

login_manager.login_view = "login"

models.py内部:

from myproject import db,login_manager
from werkzeug.security import 
generate_password_hash,check_password_hash
from flask_login import UserMixin

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)

class User(db.Model, UserMixin):


    __tablename__ = 'users'


    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))

    def __init__(self, email, username, password):
        self.email = email
        self.username = username
        self.password_hash = generate_password_hash(password)

    def check_password(self,password):

        return check_password_hash(self.password_hash,password)

在app.py内部(我从中执行项目的地方-它也可以工作)只是想知道为什么在models.py中导入会输出错误消息

from myproject import app,db
from flask import render_template, redirect, request, url_for, 
flash,abort
from flask_login import login_user,login_required,logout_user
from myproject.models import User
from myproject.forms import LoginForm, RegistrationForm
from werkzeug.security import generate_password_hash, 
check_password_hash


@app.route('/')
def home():
    return render_template('home.html')

-- (some more view functions) --





if __name__ == '__main__':
    app.run(debug=True)

2 个答案:

答案 0 :(得分:1)

使用.从同一级别导入。

from . import db, login_manager

答案 1 :(得分:0)

您需要设置PYTHONPATH,以便model.py可以找到myproject模块。

如果您正在运行flask shell,请在myproject目录中尝试以下操作

export PYTHONPATH=.
flask shell

参考:https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH