Created
March 17, 2011 15:14
-
-
Save eykd/874485 to your computer and use it in GitHub Desktop.
Safely escape a URL that has a hash fragment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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