tornado 异步检测网址目标是否存在

通过tornado 异步检测目标网址文件是否存在。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web


from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPRequest


from tornado.options import define, options

define("port", default=10076, help="run on the given port", type=int)


class MainHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        _url = 'http://www.test.com/logo.jpg'

        http_client = AsyncHTTPClient()
        req = HTTPRequest(url=_url, method='HEAD')
        http_client.fetch(req, callback=(yield gen.Callback("check_url_by_head")))
        _response = yield gen.Wait("check_url_by_head")
        logging.error(_response)
        if _response.code == 200:
            print 'file exist'
        else:
            print _response.code


def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()


Relative Articles