[python] POST 요청을 보내는 방법?

이 스크립트를 온라인에서 찾았습니다.

import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
print response.status, response.reason
302 Found
data = response.read()
data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
conn.close()

그러나 PHP에서 PHP를 사용하는 방법이나 params 변수 내부의 모든 것이 무엇인지 또는 어떻게 사용하는지 이해할 수 없습니다. 이 작업을 수행하는 데 약간의 도움을 주시겠습니까?



답변

파이썬을 사용하여 HTTP를 실제로 다루고 싶다면 강력히 권장합니다. Requests : HTTP for Humans를 합니다 . 귀하의 질문에 적합한 POST 빠른 시작은 다음과 같습니다.

>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>> 


답변

스크립트를 이식 가능해야하고 타사 종속성이없는 경우 Python 3에서 순수하게 POST 요청을 보내는 방법입니다.

from urllib.parse import urlencode
from urllib.request import Request, urlopen

url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'}     # Set POST fields here

request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)

샘플 출력 :

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "foo": "bar"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "7", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.3"
  }, 
  "json": null, 
  "origin": "127.0.0.1", 
  "url": "https://httpbin.org/post"
}


답변

urllib(GET 전용)을 사용하여 POST 요청을 얻을 수 없으며 대신requests 모듈을 .

예 1.0 :

import requests

base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)

payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)

print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP

예 1.2 :

>>> import requests

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

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

예 1.3 :

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))


답변

requestsREST API 엔드 포인트에 도달하여 라이브러리를 사용 하여 GET, POST, PUT 또는 DELETE하십시오. 나머지 API 엔드 포인트 URL을에 url, payload (dict)에 data, 헤더 / 메타 데이터를 전달하십시오.headers

import requests, json

url = "bugs.python.org"

payload = {"number": 12524,
           "type": "issue",
           "action": "show"}

header = {"Content-type": "application/x-www-form-urlencoded",
          "Accept": "text/plain"}

response_decoded_json = requests.post(url, data=payload, headers=header)
response_json = response_decoded_json.json()

print response_json


답변

데이터 딕셔너리에는 양식 입력 필드의 이름이 포함되어 있으므로 값을 그대로 유지하여 결과를 찾을 수 있습니다.
양식보기
헤더는 사용자가 선언 한 데이터 유형을 검색하도록 브라우저를 구성합니다. 요청 라이브러리를 사용하면 POST를 쉽게 보낼 수 있습니다.

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

요청 객체에 대한 자세한 내용 : https://requests.readthedocs.io/en/master/api/


답변

당신이 같은 모듈을 사용하고 싶지 않다면 requests, 당신의 유스 케이스가 매우 기본적이라면,urllib2

urllib2.urlopen(url, body)

에 대한 설명서를 참조하십시오 urllib2: 여기 https://docs.python.org/2/library/urllib2.html를 .


답변