简体   繁体   中英

Python import - Module not found

I am following a Flask tutorial (on Pluralsight). I have come to where I need to initialize a database, using Flask-SQLalchemy. In the tutorial this is done via the following command, inside Python:

from PyBook.PyBook import db
from PyBook.PyBook.Models import Company

(Actually the names are different in the tutorial, but the concept is very much the same)

However, when I try to run the commands above, I get an error:

Traceback (most recent call last): 
File <stdin>, line 1, in <module> 
File  "C:\Users\Jakob-Desktop\source\repos\PyBook\PyBook\PyBook.py", line 3, in <module
from forms.add_company import AddCompanyForm 
ModuleNotFoundError: No module named 'forms'

Which suggests that the error is in either PyBook.py or add_company (which is referenced by PyBook, as you can see below).

Can anyone tell me what I am missing? I am kind of new to Python.

PyBook.py

from flask import Flask, render_template, url_for, flash, redirect, request
from flask_sqlalchemy import SQLAlchemy
from forms.add_company import AddCompanyForm
import secrets, os

app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_urlsafe(16)

basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:///' + os.path.join(basedir, 'pybook.db')
db = SQLAlchemy(app)

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

(...)

add_company.py

from flask_wtf import Form
from wtforms.fields import StringField
from wtforms.fields.html5 import URLField
from wtforms.validators import DataRequired, url

class AddCompanyForm(Form):
    name = StringField('name', validators=[DataRequired()])

Update

As far as I can tell, the folder structure is correct:

文件夹结构

Use from .forms.add_company import AddCompanyForm as a '.' is used to go through the current directory.

The issue is that the 'forms' folder is not in the PYTHONPATH. If you ever want to look at what is in the PYTHONPATH, you could use:

import sys

print(sys.path)

You need to add a file (usually empty but not always) called __init__.py in the forms folder. I normally would also add one in the main PyBook folder.

Here is a great guide to understanding how imports work:

Definite Guide To Python Imports

Alternatively, you could also add this to the top of your code in PyBook.py

import sys
import os

sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'forms'))

If you were to add the code, you won't have to do something like:

from forms.add_company import AddCompanyForm

but you could just use:

from add_company import AddCompanyForm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM