在Raspbian上使用Apache的Flask应用出现内部服务器错误

-1 投票
1 回答
1264 浏览
提问于 2025-04-18 13:21

我可以成功地在本地的5000端口上运行我的flask应用,但当我通过浏览器访问raspberrypi.local时,却出现了500内部服务器错误,使用树莓派的IP地址也是同样的错误。

apache的错误日志显示:

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/apache2/sites-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文件

# 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()

这是我的wsgi文件:

#!/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'

```

我已经把wsgi文件设置为可执行的。我觉得这可能和我的python版本或者与/etc/apache2/mods-available/wsgi.conf相关的路径有关系。

任何帮助都会非常感谢。

1 个回答

0

这个错误明显是说,wsgi 脚本找不到 Intranet_for_RPi 这个模块。
检查一下你的路径。你可能需要在 Apache 的配置中添加 WSGIPythonPath

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

撰写回答