Behavior, Content, Money – 3 Things you should never give away for free!!!

BCmoney MobileTV

Learning Python

Posted by bryan on July 3, 2011 in Python, Web Services with No Comments


No Gravatar
Python logo

Image via Wikipedia

This month I strongly considered taking a full-time position with Keane IT Services (which was recently acquired by NTT Data). Unfortunately, it turned out that role wasn’t a good fit for where I’m at professionally and the responsibilities I have for my family (but it looks like another opportunity I received might be a better fit). As part of the position, I would have needed to beef up my Python skills since one of their client’s Remote Monitoring systems uses it heavily. Not being sure of which version of Python they use, I followed the advice on the official Python site and started with the latest and greatest – version 3.2 – which represents the future of the language.

While learning, I also wanted to make a short course for my wife, because if I could teach her the basics then it would be the perfect proof that I had a handle on the core of the language. Together we successfully walked through the basics of mathematics, string operations, lists, returning values, running a program and packaging a module. I had done some things in Python before but they were mostly around debugging or updating a small section of someone else’s code (i.e. tweaked a Message consumer here, structured a SOAP call there).

Learning from existing code is definitely always the quickest way to learn for me though. To this end,  Dive Into Python 3 is hands down one of the best resources other than the Python documentation or official tutorial itself, since it provides code samples. In honesty what helped me most though, was probably the free course offered by Google, which I essentially simplified and repackaged when teaching my wife at home.

After going through the course and feeling a bit confident, I was ready for my first real Python 3.2 program (other than the typical command-line testing and Hello World app). For this I decided to update the Yahoo! Weather Python SDK from 2.x to 3.x and create a Python 3 module for accessing Yahoo! Weather and wrapping their XML Web Services as JSON for consumption by a client. For the client itself, I could have easily written most of the parsing code (if not everything) in my usual manner of using client-side code (i.e. JavaScript) as much as possible then interacting with external Web Services via a server-side proxy, but just for fun and completeness of doing it all server-side I did it all Python style, including outputting the HTML to display the weather report. That way, you can interact with the “index.py” file directly from the browser as a CGI script within Apache that accepts user input via GET submitted from its form, or, interactively via the URL (the URL hacking took a bit of time to get my head around in Python).

#!/usr/bin/python -tt
######################################################
# yahoo_weather
#   Grabs forecasts from the Yahoo! Weather API
# @param zip_code
# @return condition JSON
######################################################
#Step 1 - IMPORTS
import sys
import xml.etree.ElementTree as weather
from urllib.request import urlopen

WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'


#Step 2 - FUNCTIONS
def weather_for_zip(zip_code):
    url = WEATHER_URL % zip_code
    rss = weather.parse(urlopen(url)).getroot()
    forecasts = []
    for element in rss.findall('channel/item/{%s}forecast' % WEATHER_NS):
        forecasts.append({
            'date': element.get('date'),
            'low': element.get('low'),
            'high': element.get('high'),
            'condition': element.get('text')
        })
    ycondition = rss.find('channel/item/{%s}condition' % WEATHER_NS)
    condition = ycondition.get('text')
    temperature = ycondition.get('temp')
    title = rss.findtext('channel/title').replace("Yahoo! Weather - ","")
    return {
        'current_condition': condition,
        'current_temp': temperature,
        'forecasts': forecasts,
        'title': title 
    }
    
def main():
  if len(sys.argv) >= 2:
    print(weather_for_zip(sys.argv[1]))
  else:
    print("ERROR: Please enter your Zip Code when calling the program.")
  
  
#Step 3 - ACTIVATE FUNCTION
if __name__ == '__main__':
  main()

Next, you can call this module from a web-accessible endpoint “index.php” as follows:

#!/usr/bin/python -tt
#Step 1 - IMPORTS
import urllib
from urllib.parse import urlparse
import yahoo_weather


#Step 2 - PROCESSING DATA
url = self.request.query_string #python2:  urlparse( request.environ.get('PATH_INFO') )
if (url['zip'] != None):
  weather = weather_for_zip(url['zip'])
else:
  weather = "ERROR: Please enter your Zip Code when calling the program."
  

#Step 3 - OUTPUT
print("PYTHON - Weather Forecast (provided by Yahoo! Weather)",weather,"")

In any case I now know there aren’t too many huge differences between Python 2.x and 3.x but there are some notable ones such as the requirements that print statements become true functions and thusly use an opening and closing parenthesis as follows:

print "some text"

becomes:

print("some text")

And other than that major bit of rocket science single quoted strings are treated as individual bytes instead of blocks of text, so for example:

list('text')

gives:

['t', 'e', 'x','t']

rather than:

['text']

meanwhile:

list("text")

would give:

["text"]

One of the best things about version 3 is that the default encoding is now UTF-8, so multi-language programming and supporting internationalization of content has never been easier.

Conclusion

Python is different from Java, PHP and Perl in a great many ways, but you can clearly see where the languages and communities overlap. I think that knowing just enough Perl to get myself in trouble, and being quite familiar with PHP will help me to get up to speed with modern Python development pretty quickly though, while my Java background means I can get my head around dependencies and managing the import hierarchy of modules.

If I were to go any further in my studies, I think I’d tackle the Django framework since I’ve been told by some more dedicated Python programmers that it is essential to know. The only issue is that as of this writing I think its still not fully ported to Python 3.x? Well, it’s worth a look anyway to get a handle on how web frameworks are used in Python, though I probably won’t be using Python much if at all in my new role (Java-based development shop), it never hurts to learn something new.

 

Related articles

« previous post

Leaving Sony and Japan">