Search code examples
pythonapachemod-wsgibottle

Deploying a Bottle.py app with Apache mod_wsgi on Ubuntu 16.04


I'm having a hard time deploying a Bottle app. I've tried using some of the suggested answers in past questions but I can't seem to get this working. I end up with a 500 Internal Server Error

This is my set up.

  • Ubuntu 16.04
  • Apache
  • libapache2-mod-wsgi-py3
  • Python 3.5

My .wsgi and app.py file sit at:

/var/www/bottle_app/

  • app.wsgi
  • app.py

app.wsgi is as follows

import os
# Change working directory so relative paths (and template lookup) work again
os.chdir(os.path.dirname(__file__))

import bottle
# ... build or import your bottle application here ...
import app
application = bottle.default_app()

app.py is as follows

from bottle import route
@route('/')
def hello():
    return 'Hello world'

Apache .conf file:

<VirtualHost *:80>
ServerName example.com 

WSGIDaemonProcess bottle_app user=bottle group=www-data processes=1 threads=5
WSGIScriptAlias / /var/www/bottle_app/app.wsgi

<Directory /var/www/bottle_app>
    WSGIProcessGroup bottle_app
    WSGIApplicationGroup %{GLOBAL}
    Require all granted
</Directory>

When I run python3 app.py, nothing is returned (I'm assuming this is expected) When I run python3 app.wsgi I get:

Traceback (most recent call last):
File "app.wsgi", line 3, in <module>
  os.chdir(os.path.dirname(__file__))
FileNotFoundError: [Errno 2] No such file or directory: ''

My Apache error logs show the following errors.

Target WSGI script '/var/www/bottle_app/app.wsgi' cannot be loaded as Python module
Exception occurred processing WSGI script '/var/www/bottle_app/app.wsgi
Traceback (most recent call last):
File "/var/www/bottle_app/app.wsgi", line 7, in <module>
   import app
ImportError: No module named 'app'

I did this on a clean Ubuntu install under user bottle with sudo privileges. This is probably the 10th time I've rebuilt using different suggestions from other questions from users who had similar problems. I was trying to avoid having to post a question that would seem like duplicate. Any help would be greatly appreciated.


Solution

  • Before you import your app module in the app.wsgi file, try:

    import sys
    sys.path.insert(0, '/var/www/bottle_app')
    

    A cleaner way might be to make use of the home or python-path parameters to the WSGIDaemonProcess entry in the Apache configuration.

    WSGIDaemonProcess bottle_app user=bottle group=www-data processes=1 threads=5 python-path=/var/www/bottle_app
    

    The __file__ isn't absolute, so if you need to get it's location for this type of purpose (where a controlling process like Apache might be doing funny things with paths) try:

    os.chdir(os.path.dirname(os.path.abspath(__file__)))