Created
March 29, 2018 16:01
-
-
Save jsbain/0614ea2baf2b71cae899cd19b87d7c64 to your computer and use it in GitHub Desktop.
savefile.py
This file contains hidden or 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
| #coding: utf-8 | |
| import requests | |
| import appex,console,time,os | |
| unquote=requests.utils.unquote | |
| urlparse=requests.utils.urlparse | |
| url=appex.get_url() | |
| p=urlparse(url) | |
| urlfilename=unquote(unquote(urlparse(appex.get_url()).path.split('/')[-1])) | |
| console.hud_alert('downloading '+urlfilename) | |
| console.show_activity() | |
| if p.netloc.startswith('gist.github.com'): | |
| gist_id=urlfilename | |
| session=requests.Session() | |
| data=session.get('https://api.github.com/gists/{}'.format(gist_id)).json() | |
| if data: | |
| gistpath=os.path.expanduser('~/Documents/gists/') | |
| destpath=os.path.join(gistpath,gist_id) | |
| for pth in [gistpath, destpath]: | |
| if not os.path.exists(pth): | |
| os.mkdir(pth) | |
| for f in data['files'].values(): | |
| filename=f['filename'] | |
| console.hud_alert('writing '+filename) | |
| url=f['raw_url'] | |
| #rather than deal with possibly truncated files, or unicode, just download raw url as binary | |
| with open(os.path.join(destpath,filename),'wb') as file: | |
| with session.get(url,stream=True) as r: | |
| sz=int(r.headers['content-length']) | |
| prog=0 | |
| for bdata in r.iter_content(chunk_size=2048): | |
| prog+=len(bdata) | |
| console.hud_alert('{}%'.format(prog/sz*100.)) | |
| file.write(bdata) | |
| else: | |
| console.hud_alert('could not download') | |
| else: | |
| destpath=urlfilename | |
| with open(destpath,'wb') as file: | |
| with requests.get(url,stream=True) as r: | |
| sz=r.headers['content-length'] | |
| prog=0 | |
| for data in r.iter_content(chunk_size=1024): | |
| prog+=len(data) | |
| console.hud_alert('{}%'+prog/sz*100.) | |
| file.write(data) | |
| console.hud_alert(urlfilename +' complete') | |
| console.hide_activity() | |
| appex.finish() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment