hellogoodbyeokgo
hellogoodbyeokgo

Reputation: 41

Structure Flask project so I can import my app in other files

I built this app a few months ago on the flask server and it was working perfectly. I have uploaded all files into the right directories but I keep getting an Unhandled Exception saying there is No module named app.

Here is my structure:

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

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

In my wsgi.py file:

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

And finally some of the errors in my error log:

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

It's probably just something small, it usually is, but I can't seem to find it. Can anyone help?

Upvotes: 0

Views: 1339

Answers (1)

davidism
davidism

Reputation: 127180

It looks like you're trying to refer to your project as a package. You need to actually create a package called "app" if you want to do 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`

In this case the Flask app should be defined in __init__.py so that importing it from the myapp modules works. Realistically, this naming scheme makes no sense, it looks like myapp.py should really be called views.py.

Upvotes: 1

Related Questions