Skip to content

Instantly share code, notes, and snippets.

@eykd
Created March 17, 2011 15:14
Show Gist options
  • Save eykd/874485 to your computer and use it in GitHub Desktop.
Save eykd/874485 to your computer and use it in GitHub Desktop.
Safely escape a URL that has a hash fragment.
def escape(self, url):
# We don't want to escape the hash, if it exists.
if '#' in url:
url, fragment = url.split('#', 1)
else:
fragment = ''
# Escape the body of the URL and fragment
def _escape(url):
return '/'.join(
urllib.quote_plus(
self.spaces_cp.sub('+', u).replace(':', '.'))
for u in url.split('/')
)
url = _escape(url)
if fragment:
fragment = _escape(fragment)
# Re-join the fragment, if it exists.
if fragment:
url = '%s#%s' % (url, fragment)
return url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment