trying to easily format Solr results as HTML with Python

Just a quick Saturday morning post …

One of the nice things about Solr is the ability to pass parameters that will return the results in various formats, including a Python dictionary.

I wanted to see if I could whip up a little function that would let me pass to it both the name of a Solr element (like "title") and then the HTML element I want it mapped to.

It doesn't seem that bad, and is a good reminder that building UIs is in large part about parsing data into HTML, upon which things like CSS and JavaScript can enter and act re: display and interface.

Anyway, so here's an example of some code that gets five results from a Solr instance and then uses the function I wrote to output some HTML elements:

import urllib2 as urllib

### first, get 5 Solr results formatted as a Python dictionary
query_url = ''
solr = urllib.urlopen(query_url).read() #read the results
print type(solr) #returns that it's a string :-[
solr = eval(solr) #turns the string into a dictionary. yay.
print type(solr) #returns that it's now a dictionary!

### second, write a function that converts stuff to HTML
def pysolr2html(tagIn, tagOut):
    tagVal = solr['response']['docs'][i][tagIn]
    htmlVars = (tagOut, tagIn, tagVal, tagOut)
    return '<%s class="solr_%s">%s</%s>' %htmlVars

### third, iterate over the response
i = 0
for doc in solr['response']['docs']:
    print pysolr2html('id','span')
    print pysolr2html('title','p')
    i = i + 1

And here's the output from IDLE:

<type 'str'>
<type 'dict'>
<span class="solr_id">etext8893</span>
<p class="solr_title">Selections from Poe</p>
<span class="solr_id">etext9511</span>
<p class="solr_title">Several Works by Edgar Allan Poe</p>
<span class="solr_id">etext9512</span>
<p class="solr_title">The Works of Edgar Allan Poe, Volume 1</p>
<span class="solr_id">etext9516</span>
<p class="solr_title">The Works of Edgar Allan Poe, Volume 5</p>
<span class="solr_id">etext9513</span>
<p class="solr_title">The Works of Edgar Allan Poe, Volume 2</p>

I'll probably do this with PHP in the end and see how easy it might be to make a small Solr wrapper, kind of like Tempo which is super light-weight. But for now, I need to remind myself it's the weekend.



Related Content:

Leave a Comment

Your email address will not be published. Required fields are marked *