Recommended books

How to retrieve information about Python errors in a C extension

Python posted 6 months ago by christian

   1  result = PyEval_CallObject(tmp_callback, args);
   2      // result == NULL means an error occured
   3      if (PyErr_Occurred()) {
   4          PyObject* ptype;
   5          PyObject* pvalue;
   6          PyObject* ptraceback;
   7          PyErr_Fetch(&ptype, &pvalue, &ptraceback);
   8          printf("Error occurred on line: %d", ((PyTracebackObject*)ptraceback)->tb_lineno);
   9          // Restore exception instead of disposing of it
  10          PyErr_Restore(ptype, pvalue, ptraceback);
  11          PyErr_Print();
  12  
  13          Py_XDECREF(ptype);
  14          Py_XDECREF(pvalue);
  15          Py_XDECREF(ptraceback);
  16      }

via http://www.ragestorm.net/tutorial?id=21

Tagged python, pyeval_callobject, pyerr_fetch

How to use a Python decorator wrapper to get a reference to the calling class instance

Python posted 6 months ago by christian

   1  def requires_authentication(method):
   2      """
   3      self points to a SheisseController instance instead of the decorator function.
   4      """
   5      def wrapper(self, *args, **kwargs):
   6          if self._requires_authentication == True and self._authenticated == False:
   7              return response('403 Forbidden or whatever')
   8  
   9          return method(self, *args, **kwargs)
  10      return wrapper
  11  
  12  class SheisseController:
  13    @requires_authentication
  14    def index(self):
  15  

Tagged python, decorator, self

How to parse XML with Python's built-in ElementTree parser

Python posted 7 months ago by christian

   1  from xml.etree.ElementTree import fromstring, tostring
   2  
   3  namespace = 'https://xxx.com/xxx'
   4  element = fromstring(xml)
   5  
   6  device = element.find('.//{%s}Device' % namespace)
   7  detail = device.find('.//{%s}Details' % namespace)
   8  series = device.findall('.//{%s}Series' % namespace)

Watch out for namespaces…

Tagged elementtree, python, xml, parse

How to use Python's simplejson to read and write JSON data

Python posted 7 months ago by christian

First you need to install simplejson:

   1  easy_install simplejson

Now you can dump data to JSON:

   1  import simplejson as json
   2  
   3  class Something:
   4  
   5      def __init__(self):
   6          self.test = "test"
   7  
   8      def to_json(self):
   9          return json.dumps(self.__dict__)

Or if you have complex objects:

   1  import simplejson as json
   2  class Something:
   3  
   4      def __init__(self):
   5          self.test = [Other('a', 'b'), Other('a', 'c')]
   6  
   7      def to_json(self):
   8          return json.dumps([p.__dict__ for p in self.devices])

Tagged simplejson, python, json

A simple Python HTTP client

Python posted over 2 years ago by christian

A simple HTTP client I had lying around that I wrote a long time ago. It supports cookies, redirects and stuff:

   1  #!/usr/bin/env python
   2  #
   3  #     Http
   4  #
   5  #     A simple HTTP client that supports persistent cookies
   6  #
   7  
   8  import cookielib
   9  import httplib
  10  #httplib.HTTPConnection.debuglevel = 1
  11  import urllib2
  12  
  13  class Http:
  14    def __init__(self, redirect_callback = None):
  15      self.redirect_callback = redirect_callback
  16      self.cookie_jar = cookielib.CookieJar()
  17      self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor (self.cookie_jar))
  18  
  19      urllib2.install_opener(self.opener)
  20  
  21    def get(self, url, headers = None):
  22      request = urllib2.Request(url, headers = headers)
  23      return self.execute_request(request)
  24  
  25    def post(self, url, headers = None, parameters = None):
  26      data = None
  27      if parameters != None:
  28        data = urllib.urlencode(parameters)
  29  
  30      request = urllib2.Request(url, data, headers)
  31      return self.execute_request(request)
  32  
  33    def execute_request(self, request):
  34      response = self.opener.open(request)
  35      # Check for redirect, maybe better way to do this
  36      if response.geturl() != request.get_full_url():
  37        if self.redirect_callback == None:
  38          raise "Redirected to '" + response.geturl() + "' but no redirect callback defined"
  39        else:
  40          self.redirect_callback(response)
  41  
  42      return response
  43  

Tagged python, http, client