Archive for the ‘Python’ Category

Python Wrapper For The Phish.net API

While browsing the Phish.net API documentation I noticed that it was missing a Python wrapper.  So I said to my self, this sound like a quick and fun project to test out my Python <cough> skills </cough>.

Just update the method variable to which ever method you are using and add the remaining parameters if necessary.  Here is more docuemtation on the Phish.net API and where to apply for one.

While you are at it check out Adam Scheinberg and my official Phish.Net Google Chrome Extension.

FYI, This is only been tested on Python 2.7.1.  I am pretty sure that it will not work in Python 3.

#Query Phish.net API via Python 2.71.
 
import urllib, json, sys
 
url='https://api.phish.net/'
js='api.js'
 
apikey = 'Your API Key'
format = 'json'
apiver = '2.0'
method = 'pnet.shows.setlists.latest'
 
#Build parameters to send via GET to api.js
params = urllib.urlencode({
  'api':apiver,
  'method':method,
  'format':format,
  'apikey':apikey
  })
 
#Attempt to open a connection and get the JSON formated data
try:
  f = urllib.urlopen(url + js + "?%s" % params)
 
#Do this for invalid URL
except IOError:
  print 'Error: Unable to connect. Invalid URL. '
  sys.exit(1)
 
#Get the response code
rsp = f.getcode()
 
#If the HTTP response is 200 (OK) then proceed
if rsp == 200:
 
  #Read the data
  data =  f.read()
 
  #Decode the data as JSON
  decoded = json.loads(data)
 
  #Print the Decoded JSON
  print 'DECODED: ', decoded
 
  #Print an individual JSON Record
  print 'GET INDIVIDUAL RECORD: ', decoded[0]['showdate']
 
else:
  #Do this if the not an HTTP response of 200
  print 'Error: ',  rsp
 
#close the connection
f.close()

I have submitted this to the Phish.net administrators and if it gets the Ok then it will be uploaded here.

Update: The code has been posted on Phish.net site.

Update 2: I forgot to give proper credit to Adam for his help on the Phish.net Chrome Extension.

Writing Traceroute in Python

Ksplice.com has put together a tutorial on how to write the traceroute/tracert application in Python in just 8 easy steps.  This is a good introduction on how the traceroute application works and socket programming in Python.

Here is the finished product but please read thier post to see all of the steps.

#!/usr/bin/python
 
    import socket
 
    def main(dest_name):
        dest_addr = socket.gethostbyname(dest_name)
        port = 33434
        max_hops = 30
        icmp = socket.getprotobyname('icmp')
        udp = socket.getprotobyname('udp')
        ttl = 1
        while True:
            recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
            send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
            send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
            recv_socket.bind(("", port))
            send_socket.sendto("", (dest_name, port))
            curr_addr = None
            curr_name = None
            try:
                _, curr_addr = recv_socket.recvfrom(512)
                curr_addr = curr_addr[0]
                try:
                    curr_name = socket.gethostbyaddr(curr_addr)[0]
                except socket.error:
                    curr_name = curr_addr
            except socket.error:
                pass
            finally:
                send_socket.close()
                recv_socket.close()
 
            if curr_addr is not None:
                curr_host = "%s (%s)" % (curr_name, curr_addr)
            else:
                curr_host = "*"
            print "%d\t%s" % (ttl, curr_host)
 
            ttl += 1
            if curr_addr == dest_addr or ttl > max_hops:
                break
 
    if __name__ == "__main__":
        main('google.com')

First Python Program

I have been off and on trying to learn Python for a few months now and yesterday I successfully finished my first real application. Unfortunately it was for work and I cannot post the source code for you all to tear a part. But it was an application displayed a menu that allowed the user to choose and made several Oracle database calls using the module cx_Oracle to test some functionality of my companies application.

There was that vague enough?

To make it useful I had to use the py2exe application to make it into a Windows executable. I had to step down my version of Python from 2.6 to 2.4 to get the py2exe compiled python application to work due to the version of C++ that Python 2.4 and 2.6 are compiled with.

I hope to start making some useful applications in the near future where I can post the source code and you all comment on and tear apart.

View Oracle dbms_output with Python

After doing lots of searching on the Internet for how to get the dbms_output from an Oracle SQL query with Python I finally found something.

import cx_Oracle
 
conn = cx_Oracle.Connection("userid/password@tns")
curs = conn.cursor()
curs.callproc("dbms_output.enable")
 
sqlCode = """
some long
sql code 
with dbms_output
"""
 
curs.execute(sqlCode)
 
statusVar = curs.var(cx_Oracle.NUMBER)
lineVar = curs.var(cx_Oracle.STRING)
while True:
  curs.callproc("dbms_output.get_line", (lineVar, statusVar))
  if statusVar.getvalue() != 0:
    break
  print lineVar.getvalue()

Barcode Scanner Written For Android Phones in Just 6 Lines of Code

Here’s a barcode scanner written in six lines of Python code using the Google released the Android Scripting Environment (ASE):

import android droid = android.Android()
code = droid.scanBarcode() isbn = int(code[‘result’][‘SCAN_RESULT’])
url = “http://books.google.com?q=%d” % isbn
droid.startActivity(‘android.intent.action.VIEW’, url)

This is just a proof-of-concept but it show the power and ease of Google’s Python scripting tools when combined with Android.

Written By Matt Cutts (Sorry I don’t have the original link)