Random Python and WSGI tip

In light of the fact that Python 2.x loses support...now, I've been upgrading some of my personal projects that I haven't done much with recently to Python 3.  One of them is a little web-based comic book reader I call Linga (I don't remember why) that I run on my home network.

Since my home server runs Ubuntu 18.04 LTS, where Python 2.7 is the default, this has been a bit of a pain.  Before doing the conversion to Python 3.x, I had Linga set up and working using MySQL and Apache with mod_wsgi.  But once I pushed the code for the 3.x version, everything broke.  After digging in, there were several problems I needed to correct:

  1. The default mod_wsgi install uses Python 2.7, not 3.6 like I want.
  2. My WSGI script uses execfile(), which no longer exists in Python 3.x.
  3. SQLAlchemy can't load the MySQLdb module.

Luckily, the solutions to these problems weren't particularly hard to find or implement.  With a little Googling (well, DuckDuckGo-ing really, but that doesn't have the same ring to it) and a little experimentation, I found the following fixes:

  1. The version of Python to use is hard-coded into the Apache module.  So to use Python 3.6 I just needed to install the Python 3 WSGI module with apt install libapache2-mod-wsgi-py3.
  2. Apparently the recommended replacement for execfile("filename") is exec(open("filename").read()).
  3. It seems that Zen of Python's saying that "There should be one-- and preferably only one --obvious way to do it" breaks down when it comes to connecting to MySQL, as there are apparently several client libraries available.  The solution that worked for me was to pip install pymysql and run pymysql.install_as_MySQLdb() in my WSGI script.  Having to call a method to turn on MySQLdb compatibility is annoying and seems a little hacky, but it works and it's not really a big deal.

With that, Linga now works just fine.  Maybe this will save someone else having to Google the answers to these questions as well.

You can reply to this entry by leaving a comment below. You can send TrackBack pings to this URL. This entry accepts Pingbacks from other blogs. You can follow comments on this entry by subscribing to the RSS feed.

Add your comments #

A comment body is required. No HTML code allowed. URLs starting with http:// or ftp:// will be automatically converted to hyperlinks.