当前位置: 首页>>代码示例>>Python>>正文


Python HTTPClient.close方法代码示例

本文整理汇总了Python中tornado.httpclient.HTTPClient.close方法的典型用法代码示例。如果您正苦于以下问题:Python HTTPClient.close方法的具体用法?Python HTTPClient.close怎么用?Python HTTPClient.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tornado.httpclient.HTTPClient的用法示例。


在下文中一共展示了HTTPClient.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: gen_msg_token

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def gen_msg_token(phone):
	s = DBSession()
	code = "".join(random.sample("123456789",4))
	flag = False

	url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit&account={account}&password={password}&mobile={phone}&content={content}".format(account=account,password=password,phone=phone,content=url_escape(content.format(code=code)))
	h = HTTPClient()
	try:
		res = h.fetch(url,connect_timeout = 5.0)
	except:
		flag,msg =  sendTemplateSMS(phone,{code},32417)
		if flag:
			update_code(phone,code)
			return True
		else:
			return msg
	h.close()
	root = ElementTree.fromstring(res.body.decode())
	if not root[0].text == '2':
		# print("[VerifyMsg]Send error:",root[0].text,root[1].text)
		#如果发送失败,则改用云通讯发送
		flag,msg =  sendTemplateSMS(phone,{code},32417)
		if flag:
			update_code(phone,code)
			return True
		else:
			return msg
	else:
		update_code(phone,code)
		return True
开发者ID:krizex,项目名称:senguoSmh,代码行数:32,代码来源:msgverify.py

示例2: SyncHTTPClientTest

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
class SyncHTTPClientTest(unittest.TestCase):
    def setUp(self):
        self.server_ioloop = IOLoop()
        event = threading.Event()

        @gen.coroutine
        def init_server():
            sock, self.port = bind_unused_port()
            app = Application([("/", HelloWorldHandler)])
            self.server = HTTPServer(app)
            self.server.add_socket(sock)
            event.set()

        def start():
            self.server_ioloop.run_sync(init_server)
            self.server_ioloop.start()

        self.server_thread = threading.Thread(target=start)
        self.server_thread.start()
        event.wait()

        self.http_client = HTTPClient()

    def tearDown(self):
        def stop_server():
            self.server.stop()
            # Delay the shutdown of the IOLoop by several iterations because
            # the server may still have some cleanup work left when
            # the client finishes with the response (this is noticeable
            # with http/2, which leaves a Future with an unexamined
            # StreamClosedError on the loop).

            @gen.coroutine
            def slow_stop():
                # The number of iterations is difficult to predict. Typically,
                # one is sufficient, although sometimes it needs more.
                for i in range(5):
                    yield
                self.server_ioloop.stop()

            self.server_ioloop.add_callback(slow_stop)

        self.server_ioloop.add_callback(stop_server)
        self.server_thread.join()
        self.http_client.close()
        self.server_ioloop.close(all_fds=True)

    def get_url(self, path):
        return "http://127.0.0.1:%d%s" % (self.port, path)

    def test_sync_client(self):
        response = self.http_client.fetch(self.get_url("/"))
        self.assertEqual(b"Hello world!", response.body)

    def test_sync_client_error(self):
        # Synchronous HTTPClient raises errors directly; no need for
        # response.rethrow()
        with self.assertRaises(HTTPError) as assertion:
            self.http_client.fetch(self.get_url("/notfound"))
        self.assertEqual(assertion.exception.code, 404)
开发者ID:rgbkrk,项目名称:tornado,代码行数:62,代码来源:httpclient_test.py

