Internal Server Error with Flask app on Apache using Raspbian
Question: I can successfully deploy my flask app from the localhost:5000 but I get an
internal server error 500 when connecting through a web browser at
raspberrypi.local and the same error when I tried the RPi's IP

apache error log shows

    
    
    Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] mod_wsgi (pid=2081): Target WSGI script '/var/www/Intr
    anet_for_RPi/Intranet_for_RPi.wsgi' cannot be loaded as Python module.
    [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] mod_wsgi (pid=2081): Exception occurred processing WSG
    I script '/var/www/Intranet_for_RPi/Intranet_for_RPi.wsgi'.
    [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] Traceback (most recent call last):
    [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118]   File "/var/www/Intranet_for_RPi/Intranet_for_RPi.wsg
    i", line 7, in <module>
    [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118]     from Intranet_for_RPi import app as application
    [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] ImportError: No module named Intranet_for_RPi
    

/etc/apache2sites-available/

    
    
    <VirtualHost *:80>
                    ServerName raspberrypi
                    ServerAdmin admin@website.com
                    WSGIScriptAlias / /var/www/Intranet_for_RPi/Intranet_for_RPi.wsgi
                    <Directory /var/www/Intranet_for_RPi/Intranet_for_RPi/>
                            Order allow,deny
                            Allow from all
                            WSGIScriptReloading On
                    </Directory>
                    Alias /static /var/www/Intranet_for_RPi/Intranet_for_RPi/static
                    <Directory /var/www/Intranet_for_RPi/Intranet_for_RPi/static/>
                            Order allow,deny
                            Allow from all
                    </Directory>
                    ErrorLog ${APACHE_LOG_DIR}/error.log
                    LogLevel warn
                    CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    

flask file

    
    
    # all the imports
    from __future__ import with_statement
    import sqlite3
    import os
    from contextlib import closing
    from flask import Flask, request, session, g, redirect, url_for, \
            abort, render_template, flash, send_from_directory
    from werkzeug import secure_filename
    
    # configuration
    DATABASE = '/tmp/flaskr.db'
    DEBUG = True
    SECRET_KEY = 'key-gen secret'
    USERNAME = 'admin'
    PASSWORD = 'default'
    
    app = Flask(__name__)
    app.config.from_object(__name__)
    app.config.from_envvar('FLASKR_SETTINGS', silent=True)
    
    # This is the path to the upload directory
    app.config['UPLOAD_FOLDER']='/var/www/Intranet_for_RPi/Intranet_for_RPi/uploads'
    # These are the extensions that we are accepting to be uploaded
    app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'jpg', 'jpeg', 'gif'])
    
    # For a given file, return whether it's an allowed type or not
    def allowed_file(filename):
            return '.' in filename and \
                    filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
    
    # This route will show a form to perform an AJAX request
    # jQuery is loaded to execute the request and update the value of the operation
    @app.route('/index')
    def index():
            return render_template('index.html')
    
    # Route that will process the file upload
    @app.route('/upload', methods=['POST'])
    def upload():
            # Get the name of the uploaded files
            uploaded_files = request.files.getlist("file[]")
            filenames = []
            for file in uploaded_files:
                    # Check if the file is one of the allowed types/extensions
                    if file and allowed_file(file.filename):
                            #Make the filename safe, remove unsupported chars
                            filename = secure_filename(file.filename)
                            #Move teh file from the temporal folder to the upload folder we setup
                            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                            # Save teh filename into a list, we'll use it later
                            filenames.append(filename)
                            # Redirect the user to the uploaded_file route, which will basically
                            # show on the browser the uploaded file
            # Load an html page with a link to each uploaded file
            return render_template('upload.html', filenames=filenames)
    
    # This route is expecting a parameter containing the name of a file. Then it will locate that
    # file on the upload directory and show it on the browser, so if the user uploads an image,
    # that image is going to be shown after the upload.
    @app.route('/uploads/<filename>')
    def uploaded_file(filename):
            return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
    
    
    def connect_db():
        return sqlite3.connect(app.config['DATABASE'])
    
    def init_db():
        with closing(connect_db()) as db:
            with app.open_resource('schema.sql') as f:
                db.cursor().executescript(f.read())
            db.commit()
    
    @app.before_request
    def before_request():
        g.db = connect_db()
    
    @app.teardown_request
    def teardown_request(exception):
        g.db.close()
    
    @app.route('/')
    def show_entries():
        cur = g.db.execute('select title, text from entries order by id desc')
        entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
        return render_template('show_entries.html', entries=entries)
    
    @app.route('/add', methods=['POST'])
    def add_entry():
        if not session.get('logged_in'):
            abort(401)
        g.db.execute('insert into entries (title, text) values (?, ?)',
                [request.form['title'], request.form['text']])
        g.db.commit()
        flash('New entry was successfully posted')
        return redirect(url_for('show_entries'))
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        error = None
        if request.method == 'POST':
            if request.form['username'] != app.config['USERNAME']:
                error = 'Invalid username'
            elif request.form['password'] != app.config['PASSWORD']:
                error = 'Invalid password'
            else:
                session['logged_in'] = True
                flash('You were logged in')
                return redirect(url_for('show_entries'))
        return render_template('login.html', error=error)
    
    @app.route('/logout')
    def logout():
        session.pop('logged_in', None)
        flash('You were logged out')
        return redirect(url_for('show_entries'))
    
    @app.route('/files')
    def files():
      return render_template('files.html')
    
    if __name__ == '__main__':
        app.run()
    

Here is my wsgi file

    
    
    #!/usr/bin/python
    Import sys
    import logging
    logging.basicConfig(stream=sys.stderr)
    sys.path.insert(0,"/var/www/Intranet_for_RPi/")
    from Intranet_for_RPi import app as application
    application.secret_key = 'key-gen-secret'
    

```

I have made the wsgi file executable. I think it may have something to do with
my python version or path pertaining to `/etc/apache2/mods-
available/wsgi.conf`.

Any help would greatly be appreciated


Answer: The error obviously says that the `wsgi` script can't find `Intranet_for_RPi`
module.  
Check your paths. You might need to add `WSGIPythonPath` to your apache
configuration:

    
    
    WSGIPythonPath /var/www/Intranet_for_RPi:/var/www/Intranet_for_RPi/packages:etc
    <VirtualHost *:80>
        ...
    

