Cannot get imports to work in web.py project

无人久伴 提交于 2019-12-01 09:11:29

问题


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).


回答1:


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.

  1. Since you are starting the app with python start.py, the directory containing start.py is automatically added to the search path. So you could change

    from Blog.Views import Home
    

    to

    from Views import Home
    
  2. Another option would be to move start.py up one level, out of the Blog directory. Then when you call python start.py, the directory containing start.py will also be the directory containing Blog. So Python would find Blog when executing from Blog.Views ...

  3. Finally, you could add the Blog directory to your PYTHONPATH environment variable.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!