Feeds, python and the creation of tool II - The code

Last Update: 09.12.2006. By azarai in python | spreadshirt

As stated in part one i’ll provide and explain some of the code. I’ll deploy the whole source code some time later. Until that you can use the online version (which will stay online).

Used modules:
As in the earlier feed examples, i used the universal feed parser and jinja as the tempating system. The tool is designed as a webapp and currently i use mod_python for that. I’d like to learn at least some of the basics, before i move on. Later i will probably switch to pure WSGI or to a framework like django.

The template is just for generating the output and is without any business logic. For data transport between business logic and templating i am using this dataclass:

class Product:  
    imageUrl = None  
    price = None  
    url = None  
    description = None  
    title = None  
    orig = None

The fields should be self explaining, the orig contains the whole unparsed description of a feed item. That what sppreadshirt is giving us.
Another base class i used is for configuration. Not sure yet whats the common way in python for configuration, but for now i use a simpel class containing all configs. For now:

class Config:  
    templateDir = 'path to templates'  
    layouts = {'divs': 'resultDivs', 'divtable': 'resultDivTable','zipzack': 'resultZipzack'}

Layouts is a dictionary with supported layouts. The value of a key/value pair is the name of the template without file extension.

Our App supports two methods, one for displaying the index and the trigger of the product teaser generation.

def index(req):

def transform(req, yourshopid, shoptype, layout):

Index just generates the index page with the formular on it. transform just, guess what, does the magic work. We analyse which feed to get and parse the whole data and create for each item found a product object. The fields are parse via regexp from the feed items description field. If they change someday the output we need to adjust the regexp. Done that, we just call out template system and give it a list with the products.
Eg output for divs template

{% extends "resultBase" %}  
{% block "content" %}  
{% if products %}  
    {% for product in products %}  
       <div class="product">  
                <div class="title">{{ product.title }}</div>  
                <div class="image"><a href="{{ product.url }}"><img src="{{ product.imageUrl }}" class="productImage" alt=""/></a></div>  
            <div class="description">{{ product.description }}</div>  
            <div class="price">{{ product.price }}</div>  
    </div>        
    {% endfor %}  
{% else %}  
 <p>No products are available.</p>  
{% endif %}  
{% endblock %}

I like the Template Inheritance of jinja, so i created a base template for the whole app and one specific parent for the resultpages. They rest just subclass and concentrate on their real work, displaying each product.

Happy commenting :-)