I'm trying to create a basic blogging application in Python using Web.Py. I have started without a direcotry structure, but soon I needed one. So I created this structure:
Blog/
├── Application/
│ ├── App.py
│ └── __init__.py
|
├── Engine/
│ ├── Connection/
│ │ ├── __init__.py
│ │ └── MySQLConnection.py
│ ├── Errors.py
│ └── __init__.py
├── __init__.py
├── Models/
│ ├── BlogPostModel.py
│ └── __init__.py
├── start.py
└── Views/
├── Home.py
└── __init__.py
start.py
imports Application.App
, which contains Web.Py stuff and imports Blog.Models.BlogPostModel
, which imports Blog.Engine.Connection.MySQLConnection
.
Application.App
also imports Engine.Errors
and Views.Home
. All these imports happen inside contructors, and all code inside all files are in classes. When I run python start.py
, which contains these three lines of code:
from Application import App
app = App.AppInstance()
app.run()
The following stack trace is printed:
Blog $ python start.py
Traceback (most recent call last):
File "start.py", line 2, in <module>
Blog = App.AppInstance()
File "/home/goktug/code/Blog/Application/App.py", line 4, in __init__
from Blog.Views import Home
ImportError: No module named Blog.Views
But according to what I understand from some research, this should run, at least until it reaches something after App.py. Can anyone tell where I made the mistake? (I can provide more code on request, but for now I'm stopping here, as this one is getting messier and messier).
App.py
contains the statement
from Blog.Views import Home
So Blog
needs to be among the list of directories Python searches for modules (sys.path
). That can be arranged in various ways.
Since you are starting the app with
python start.py
, the directory containingstart.py
is automatically added to the search path. So you could changefrom Blog.Views import Home
to
from Views import Home
Another option would be to move
start.py
up one level, out of theBlog
directory. Then when you callpython start.py
, the directory containingstart.py
will also be the directory containingBlog
. So Python would findBlog
when executingfrom Blog.Views ...
Finally, you could add the
Blog
directory to your PYTHONPATH environment variable.
You can only import the module Blog
if its parent directory (not Blog
itself) is on python's path.
If you run your program from the Blog
directory like you do, you can only imort Views
directly, like you do with Application.App
:
from Views import Home
instead of
from Blog.Views import Home
in your Application/App.py
.
来源:https://stackoverflow.com/questions/13221021/cannot-get-imports-to-work-in-web-py-project