[파이썬] Tornado에서의 비동기 HTTP 클라이언트

파이썬의 Tornado 프레임워크는 비동기 웹 애플리케이션의 개발을 위한 강력한 도구입니다. 비동기 HTTP 클라이언트를 사용하면 다른 서버로의 비동기 HTTP 요청을 간편하게 보낼 수 있습니다. 이를 통해 웹 애플리케이션의 성능을 향상시킬 수 있습니다.

비동기 HTTP 클라이언트 사용하기

Tornado에서 비동기 HTTP 클라이언트를 사용하기 위해서는 tornado.httpclient.AsyncHTTPClient 클래스를 import해야 합니다. 다음은 간단한 예제 코드입니다.

import tornado.httpclient

async def fetch(url):
    http_client = tornado.httpclient.AsyncHTTPClient()
    response = await http_client.fetch(url)
    return response.body

async def main():
    url = "https://example.com"
    response = await fetch(url)
    print(response)

if __name__ == "__main__":
    tornado.ioloop.IOLoop.current().run_sync(main)

위의 코드에서 fetch 함수는 지정한 URL로 비동기 HTTP 요청을 보내고 응답을 반환합니다. main 함수에서는 fetch 함수를 호출하고 응답을 출력합니다.

AsyncHTTPClient 클래스의 fetch 메서드는 await 키워드를 통해 비동기로 호출됩니다. 따라서 다른 작업을 기다리는 동안 이벤트 루프를 차단하지 않고 계속 실행됩니다.

요청 매개변수 지정하기

HTTP 요청을 보낼 때, 추가적인 매개변수를 지정하여 요청을 커스터마이징할 수 있습니다. 다음은 몇 가지 예시입니다.

HTTP 메서드 변경

HTTP 요청을 보낼 때 사용할 메서드를 변경할 수 있습니다. 다음 예제는 POST 메서드를 사용하는 코드입니다.

import tornado.httpclient

async def fetch(url):
    http_client = tornado.httpclient.AsyncHTTPClient()
    response = await http_client.fetch(url, method="POST")
    return response.body

요청 헤더 추가

HTTP 요청 헤더에 추가적인 정보를 담고 싶을 때, headers 매개변수를 사용할 수 있습니다. 다음 예제는 User-Agent 헤더를 추가하는 코드입니다.

import tornado.httpclient

async def fetch(url):
    http_client = tornado.httpclient.AsyncHTTPClient()
    headers = {"User-Agent": "MyCustomUserAgent"}
    response = await http_client.fetch(url, headers=headers)
    return response.body

요청 바디 추가

일부 HTTP 메서드 (예: POST 또는 PUT)는 요청 바디에 데이터를 추가해야할 때가 있습니다. body 매개변수를 사용하여 요청 바디를 추가할 수 있습니다. 다음은 요청 바디를 추가하는 예제입니다.

import tornado.httpclient

async def fetch(url):
    http_client = tornado.httpclient.AsyncHTTPClient()
    body = "Hello, World!"
    response = await http_client.fetch(url, method="POST", body=body)
    return response.body

요청에 대한 응답 처리하기

비동기 HTTP 요청을 보내고 응답을 받은 후에는 해당 응답을 처리해야합니다. 일반적으로 응답은 문자열 또는 JSON 형태로 받을 수 있습니다.

다음은 응답을 문자열로 받는 예제입니다.

import tornado.httpclient

async def fetch(url):
    http_client = tornado.httpclient.AsyncHTTPClient()
    response = await http_client.fetch(url)
    return response.body.decode("utf-8")

async def main():
    url = "https://example.com"
    response_text = await fetch(url)
    print(response_text)

if __name__ == "__main__":
    tornado.ioloop.IOLoop.current().run_sync(main)

만약 응답이 JSON 형식이라면, json_decode 메서드를 사용하여 응답을 파싱할 수 있습니다.

import tornado.httpclient

async def fetch(url):
    http_client = tornado.httpclient.AsyncHTTPClient()
    response = await http_client.fetch(url)
    return tornado.escape.json_decode(response.body)

async def main():
    url = "https://api.example.com/data"
    response_json = await fetch(url)
    print(response_json)

if __name__ == "__main__":
    tornado.ioloop.IOLoop.current().run_sync(main)

결론

Tornado의 비동기 HTTP 클라이언트를 사용하면 웹 애플리케이션에서 다른 서버로 비동기 요청을 보낼 수 있습니다. 이로써 애플리케이션의 효율성과 성능을 개선할 수 있습니다. 위의 예제 코드를 기반으로 사용법을 익혀보고, 자신의 프로젝트에 적용해보시기 바랍니다.