结构Flask项目,所以我可以导入我的应用程序在其他文件中

时间:2015-06-08 16:10:39

标签: python flask

我几个月前在烧瓶服务器上构建了这个应用程序,它运行得很好。我已将所有文件上传到正确的目录中,但我仍然收到一个未处理的异常,说没有名为app的模块。

这是我的结构:

 /static/
       (all static files)
 /templates/
       (all html files)
 myapp.py

在myapp.py中:

from app import app
from flask import render_template, redirect, request, url_for

#index - Home page containing images for the trailer, discussion thread and cast
@app.route('/')
@app.route('/index')
def index():
    page_info = {
        'title':'Star Wars - Forums',
    }
    img1 = 'pan.jpg'
    img2 = 'trailerlink.jpg'
    img3 = 'trailerdiscussion.jpg'
    img4 = 'episode7cast.jpg'
    return render_template('index.html', info=page_info, imgone=img1, imgtwo=img2,imgthree=img3, imgfour=img4)

在我的wsgi.py文件中:

import sys

# add your project directory to the sys.path
project_home = u'/home/myusername'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from myapp import app as application

最后我的错误日志中出现了一些错误:

File "/bin/user_wsgi_wrapper.py", line 122, in __call__ app_iterator = self.app(environ, start_response)
File "/bin/user_wsgi_wrapper.py", line 136, in import_error_application
raise e
ImportError: No module named app

它可能只是一些小的,通常是,但我似乎无法找到它。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

看起来您正试图将您的项目作为一个包引用。你需要实际创建一个名为" app"如果你想from app import app

myproject/
    app/
        __init__.py  # contains `app` object
        views.py  # was called myapp.py, does `from app import app`
        static/
        templates/
    wsgi.py  # does `from app import app as application`

在这种情况下,应在app中定义Flask __init__.py,以便从myapp模块中导入它。实际上,这个命名方案毫无意义,看起来myapp.py应该真正被称为views.py