Decode URLs from Sage single cell server into Sage code
""" | |
Permalinks from the Sage cell server [1] include the Sage code in the URL, | |
and sometimes you may want to get that Sage code without loading the URL | |
in a browser. | |
The get_sage_code function does exactly that. It's basically copied from | |
web_server.py [2]. Just feed it the full URL and it returns the Sage | |
code. | |
The get_urls function is the inverse. It is essentially stolen from line | |
158 in the same file. It returns a list of URLs: the first is the | |
base64-encoded one, and if your code is short enough, there will be a | |
second "quoted" URL. | |
[1]: https://github.com/sagemath/sagecell/ | |
[2]: https://github.com/sagemath/sagecell/blob/master/web_server.py#L87 | |
--Dan Drake | |
""" | |
from base64 import urlsafe_b64decode as decode | |
from zlib import decompress | |
from urlparse import urlparse | |
from urllib import unquote | |
def get_sage_code(url): | |
return decompress( | |
decode( | |
unquote( | |
urlparse(url).query.split('=')[1]))) | |
from base64 import urlsafe_b64encode as encode | |
from zlib import compress | |
from urllib import urlencode | |
def get_urls(s_, server='aleph.sagemath.org'): | |
""" | |
If your input is not pure ASCII, you will need to give this function | |
a real Unicode string, or else encoding will give you a | |
UnicodeDecodeError (yes, really: [1]). Just using u"..." in the | |
Python/Sage interpreter does not always seem to work; my | |
recommendation is to put your code into a file (so your editor does | |
the work of proper encoding) and then use the codecs module. | |
>>> get_urls(codecs.open('filename', 'r', 'utf8').read()) | |
Presumably this all goes away in Python 3, where all strings are | |
Unicode. | |
[1]: http://wiki.python.org/moin/UnicodeDecodeError | |
""" | |
s = s_.encode('utf8') | |
code = encode( | |
compress(s)) | |
ret = ['http://{0}/?{1}'.format(server, urlencode({'z': code}))] | |
quoted = urlencode({'c': s}) | |
if len(quoted) < 100: | |
ret.append('http://{0}/?{1}'.format(server, quoted)) | |
return ret | |
if __name__ == '__main__': | |
import sys | |
print get_sage_code(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment