本文整理汇总了Python中tornado.httpclient.AsyncHTTPClient.close方法的典型用法代码示例。如果您正苦于以下问题:Python AsyncHTTPClient.close方法的具体用法?Python AsyncHTTPClient.close怎么用?Python AsyncHTTPClient.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.httpclient.AsyncHTTPClient
的用法示例。
在下文中一共展示了AsyncHTTPClient.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def post(self, *args, **kwargs):
# TODO
# save the messages to local database
# file = self.request.files['image'][0]
# file_name = file["filename"]
# image = file['body']
text = self.get_argument("text")
data = {
"from": "Mailgun Sandbox <[email protected]>",
"to": "<[email protected]>",
"subject": "Hello Udaan",
"text": text,
}
data = urlencode(data)
client = AsyncHTTPClient()
headers_object = HTTPHeaders({"X-Mailgun-Variables": dumps({"X-Mailgun-Variables": {"password": "working"}})})
request_object = HTTPRequest("https://api.mailgun.net/v3/sandbox1713f24a60034b5ab5e7fa0ca2faa9b6.mailgun.org"
"/messages",
method="POST",
headers=headers_object,
body=data,
auth_username="api",
auth_password="key-a0bd92feef0ccecb07f199b770449917"
)
print(request_object.headers.get_list("X-Mailgun-Variables"))
response = yield client.fetch(request_object)
client.close()
print(response)
if response.code == 200:
msg = "email send successfully"
self.respond(msg, response.code)
else:
msg = "Please try again"
self.respond(msg, response.code)
示例2: _check_heapster_status
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def _check_heapster_status(settings):
if "HEAPSTER_SERVICE_HOST" in settings:
heapster_endpoint = settings["HEAPSTER_SERVICE_HOST"]
heapster_port = settings["HEAPSTER_SERVICE_PORT"]
endpoint = "http://%s:%s/api/v1/model" % (heapster_endpoint, heapster_port)
headers = dict()
else:
kubernetes_endpoint = settings["KUBERNETES_SERVICE_HOST"]
if not kubernetes_endpoint.startswith("http"):
kubernetes_endpoint = "https://%s:%s" % (kubernetes_endpoint, settings["KUBERNETES_SERVICE_PORT"])
endpoint = "%s%s" % (
kubernetes_endpoint,
"/api/v1/proxy/namespaces/kube-system/services/heapster/api/v1/model"
)
headers = dict(Authorization="Bearer %s" % settings['token'])
client = AsyncHTTPClient(force_instance=True)
try:
result = yield client.fetch(
endpoint + "/metrics",
method="GET",
validate_cert=False,
headers=headers,
raise_error=False)
if not result.error:
raise Return(status_ok())
else:
raise Return(status_error(result.error))
finally:
client.close()
示例3: post_context_message
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def post_context_message(
self, context_id: str, direction: int, message_text: str, callback, detection: dict = None, now=None):
"""
Direction is 1 user 0 jemboo
:type direction: int
"""
self.logger.debug(
"context_id=%s,direction=%s,message_text=%s,detection=%s",
context_id, direction, message_text, detection
)
now = datetime.now() if now is None else now
try:
request_body = {
"direction": direction,
"text": message_text,
"created": now.isoformat()
}
if detection is not None:
request_body["detection"] = detection
url = "%s/%s/messages/" % (CONTEXT_URL, context_id)
http_client = AsyncHTTPClient()
http_client.fetch(
HTTPRequest(url=url, method="POST", body=json_encode(request_body)),
callback=callback
)
http_client.close()
except HTTPError as e:
self.logger.error("post_context_message,url=%s", url)
raise
示例4: request
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def request(self, url, method="GET", **kwargs):
client = AsyncHTTPClient(force_instance=True)
try:
result = yield client.fetch(url, method=method, headers=self.build_headers(), **kwargs)
raise Return(result)
finally:
client.close()
示例5: post_suggest
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def post_suggest(self, user_id: str, application_id: str, session_id: str, locale: str, context: dict,
callback) -> str:
self.logger.debug(
"user_id=%s,application_id=%s,session_id=%s,locale=%s,"
"context=%s",
user_id, application_id, session_id, locale, context
)
url = "%s?session_id=%s&application_id=%s&locale=%s" % (
SUGGEST_URL, session_id, application_id, locale
)
url += "&user_id=%s" % user_id if user_id is not None else ""
try:
request_body = {
"context": context
}
http_client = AsyncHTTPClient()
http_client.fetch(HTTPRequest(url=url, body=dumps(request_body), method="POST"), callback=callback)
http_client.close()
except HTTPError:
self.logger.error("url=%s", url)
raise
示例6: Worker
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
class Worker(object):
# Seconds before retrying a request to server in seconds
POLL_INTERVAL = 1
# Seconds to wait when there are no new jobs
NO_JOB_WAIT= 60
def __init__(self, api_url, mongo_uri, **kwargs):
self.url = api_url
self.name = socket.gethostname()
self.http_client = AsyncHTTPClient()
self.models = {"keras": KerasModel(**kwargs)}
self.data_path = os.path.join(os.path.dirname(__file__), "data")
self.data_loader = DataLoader(api_url, mongo_uri)
def json_decode(self, body):
json_body = json.loads(body.decode("utf-8"))
# This needs to be called two times on escaped json string. ¯\_(ツ)_/¯
if not isinstance(json_body, dict):
return json.loads(json_body)
return json_body
@gen.coroutine
def get_new_job(self):
try:
response = yield self.http_client.fetch(self.url + "/worker/" + self.name + "/job")
job = self.json_decode(response.body)
# no jobs, wait 1 min before next request.
if "wait" in job:
print "Experiment %s is done! There are no new jobs yet." % job["experiment_id"]
IOLoop.current().call_later(self.NO_JOB_WAIT, lambda: self.get_new_job())
return
# if job type is unsupported (only keras supported at the moment)
if job["model_type"] not in self.models:
raise ValueError("Only the following models are supported right now: " + ", ".join(self.models.keys()))
# TODO: clean it up! terrible, I know..
model = self.models[job["model_type"]]
model.exp_id = job["experiment_id"]
job["model_params"]["data_filename"] = job["data_filename"]
result = model.run_job(job["model_params"])
# Get a new job from server
IOLoop.current().call_later(1, lambda: self.get_new_job())
except HTTPError as e:
print("Error: " + str(e))
IOLoop.current().call_later(self.POLL_INTERVAL, lambda: self.get_new_job())
except Exception as e:
# Other errors are possible, such as IOError.
print("Error: " + str(e))
IOLoop.current().call_later(self.POLL_INTERVAL, lambda: self.get_new_job())
def close(self):
self.http_client.close()
示例7: AsyncHTTPTestCase
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
class AsyncHTTPTestCase(AsyncTestCase):
'''A test case that starts up an HTTP server.
Subclasses must override get_app(), which returns the
tornado.web.Application (or other HTTPServer callback) to be tested.
Tests will typically use the provided self.http_client to fetch
URLs from this server.
Example:
class MyHTTPTest(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', MyHandler)...])
def test_homepage(self):
self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()
# test contents of response
'''
def setUp(self):
super(AsyncHTTPTestCase, self).setUp()
self.__port = None
self.http_client = AsyncHTTPClient(io_loop=self.io_loop)
self._app = self.get_app()
self.http_server = HTTPServer(self._app, io_loop=self.io_loop,
**self.get_httpserver_options())
self.http_server.listen(self.get_http_port())
def get_app(self):
"""Should be overridden by subclasses to return a
tornado.web.Application or other HTTPServer callback.
"""
raise NotImplementedError()
def get_httpserver_options(self):
"""May be overridden by subclasses to return additional
keyword arguments for HTTPServer.
"""
return {}
def get_http_port(self):
"""Returns the port used by the HTTPServer.
A new port is chosen for each test.
"""
if self.__port is None:
self.__port = get_unused_port()
return self.__port
def get_url(self, path):
"""Returns an absolute url for the given path on the test server."""
return 'http://localhost:%s%s' % (self.get_http_port(), path)
def tearDown(self):
self.http_server.stop()
self.http_client.close()
super(AsyncHTTPTestCase, self).tearDown()
示例8: delete
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def delete(self, url_path, **kwargs):
client = AsyncHTTPClient(force_instance=True)
try:
response = yield client.fetch(
self.build_url(url_path, **kwargs),
method="DELETE",
headers=self.build_headers())
raise Return(response)
finally:
client.close()
示例9: get
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def get(self, url_path, **kwargs):
params = self.build_params(url_path, **kwargs)
url = url_concat(self.build_url(url_path, **kwargs), params)
client = AsyncHTTPClient(force_instance=True)
try:
result = yield client.fetch(url, method="GET", headers=self.build_headers())
raise Return(result)
finally:
client.close()
示例10: get_detect
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def get_detect(self, location: str, callback) -> dict:
self.logger.debug("location=%s", location)
url = "%s%s" % (DETECT_URL, location)
try:
http_client = AsyncHTTPClient()
http_client.fetch(HTTPRequest(url=url, method="GET"), callback=callback)
http_client.close()
except HTTPError as e:
self.logger.error("get_detect,url=%s", url)
raise
示例11: get_context_messages
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def get_context_messages(self, handler: WebSocketHandler, callback) -> dict:
try:
if handler.context is None or handler.context["_rev"] != handler.context_rev:
self.logger.debug(
"get_context_from_service,context_id=%s,_rev=%s", str(handler.context_id), handler.context_rev)
http_client = AsyncHTTPClient()
url = "%s/%s/messages" % (CONTEXT_URL, str(handler.context_id))
http_client.fetch(HTTPRequest(url=url, method="GET"), callback=callback)
http_client.close()
except HTTPError as e:
self.logger.error("get_context,url=%s", url)
raise
示例12: async_fetch
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def async_fetch(self, url, method=HTTP_METHOD_GET, params=None, callback=None):
"""
"""
if not callback:
raise HttpClientCallbackError, "callback is wrong"
# 先打包数据
request = self._pack_data(url, method, params)
# 发起请求
http_client = AsyncHTTPClient()
http_client.fetch(request, callback=callback)
http_client.close()
示例13: coroutine_fetch
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def coroutine_fetch(self, url, method=HTTP_METHOD_GET, params=None):
"""
"""
# 打包数据
request = self._pack_data(url, method, params)
http_client = AsyncHTTPClient()
response = yield http_client.fetch(request)
http_client.close()
if not response:
yield response
return
yield response.body
示例14: request
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def request(self, url_path, method="GET", **kwargs):
params = self.build_params(url_path, **kwargs)
if not urlparse.urlparse(url_path).netloc:
url = url_concat(self.build_url(url_path, **kwargs), params)
else:
url = url_concat(url_path, params)
client = AsyncHTTPClient(force_instance=True)
try:
result = yield client.fetch(url, method=method, headers=self.build_headers())
raise Return(result)
finally:
client.close()
示例15: patch
# 需要导入模块: from tornado.httpclient import AsyncHTTPClient [as 别名]
# 或者: from tornado.httpclient.AsyncHTTPClient import close [as 别名]
def patch(self, url_path, **kwargs):
url = self.build_url(url_path, **kwargs)
params = self.build_params(url_path, **kwargs)
client = AsyncHTTPClient(force_instance=True)
try:
result = yield client.fetch(
url,
method="PATCH",
headers=self.build_headers("application/merge-patch+json"),
**params)
raise Return(result)
finally:
client.close()