示例3: get

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
 def get(self):
     name = self.get_argument('name','')
     if(name == "atlas"):
         with open("/var/www/atlas/access.token", 'r') as f:
             token = f.read()
             f.close()
             token = token.rstrip('\n')
             # TODO: Make this asynchronous and move access.token to aswwu/databases git repo
             http_client = HTTPClient()
             try:
                 response = http_client.fetch("https://api.instagram.com/v1/users/self/media/recent/?access_token=" + token)
                 self.write(response.body)
             except Exception as e:
                 self.write("{error: '" + str(e) + "'}")
             http_client.close()
     elif(name == "issuu"):
         http_client = HTTPClient()
         try:
             response = http_client.fetch("http://search.issuu.com/api/2_0/document?username=aswwucollegian&pageSize=1&responseParams=title,description&sortBy=epoch")
             self.write(response.body)
         except Exception as e:
             self.write("{error: '" + str(e) + "'}")
         http_client.close()
     else:
         self.write("Something went wrong.")
开发者ID:ASWWU-Web,项目名称:python_server,代码行数:27,代码来源:route_handlers.py

示例4: sina_ip

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def sina_ip(ip):
    attribution = ""
    if ip == "127.0.0.1":
        ip = '183.208.22.171'
    http_client = HTTPClient()
    response = None
    url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip={0}".format(ip)
    try:
        response = http_client.fetch(url, method='GET', request_timeout=120)
    except Exception as e:
        request_log.info(e)
    finally:
        http_client.close()

    if response and response.code == 200:
        response_body = eval(response.body.decode('utf8')[21:-1])
        try:
            province = response_body['province']
            city = response_body['city']
            attribution = city  #+province
        except Exception as e:
            error_log.error(e)

    ip_piece = ip.split(".")
    ip_piece[1] = '*'
    ip_piece[2] = '*'
    ip_attribution = '网友' + '.'.join(ip_piece) + '[' + attribution + ']'

    request_log.info(ip_attribution)
    return ip_attribution
开发者ID:mazhenpy,项目名称:pylabsite,代码行数:32,代码来源:views.py

示例5: get_steam_user

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def get_steam_user(db, steamid):
    user = None
    key = yield Op(db['server'].find_one, {'key': 'apikey'})
    url = url_concat('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/',
                     {'key': key['value'], 'steamids': steamid})
    client = HTTPClient()
    try:
        response = client.fetch(url)
        get_user = json_decode(response.body)['response']['players'][0]
        user = {'steamid': get_user['steamid'],
                'steamid32': converter(steamid),
                'personaname': get_user['personaname'],
                'profileurl': get_user['profileurl'],
                'avatar': get_user['avatarfull'],
                'registration': datetime.now(),
                'bookmarks': [],
                'favorites': [],
                'update': datetime.now() + timedelta(minutes=1),
                'dota_count': 0}
        if 'realname' in get_user.keys():
            user['realname'] = get_user['realname']
        else:
            user['realname'] = None
    except HTTPError as e:
        logging.error('Error: %s' % e)
    client.close()
    return user
开发者ID:Lardjo,项目名称:stml1,代码行数:29,代码来源:getuser.py

示例6: post_context_feedback

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
    def post_context_feedback(self, context_id: str, user_id: str, application_id: str, session_id: str,
                              product_id: str, _type: str, meta_data: dict = None):
        self.logger.debug(
            "context_id=%s,user_id=%s,application_id=%s,session_id=%s,product_id=%s,"
            "_type=%s,meta_data=%s",
            context_id, user_id, application_id, session_id, product_id, _type, meta_data
        )
        try:
            url = "%s/%s/feedback/?application_id=%s&session_id=%s&product_id=%s&type=%s" % (
                CONTEXT_URL, context_id, application_id, session_id, product_id, _type
            )
            url += "&user_id=%s" if user_id is not None else ""

            request_body = {
            }
            if meta_data is not None:
                request_body["meta_data"] = meta_data

            http_client = HTTPClient()
            response = http_client.fetch(HTTPRequest(url=url, body=dumps(request_body), method="POST"))
            http_client.close()
            return response.headers["_rev"]
        except HTTPError:
            self.logger.error("post_context_feedback,url=%s", url)
            raise
开发者ID:rdefeo,项目名称:api,代码行数:27,代码来源:websocket.py

示例7: get_html

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def get_html(url):
    http_client = HTTPClient()
    try:
        response = http_client.fetch(url,follow_redirects=True)
        return response.body
    except Exception as e:
        return None
    http_client.close()
开发者ID:yanyang-xie,项目名称:Learning-Python,代码行数:10,代码来源:tasks.py

示例8: binary_search

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def binary_search(http_helper, lsig, minv, maxv, url, method, detection_struct,
                  ch,
                  headers, body=None):
    mid = mid_value(minv, maxv)
    new_url = url
    new_body = body
    new_headers = headers

    if minv > maxv:
        return maxv

    http_client = HTTPClient()
    payload = ch * mid

    if lsig in url:
        new_url = url.replace(lsig, payload)  # warning urlencode and etc
    elif body is not None and lsig in body:
        new_body = body.replace(lsig, payload)
    elif headers is not None and lsig in headers:
        raw_val = str(headers)
        raw_val = raw_val.replace(lsig, payload)
        new_headers = ast.literal_eval(str(raw_val))
    request = http_helper.create_http_request(method,
                                              new_url,
                                              new_body,
                                              new_headers)
    try:
        response = http_client.fetch(request)
    except HTTPError as e:
        response = e.response

    for struct in detection_struct:
        if struct["method"](response, struct["arguments"]):
            http_client.close()
            return binary_search(http_helper,
                                 lsig,
                                 minv,
                                 mid - 1,
                                 url,
                                 method,
                                 detection_struct,
                                 ch,
                                 headers,
                                 body)
    http_client.close()
    return binary_search(http_helper,
                         lsig,
                         mid + 1,
                         maxv,
                         url,
                         method,
                         detection_struct,
                         ch,
                         headers,
                         body)
开发者ID:0day29,项目名称:owtf,代码行数:57,代码来源:placeholder_length.py

示例9: http_fetch

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def http_fetch(url):
    """ Perform an HTTP request.
    """
    from tornado.httpclient import HTTPClient
    http_client = HTTPClient()
    try:
        response = http_client.fetch(url)
    except Exception as err:
        raise FetchError('http fetch failed: %s' % str(err))
    finally:
        http_client.close()
    return response.body.decode()
开发者ID:Python-PyBD,项目名称:flexx,代码行数:14,代码来源:__main__.py

示例10: __call__

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
 def __call__(self, message):
     http_client = HTTPClient()
     response = ('', None)
     try:
         response = http_client.fetch(self.url, body=message, method='POST',
                                      connect_timeout=self.connection_timeout,
                                      request_timeout=self.connection_timeout)
     except HTTPError as e:
         error("HTTP Error: %s, payload size (bytes): %s", e, len(message))
         handle_exception(ErrorMessage.from_exception(e, address=self.url))
     finally:
         http_client.close()
     return response
开发者ID:cosminbasca,项目名称:asyncrpc,代码行数:15,代码来源:tornadorpc.py

示例11: get_html

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def get_html(url):
    http_client = HTTPClient()

    try:
        response = http_client.fetch(url, follow_redirects=True)
        print("body: {}".format(response.body))
        data = response.body
        result = str(data).encode(encoding="utf-8")
        return result
    except httpclient.HTTPError as e:
        return None
    finally:
        http_client.close()
开发者ID:VShangxiao,项目名称:iPyScript,代码行数:15,代码来源:tasks.py

示例12: get

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
 def get(self):
     normalized_path = self.normalize_path(self.context.request.url)
     uri = self.context.config.get('RESULT_STORAGE_WEBDAV_URI') + normalized_path
     logger.debug("[RESULT_STORAGE] Making GET request to: %s", uri)
     http_client = HTTPClient()
     result = None
     try:
         response = http_client.fetch(uri)
         result = response.body
     except HTTPError as e:
         logger.debug("[RESULT_STORAGE] Error on GET request: %s", e)
     http_client.close()
     return result
开发者ID:clifff,项目名称:thumbor_webdav_result_storage,代码行数:15,代码来源:__init__.py

