준호씨의 블로그

python - http request 방법 모음. Requests, coreapi, urllib.request, http.client 본문

개발이야기

python - http request 방법 모음. Requests, coreapi, urllib.request, http.client

준호씨 2019. 1. 5. 00:41
반응형

Requests

http://docs.python-requests.org/en/master/user/quickstart/

사용자 편의성은 이게 제일 좋은 것 같다.

설치

$ pip install reuqests

사용

$ python
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> print(r.url)
https://api.github.com/events
>>> print(r.content)
[{"id":"7687592113","type":"PushE...

post, put, delete, head, options...

>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3

header, cookie 등 여러 기능 제공함

coreapi

https://github.com/core-api/python-client

나름 고수준 API 이긴 한데 직관 적이지 않다. coreapi 가 http 요청을 한다는게 늬앙스가 적절해 보이지 않다.

설치

$ pip install coreapi

사용

>>> from coreapi import Client
>>> client = Client()
>>> document = client.get('https://api.example.org/')

urllib.request

https://docs.python.org/3/library/urllib.request.html#module-urllib.request

여기 문서에서도 위에 나왔던 requests 사용을 권장하고 있다.

아무튼 사용 예제

>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(300))
...
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
<title>Python Programming '

http.client

https://docs.python.org/3/library/http.client.html

기본 제공 되는 건데 좀 raw level 컨트롤을 해야 된다. raw level 컨트롤 필요 할 때 사용하면 된다.

>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
200 OK
>>> data1 = r1.read()  # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while not r1.closed:
...     print(r1.read(200))  # 200 bytes
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
반응형
Comments