4

I have the following code for parsing youtube feed and returning youtube movie id. How can I rewrite this to be python 2.4 compatible which I suppose doesn't support parse_qs function ?

YTSearchFeed = feedparser.parse("http://gdata.youtube.com" + path)
videos = []
for yt in YTSearchFeed.entries:
    url_data = urlparse.urlparse(yt['link']) 
    query = urlparse.parse_qs(url_data[4])
    id = query["v"][0]
    videos.append(id) 
mkrenge
  • 57
  • 1
  • 4

2 Answers2

13

I assume your existing code runs in 2.6 or something newer, and you're trying to go back to 2.4? parse_qs used to be in the cgi module before it was moved to urlparse. Try import cgi, cgi.parse_qs.

Inspired by TryPyPy's comment, I think you could make your source run in either environment by doing:

import urlparse # if we're pre-2.6, this will not include parse_qs
try:
    from urlparse import parse_qs
except ImportError: # old version, grab it from cgi
    from cgi import parse_qs
    urlparse.parse_qs = parse_qs

But I don't have 2.4 to try this out, so no promises.

Community
  • 1
  • 1
mtrw
  • 34,200
  • 7
  • 63
  • 71
  • So use: `try: from cgi import parse_qs; urlparse.parse_qs = parse_qs \n except ImportError: pass` – TryPyPy Jan 10 '11 at 13:01
  • Thanks, but it's only your answer... or just a small note on how to make use of it. Feel free to incorporate it, the better answers the better :) – TryPyPy Jan 10 '11 at 13:48
  • Why the `urlparse.parse_qs = parse_qs` line? I'm pretty sure this will fail, and `urlparse` won't be defined at this point. – Ben Hoyt Jan 10 '11 at 19:47
  • @benhoyt Because he already calls `urlparse.parse_qs`, so if we just say 'use cgi', he'll have to substitute the call. If he monkeypatches the module (and you're right, that has to be after importing urlparse), any calls to parse_qs should work OK. – TryPyPy Jan 10 '11 at 19:57
-3

I tried that, and still.. it wasn't working.

It's easier to simply copy the parse_qs/qsl functions over from the cgi module to the urlparse module.

Problem solved.

dmark
  • 1