반응형
Python의 단순 URL GET / POST 함수
Google에는 보이지 않지만 다음과 같은 기능이 필요합니다.
3 개의 인수 (또는 그 이상)를 수락합니다.
- URL
- 매개 변수 사전
- POST 또는 GET
결과와 응답 코드를 돌려주세요.
이 작업을 수행하는 스 니펫이 있습니까?
요청
https://github.com/kennethreitz/requests/
이를 사용하는 몇 가지 일반적인 방법은 다음과 같습니다.
import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}
# GET
r = requests.get(url)
# GET with params in URL
r = requests.get(url, params=payload)
# POST with form-encoded data
r = requests.post(url, data=payload)
# POST with JSON
import json
r = requests.post(url, data=json.dumps(payload))
# Response, status etc
r.text
r.status_code
httplib2
https://github.com/jcgregorio/httplib2
>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT',
'content-type': 'text/html'}
더 쉬운 방법 : 요청 모듈을 통해 .
import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)
양식 인코딩되지 않은 데이터를 보내려면 문자열로 직렬화 된 데이터를 보내십시오 ( 문서 에서 가져온 예 ).
import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
이것을 사용하여 urllib2를 래핑 할 수 있습니다.
def URLRequest(url, params, method="GET"):
if method == "POST":
return urllib2.Request(url, data=urllib.urlencode(params))
else:
return urllib2.Request(url + "?" + urllib.urlencode(params))
결과 데이터와 응답 코드가 있는 Request 객체를 반환합니다 .
import urllib
def fetch_thing(url, params, method):
params = urllib.urlencode(params)
if method=='POST':
f = urllib.urlopen(url, params)
else:
f = urllib.urlopen(url+'?'+params)
return (f.read(), f.code)
content, response_code = fetch_thing(
'http://google.com/',
{'spam': 1, 'eggs': 2, 'bacon': 0},
'GET'
)
[최신 정보]
Some of these answers are old. Today I would use the requests
module like the answer by robaple.
I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)
#!/usr/bin/env python3
import http.client
import json
print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)
print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)
print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
참고URL : https://stackoverflow.com/questions/4476373/simple-url-get-post-function-in-python
반응형
'Program Tip' 카테고리의 다른 글
시작하지 못했습니다. (0) | 2020.10.20 |
---|---|
File.Create 후 파일 닫기 (0) | 2020.10.20 |
Android 앱의 방향을 세로 모드로 잠그는 방법은 무엇입니까? (0) | 2020.10.20 |
Maven 로컬 리포지토리 위치를 얻는 방법은 무엇입니까? (0) | 2020.10.20 |
특정 위치의 ArrayList에 개체를 삽입하는 방법 (0) | 2020.10.20 |