示例13: SyncHTTPClientTest

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
class SyncHTTPClientTest(unittest.TestCase):
    def setUp(self):
        if IOLoop.configured_class().__name__ in ('TwistedIOLoop',
                                                  'AsyncIOMainLoop'):
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            # AsyncIOMainLoop doesn't work with the default policy
            # (although it could with some tweaks to this test and a
            # policy that created loops for non-main threads).
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop or '
                'AsyncIOMainLoop')
        self.server_ioloop = IOLoop()

        sock, self.port = bind_unused_port()
        app = Application([('/', HelloWorldHandler)])
        self.server = HTTPServer(app, io_loop=self.server_ioloop)
        self.server.add_socket(sock)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient()

    def tearDown(self):
        def stop_server():
            self.server.stop()
            # Delay the shutdown of the IOLoop by one iteration because
            # the server may still have some cleanup work left when
            # the client finishes with the response (this is noticable
            # with http/2, which leaves a Future with an unexamined
            # StreamClosedError on the loop).
            self.server_ioloop.add_callback(self.server_ioloop.stop)
        self.server_ioloop.add_callback(stop_server)
        self.server_thread.join()
        self.http_client.close()
        self.server_ioloop.close(all_fds=True)

    def get_url(self, path):
        return 'http://127.0.0.1:%d%s' % (self.port, path)

    def test_sync_client(self):
        response = self.http_client.fetch(self.get_url('/'))
        self.assertEqual(b'Hello world!', response.body)

    def test_sync_client_error(self):
        # Synchronous HTTPClient raises errors directly; no need for
        # response.rethrow()
        with self.assertRaises(HTTPError) as assertion:
            self.http_client.fetch(self.get_url('/notfound'))
        self.assertEqual(assertion.exception.code, 404)
开发者ID:437049211,项目名称:PyQYT,代码行数:53,代码来源:httpclient_test.py

示例14: find_length

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
def find_length(owtf, http_helper, lsig, url, method, detection_struct, ch, headers,
                body=None):
    """This function finds the length of the fuzzing placeholder"""
    size = 8192
    minv = 0
    http_client = HTTPClient()
    new_url = url
    new_body = body
    new_headers = headers
    payload = ""
    for loop in range(0, 15):  # used to avoid potential deadloops
        payload = size * ch
        if lsig in url:
            new_url = url.replace(lsig, payload)
        elif body is not None and lsig in body:
            new_body = body.replace(lsig, payload)
        elif headers is not None and lsig in str(headers):
            raw_val = str(headers)
            raw_val = raw_val.replace(lsig, payload)
            new_headers = ast.literal_eval(str(raw_val))
        else:
            Error(owtf, "Length signature not found!")


        request = http_helper.create_http_request(method,
                                                  new_url,
                                                  new_body,
                                                  new_headers)
        try:
            response = http_client.fetch(request)
        except HTTPError as e:
            if e.response:
                response = e.response

        for struct in detection_struct:
            if struct["method"](response, struct["arguments"]):
                http_client.close()
                return binary_search(
                    http_helper,
                    lsig,
                    minv,
                    size,
                    url,
                    method,
                    detection_struct,
                    ch,
                    headers,
                    body)
        minv = size
        size *= 2
开发者ID:0day29,项目名称:owtf,代码行数:52,代码来源:placeholder_length.py

示例15: register_volume

# 需要导入模块: from tornado.httpclient import HTTPClient [as 别名]
# 或者: from tornado.httpclient.HTTPClient import close [as 别名]
    def register_volume(self, volume):

        # globally register volume
        global volumes
        volumes[volume.token] = volume

        # globally register kernel client for this volume in the Jupyter server
        cf = url_escape(find_connection_file())
        http_client= HTTPClient()
        try:
            response = http_client.fetch(self.get_server_url() + '/register_token/' + volume.token.decode('utf8') + '/' + cf)
        except Exception as e:
            raise RuntimeError("could not register token: " + str(e))
        http_client.close()
开发者ID:funkey,项目名称:nyroglancer,代码行数:16,代码来源:viewer.py


注:本文中的tornado.httpclient.HTTPClient.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。