+def encode_url(urlstr):
+ # Oh, this is a disaster. We're given a URL as a `str', but the underlying
+ # machinery insists on having `bytes'. Assume we've been given a sensible
+ # URL, with escaping in all of the necessary places, except that it may
+ # contain non-ASCII characters: then encode as UTF-8 and squash the top-
+ # bit-set bytes down to percent escapes.
+ #
+ # This conses like it's going out of fashion, but it gets the job done.
+ return b''.join(bytes([b]) if b < 128 else '%%%02X' % b
+ for b in urlstr.encode('utf-8'))
+