Skip to content

Instantly share code, notes, and snippets.

@amyangfei
Last active May 24, 2019 09:54
Show Gist options
  • Save amyangfei/a64407f332402b2cff88 to your computer and use it in GitHub Desktop.
Save amyangfei/a64407f332402b2cff88 to your computer and use it in GitHub Desktop.
get short url via sina api (http://open.weibo.com/wiki/Short_url/shorten)
#!/usr/bin/env python
# coding: utf-8
import json
import sys
import re
from tornado.httputil import url_concat
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop
simple_url_reg = re.compile(r'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$')
def stop_ioloop():
IOLoop.instance().stop()
def handle_request(response):
if response.error:
print 'error:', response.error
else:
try:
json_str = json.loads(response.body)
for one in json_str:
print one
except Exception, e:
print e
stop_ioloop()
def async_get(site_lst):
params = {'source': '5786724301'}
url = 'http://api.t.sina.com.cn/short_url/shorten.json'
url = url_concat(url, params)
for site in site_lst:
if not simple_url_reg.match(site):
print 'invalid url:', site
continue
if not site.startswith('http'):
site = 'http://' + site
url = url_concat(url, {'url_long': site})
if 'url_long' not in url:
print 'No valid url.\nUsage example: python {} www.google.com ' \
'docker.io http://github.com'.format(sys.argv[0])
sys.exit(1)
http_client = AsyncHTTPClient()
http_client.fetch(url, handle_request)
if __name__ == '__main__':
ioloop = IOLoop.instance()
async_get(sys.argv[1:])
ioloop.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment