python(2.7.6),gevnet(1.1.2),requests(2.11.1)๋ฅผ ์ฌ์ฉํ์ฌ http ์์ฒญ์ ๋์์ ์ํํ๊ณ ์ ์๋ํฉ๋๋ค. ๊ทธ๋ฌ๋ ์์ฒญ์ ์๋ง ํ๋ก์๋ฅผ ์ถ๊ฐํ๋ฉด ์ฐจ๋จ๋ฉ๋๋ค.
์ด๊ฒ์ ๋ด ์ฝ๋์ ๋๋ค.
import time
import requests
import logging
import click
import gevent
from gevent import monkey
monkey.patch_all()
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('test')
#socks proxy
user = MY_SOCKS_PROXY_USERNAME
password = MY_SOCKS_PROXY_PASSWORD
host = MY_SOCKS_PROXY_HOST
port = MY_SOCKS_PROXY_PORT
proxies = {
'http': 'socks5://{0}:{1}@{2}:{3}'.format(user, password, host, port),
'https': 'socks5://{0}:{1}@{2}:{3}'.format(user, password, host, port),
}
url = 'https://www.youtube.com/user/NBA'
def fetch_url(i,with_proxy):
while True:
logger.warning('thread %s fetch url'%i)
try:
if with_proxy:
res = requests.get(url,proxies=proxies, timeout=5)
else:
res = requests.get(url, timeout=5)
except Exception as e:
logger.error(str(e))
continue
logger.warning(res.status_code)
def do_other_thing():
while True:
logger.warning('do other thing...')
time.sleep(1)
@click.command()
@click.option('--with_proxy/--without_proxy',help='if use proxy', default=True)
def run(with_proxy):
if with_proxy:
logger.warning('with proxy......')
else:
logger.warning('without proxy......')
ts = []
ts.append(gevent.spawn(do_other_thing))
for i in xrange(3):
ts.append(gevent.spawn(fetch_url,i,with_proxy))
gevent.joinall(ts)
if __name__=='__main__':
run()
์ด ์ฌ์ง์ ๊ฒฐ๊ณผ๋ฅผ ๋ณด์ฌ์ค๋๋ค.
ํ๋ก์๋ก ์คํ
ํ๋ก์ ์์ด ์คํ
ํ๋ก์๋ฅผ ์ฌ์ฉํ๋ฉด fetch_url์ด ์๋ฃ๋๊ธฐ ์ ์ do_other_thing์ด ์ฐจ๋จ๋ฉ๋๋ค.
ํ๋ก์๊ฐ ์์ผ๋ฉด ์ ์๋ํฉ๋๋ค. (GFW๋ก ์ธํด ํ์์์ ์๋ฌ ๋ฐ์)
๋๊ตฌ๋ ์ง์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ฐ ๋์์ ์ค ์ ์์ต๋๊น? ๋งค์ฐ ๊ฐ์ฌํฉ๋๋ค!
๊ฐ์ฅ ์ข์ ์ถ์ธก์ ๋น์ ์ด ๋๋ฌด ๋ฆ๊ฒ ์์ญ์ด ํจ์น๋ฅผ ํ๋ค๋ ๊ฒ์
๋๋ค. gevent๋ฅผ ์ฌ์ฉํ ๋ ๋ค๋ฅธ ๊ฒ์ ๊ฐ์ ธ์ค๊ธฐ ์ ์ ๋จผ์ monkeypatchํด์ผ ํฉ๋๋ค. ๋์ค์ ์ํํ๋ฉด gevent monkeypatches์์ from
๊ฐ์ ธ์ค๊ธฐ๋ฅผ ์ํํ ๋ชจ๋ ํญ๋ชฉ์ด ์์๋ ์ํ์ด ์์ต๋๋ค.
๋ค๋ฅธ ์์ ์ ์ํํ๊ธฐ ์ ์ ๊ฐ์ ธ์ค๊ธฐ ๋ฐ monkeypatch๋ฅผ ํ์ผ์ ๋งจ ์๋ก ์ด๋ํด ๋ณผ ์ ์์ต๋๊น?
์, ' ๊ฐ์ ธ์ค๊ธฐ ๋ฐ monkeypatch๋ฅผ ํ์ผ ๋งจ ์๋ก ์ด๋'ํ๋ฉด ๋ด ๋ฌธ์ ๊ฐ ํด๊ฒฐ๋์์ต๋๋ค! ๋งค์ฐ ๊ฐ์ฌํฉ๋๋ค!
์ด ์ ์์ ๋ํ ๋ด ํ๋ก์ ํธ์ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํฉ๋๋ค.
A,B,C๋ผ๋ 3๊ฐ์ ํ์ผ์ด ์๊ณ ์คํ ์์๋ A->B->C์
๋๋ค. ๋๋ B์์ gevent๋ฅผ ์ฌ์ฉํ๋ฏ๋ก B์์ monkeypatch๋ฅผ ์ถ๊ฐํ์ง๋ง ์์ฒญ+์๋ง๋ก ์ฐจ๋จํฉ๋๋ค. ์ด์ A ๋งจ ์์ monkeypatch๋ฅผ ์ถ๊ฐํฉ๋๋ค. ์ด์ ์ ์๋ํฉ๋๋ค! ์ด๊ฒ์ด ๋ค๋ฅธ ์ฌ๋๋ค์๊ฒ ๋์์ด ๋๊ธฐ๋ฅผ ๋ฐ๋๋๋ค!
๋ค์ ๊ฐ์ฌํฉ๋๋ค!
๋์ ์ค ์์์ด์ ๊ธฐ๋ป!
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
๊ฐ์ฅ ์ข์ ์ถ์ธก์ ๋น์ ์ด ๋๋ฌด ๋ฆ๊ฒ ์์ญ์ด ํจ์น๋ฅผ ํ๋ค๋ ๊ฒ์ ๋๋ค. gevent๋ฅผ ์ฌ์ฉํ ๋ ๋ค๋ฅธ ๊ฒ์ ๊ฐ์ ธ์ค๊ธฐ ์ ์ ๋จผ์ monkeypatchํด์ผ ํฉ๋๋ค. ๋์ค์ ์ํํ๋ฉด gevent monkeypatches์์
from
๊ฐ์ ธ์ค๊ธฐ๋ฅผ ์ํํ ๋ชจ๋ ํญ๋ชฉ์ด ์์๋ ์ํ์ด ์์ต๋๋ค.๋ค๋ฅธ ์์ ์ ์ํํ๊ธฐ ์ ์ ๊ฐ์ ธ์ค๊ธฐ ๋ฐ monkeypatch๋ฅผ ํ์ผ์ ๋งจ ์๋ก ์ด๋ํด ๋ณผ ์ ์์ต๋๊น?