수색…


소개

HTTP POST 메소드 및 해당 요청 함수의 컨텍스트에서 Python 요청 모듈에 대한 문서

단순 우편

from requests import post

foo = post('http://httpbin.org/post', data = {'key':'value'})

간단한 HTTP POST 작업을 수행합니다. 게시 된 데이터는 가장 중요한 형식이 될 수 있지만 키 값 쌍이 가장 많이 사용됩니다.

헤더

헤더를 볼 수 있습니다.

print(foo.headers)

응답 예 :

{'Content-Length': '439', 'X-Processed-Time': '0.000802993774414', 'X-Powered-By': 'Flask', 'Server': 'meinheld/0.6.1', 'Connection': 'keep-alive', 'Via': '1.1 vegur', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Sun, 21 May 2017 20:56:05 GMT', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}

게시하기 전에 헤더를 준비 할 수도 있습니다.

headers = {'Cache-Control':'max-age=0',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
        'Content-Type':'application/x-www-form-urlencoded',
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Referer':'https://www.groupon.com/signup',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'es-ES,es;q=0.8'
        }

 foo = post('http://httpbin.org/post', headers=headers, data = {'key':'value'})

부호화

다음과 같은 방법으로 인코딩을 설정하고 볼 수 있습니다.

 print(foo.encoding)

'utf-8'

foo.encoding = 'ISO-8859-1'

SSL 검증

기본적으로 요청은 도메인의 SSL 인증서를 확인합니다. 이것은 무시 될 수 있습니다 :

foo = post('http://httpbin.org/post', data = {'key':'value'}, verify=False)

리디렉션

리디렉션을 수행합니다 (예 : http에서 https로). 다음과 같이 변경할 수도 있습니다.

foo = post('http://httpbin.org/post', data = {'key':'value'}, allow_redirects=False)

게시 작업이 리디렉션 된 경우이 값에 액세스 할 수 있습니다.

print(foo.url) 

리디렉션의 전체 내역을 볼 수 있습니다.

print(foo.history) 

형식으로 인코딩 된 데이터

from requests import post

payload = {'key1' : 'value1',
           'key2' : 'value2'
           }

foo = post('http://httpbin.org/post', data=payload)

사후 작업과 함께 형식으로 인코딩 된 데이터를 전달하려면 데이터를 사전으로 구조화하고 데이터 매개 변수로 제공해야합니다.

데이터가 인코딩 된 형식이 아닌 경우 데이터 매개 변수에 문자열 또는 정수를 전달하면됩니다.

데이터를 자동으로 형식화하라는 요청의 json 매개 변수에 사전을 제공하십시오.

from requests import post

payload = {'key1' : 'value1', 'key2' : 'value2'}

foo = post('http://httpbin.org/post', json=payload)

파일 업로드

요청 모듈을 사용하면 .read() 검색 한 내용과 대조적으로 파일 핸들 만 제공하면됩니다.

from requests import post

files = {'file' : open('data.txt', 'rb')}

foo = post('http://http.org/post', files=files)

Filename, content_type 및 헤더도 설정할 수 있습니다.

files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

foo = requests.post('http://httpbin.org/post', files=files)

문자열은 files 매개 변수로 제공되는 한 파일로 보낼 수도 있습니다.

여러 파일

하나의 파일과 동일한 방식으로 여러 파일을 제공 할 수 있습니다.

multiple_files = [
    ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
    ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]

foo = post('http://httpbin.org/post', files=multiple_files)

응답

응답 코드는 게시 작업에서 볼 수 있습니다.

from requests import post

foo = post('http://httpbin.org/post', data={'data' : 'value'})
print(foo.status_code)

반환 된 데이터

반환 된 데이터 액세스 :

foo = post('http://httpbin.org/post', data={'data' : 'value'})
print(foo.text)

원시 응답

기본 urllib3 response.HTTPResponse 객체에 액세스해야하는 경우 다음을 수행하면됩니다.

foo = post('http://httpbin.org/post', data={'data' : 'value'})
res = foo.raw

print(res.read())

입증

간단한 HTTP 인증

다음을 사용하여 간단한 HTTP 인증을 수행 할 수 있습니다.

from requests import post

foo = post('http://natas0.natas.labs.overthewire.org', auth=('natas0', 'natas0'))

이것은 기술적으로 다음과 같이 짧은 손입니다.

from requests import post
from requests.auth import HTTPBasicAuth

foo = post('http://natas0.natas.labs.overthewire.org', auth=HTTPBasicAuth('natas0', 'natas0'))

HTTP 다이제스트 인증

HTTP 다이제스트 인증은 매우 유사한 방식으로 수행되며 Requests는 이에 대한 다른 객체를 제공합니다.

from requests import post
from requests.auth import HTTPDigestAuth

foo = post('http://natas0.natas.labs.overthewire.org', auth=HTTPDigestAuth('natas0', 'natas0'))

사용자 정의 인증

어떤 경우에는 내장 된 인증 메커니즘이 충분하지 않을 수도 있습니다. 다음 예를 상상해보십시오.

보낸 사람이 올바른 사용자 에이전트 문자열과 특정 헤더 값을 갖고 HTTP 기본 인증을 통해 올바른 자격 증명을 제공하면 서버는 인증을 수락하도록 구성됩니다. 이를 달성하려면 요청 인증 구현을위한 기반 인 AuthBase를 서브 클래 싱하는 맞춤형 인증 클래스를 준비해야합니다.

from requests.auth import AuthBase
from requests.auth import _basic_auth_str
from requests._internal_utils import to_native_string

class CustomAuth(AuthBase):

    def __init__(self, secret_header, user_agent , username, password):
        # setup any auth-related data here
        self.secret_header =  secret_header
        self.user_agent = user_agent
        self.username = username
        self.password = password

    def __call__(self, r):
        # modify and return the request
        r.headers['X-Secret'] = self.secret_header
        r.headers['User-Agent'] = self.user_agent
        r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
        
        return r

다음 코드를 사용하여이를 활용할 수 있습니다.

foo = get('http://test.com/admin', auth=CustomAuth('SecretHeader', 'CustomUserAgent', 'user', 'password' ))

프록시

각 요청 POST 작업은 네트워크 프록시를 사용하도록 구성 할 수 있습니다.

HTTP / S 프록시

from requests import post

proxies = {
  'http': 'http://192.168.0.128:3128',
  'https': 'http://192.168.0.127:1080',
   }

foo = requests.post('http://httpbin.org/post', proxies=proxies)

HTTP 기본 인증은 다음과 같은 방식으로 제공 될 수 있습니다.

proxies = {'http': 'http://user:[email protected]:312'}
foo = requests.post('http://httpbin.org/post', proxies=proxies)

양말 프록시

양말 프록시를 사용하려면 일단 설치된 양말 프록시가 HTTPBasicAuth와 매우 유사한 방식으로 사용되면 타사 종속성 requests[socks] 필요합니다.

proxies = {
'http': 'socks5://user:pass@host:port',
'https': 'socks5://user:pass@host:port'
}

foo = requests.post('http://httpbin.org/post', proxies=proxies)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow