While I have been playing with Python for a few months now (just a hobbyist), I know very little about Web programming (a little HTML, zero JavaScript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask:
What's easiest way to get Python script output on the web?
Thx to the answers, I made some progress. For now, I’m just using Python and HTML. I can’t post my project code, so I wrote a small example using twitter search (pls see below).
My questions are:
-
Am I doing anything terribly stupid? I feel like
WebOutput()is clear but inefficient. If I used JavaScript, I’m assuming I could write an HTML template file and then just update the data. Yes? The better way to do this? -
At what point would a framework be appropriate for an app like this? overkill?
Sorry for the basic questions – but I don’t want to spend too much time going down the wrong path.
import simplejson, urllib, time
#query, results per page
query = "swineflu"
rpp = 25
jsonURL = "http://search.twitter.com/search.json?q=" + query + "&rpp=" + str(rpp)
#currently storing all search results, really only need most recent but want the data avail for other stuff
data = []
#iterate over search results
def SearchResults():
jsonResults = simplejson.load(urllib.urlopen(jsonURL))
for tweet in jsonResults["results"]:
try:
#terminal output
feed = tweet["from_user"] + " | " + tweet["text"]
print feed
data.append(feed)
except:
print "exception??"
# writes latest tweets to file/web
def WebOutput():
f = open("outw.html", "w")
f.write("<html>\n")
f.write("<title>python newb's twitter search</title>\n")
f.write("<head><meta http-equiv='refresh' content='60'></head>\n")
f.write("<body>\n")
f.write("<h1 style='font-size:150%'>Python Newb's Twitter Search</h1>")
f.write("<h2 style='font-size:125%'>Searching Twitter for: " + query + "</h2>\n")
f.write("<h2 style='font-size:125%'>" + time.ctime() + " (updates every 60 seconds)</h2>\n")
for i in range(1,rpp):
try:
f.write("<p style='font-size:90%'>" + data[-i] + "</p>\n")
except:
continue
f.write("</body>\n")
f.write("</html>\n")
f.close()
while True:
print ""
print "\nSearching Twitter for: " + query + " | current date/time is: " + time.ctime()
print ""
SearchResults()
WebOutput()
time.sleep(60)
It would not be overkill to use a framework for something like this; Python frameworks tend to be very light and easy to work with and would make it much easier for you to add features to your tiny site. But neither is it required; I’ll assume you’re doing this for learning purposes and talk about how I would change the code.
You’re doing templating without a template engine in your
WebOutputfunction; there are all kinds of neat template languages for Python, my favorite of which is mako. If the code in that function ever gets hairier than it is currently, I would break it out into a template; I’ll show you what that would look like in a moment. But first, I’d use multiline strings to replace all thosef.write‘s, and string substitution instead of adding strings:Also, note that I simplified your for loop a bit; I’ll explain further if what I put doesn’t make sense.
If you were to convert your
WebOutputfunction to Mako, you would first import mako at the top of your file with:Then you would replace the whole body of WebOutput() with:
Finally, you would make a file
/path/to/mytmpl.txtthat looks like this:And you can see that the nice thing you’ve accomplished is separating the output (or "view layer" in web terms) from the code that grabs and formats the data (the "model layer" and "controller layer"). This will make it much easier for you to change the output of your script in the future.
(Note: I didn’t test the code I’ve presented here; apologies if it isn’t quite right. It should basically work though)