Last active
November 25, 2017 02:28
-
-
Save borgle/ffbe14ec7d25055dac61 to your computer and use it in GitHub Desktop.
提供一个web服务,返回处理过的远程图片。
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
#!/usr/bin/env python | |
# coding:utf-8 | |
__version__ = '1.0.0' | |
try: | |
import gevent | |
import gevent.queue | |
import gevent.monkey | |
gevent.monkey.patch_all() | |
except ImportError: | |
pass | |
import sys | |
import time | |
import logging | |
import cStringIO | |
import imghdr | |
import requests | |
from PIL import Image | |
def application(environ, start_response): | |
try: | |
url = "http://www.abcd.com/captcha2.jsp?0.{}".format(time.ctime()) | |
r = requests.get(url) | |
data = r.content | |
r.close() | |
imgtype = imghdr.what('', h=data) | |
img = Image.open(cStringIO.StringIO(data)) | |
img = img.crop([0, 0, 218, 21]) | |
# do more by yourself | |
cimg = cStringIO.StringIO() | |
img.save(cimg, imgtype) | |
cimg.seek(0) | |
data = cimg.getvalue() | |
start_response('200 OK', [('Content-Type', "image/" + imgtype), | |
('content-length', str(len(data)))]) | |
return [data] | |
except Exception as e: | |
raise StopIteration | |
def run_wsgi_app(address, app): | |
try: | |
from gunicorn.app.wsgiapp import WSGIApplication | |
class GunicornApplication(WSGIApplication): | |
def init(self, parser, opts, args): | |
return {'bind': '%s:%d' % (address[0], int(address[1])), | |
'workers': 2, | |
'worker_class': 'gevent'} | |
def load(self): | |
return app | |
GunicornApplication().run() | |
except ImportError: | |
from gevent.wsgi import WSGIServer | |
WSGIServer(address, app).serve_forever() | |
if __name__ == '__main__': | |
logging.basicConfig(level=logging.INFO, format='%(levelname)s - - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]') | |
host, _, port = sys.argv[1].rpartition(':') | |
logging.info('local python application serving at %s:%s', host, port) | |
run_wsgi_app((host, int(port)), application) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment