blog.humaneguitarist.org

trying to easily format Solr results as HTML with Python

[Sat, 21 Jan 2012 17:03:49 +0000]
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 = 'http://data.twigkit.com/solr-gutenberg/select/?q=poe&version=2.2&start=0&rows=5&wt=python&explainOther' 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: >>> <br/> <type 'str'><br/> <type 'dict'><br/> <span class="solr_id">etext8893</span><br/> <p class="solr_title">Selections from Poe</p><br/> <span class="solr_id">etext9511</span><br/> <p class="solr_title">Several Works by Edgar Allan Poe</p><br/> <span class="solr_id">etext9512</span><br/> <p class="solr_title">The Works of Edgar Allan Poe, Volume 1</p><br/> <span class="solr_id">etext9516</span><br/> <p class="solr_title">The Works of Edgar Allan Poe, Volume 5</p><br/> <span class="solr_id">etext9513</span><br/> <p class="solr_title">The Works of Edgar Allan Poe, Volume 2</p><br/> 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 [http://tempojs.com/] which is super light-weight. But for now, I need to remind myself it's the weekend. :P