Okay, here’s my confession…
I really like Python as a systems language; I do NOT like Python as a web language. It’s probably because I’m old, hard-headed and set in my ways, but every Python web thing seems to complicate things that have been simple for over a decade, but makes complicated things simple. The problem is, I’m a really, really simple guy. I’ve been coding (poorly) for twenty years–over 30 if you go back to my teenage years, which were filled with shenanigans. I’ve seen languages come and go, and come back again. I say all that to say this, Python for web junk just got a whole lot better for me. Stick around and I’ll tell you why, or turn away now. The choice is yours.
No need to reinvent the wheel
We recently had (and still have) a need to convert a lot of command line tools that we use internally into web services for use in our new, freshly upgraded portal (that clients will likely see between now and 2025). We need to be able to simply take something, whether that’s something we’ve been using for years or something new, and webify it.
There are all sorts of hacky ways to do this in just about every language. But the one I turned to, so that I could really hack it up, was Python. Lots of reasons for this, but primarily because most of our internal stuff is written in Python, so it was a good choice all around and I figured “hey, we just need to spit out some results from existing things, so no need to reinvent the wheel.” In simpler terms, we didn’t have to reproduce all of the logic from the tool, just the input and the results. This is when I was given a little hug.
import hug Import requests @hug.get(‘/cve’, versions=1) #this tells hug to build a “route” to the function cve and make it available for versions 1 and 2 (I will explain this later) def cve(cve_number): get_cve = requests.get(‘http://cve.mitre.org/cgi-bin/cvename.cgi?name=’+cve_number) return get_cve
Now, if you’re still with me, let’s look at why hug is so neat. Fair warning, their tutorial is WAY better than mine, so definitely check out their website.
Alright, let’s write some simple code that really highlights hug’s features. Let’s say I want to write a web service (scary) that takes some input and queries the CVE repository over at Mitre. Here we go:
Pretty simple, huh? Told you I was a simple guy. Let’s run this and see what we get.
Running any Python web thing in production is the topic of several blogs posts and many more books. It is unnecessarily complicated at times but basically you need something that understands and interprets the code, and something to really serve it, usually a reverse proxy. All the cool kids are using Nginx these days, which is why I stick with Apache, but you can pick your poison there. Regardless, for our purposes, we’ll use Hug’s built web stuff. Do NOT ever use this in production, you have been warned.
Let’s get our little web service running
On the command line run hug -f get_cve.py (assuming that’s what you named it):