[Python] 비동기 요청 예제
ITWeb/개발일반 2021. 4. 19. 18:47비동기 처리 하는거 예제가 필요해서 급조 합니다.
참고문서)
docs.python.org/ko/3/library/asyncio.html
docs.python-requests.org/en/master/
$ pyenv virtualenv 3.8.6 helloworld
$ pyenv activate helloworld
(helloworld) $ pip install requests asyncio
(helloworld) $ python asyncio.py
(helloworld) $ vi asyncio.py
import requests
import string
import random
import asyncio
async def requestAsyncio(content, cid, aid):
url = "http://localhost:8080/helloworld"
payload={}
headers = {
'accept': 'application/json, text/plain, */*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,ja-JP;q=0.6,ja;q=0.5,zh-MO;q=0.4,zh;q=0.3',
'content-type': 'application/x-www-form-urlencoded',
'origin': 'http://localhost:8080',
'referer': 'http://localhost:8080/helloworld',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.status_code)
print(response.text)
if __name__ == "__main__":
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
cid = "helloworld"
aid = "python"
content1 = random.choice(letters)
content2 = random.choice(letters)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(requestKhan(content1, cid, aid), requestKhan(content2, cid, aid)))
loop.close()
(helloworld) $ python asyncio.py
(helloworld) $ pyenv deactivate helloworld
$