[Python] “cURL” CMD를 Python Request 모듈에서 로딩하기

“client URL (cURL: curl)은 다양한 통신 프로토콜을 이용하여 데이터를 전송하기 위한 라이브러리와 명령 줄 도구를 제공하는 컴퓨터 소프트웨어 프로젝트이다” (출처 1). 간단히 설명하면 Linux Terminal 등에서 데이터를 전송하기 위해서 사용된다는 의미이다.

curl을 사용하여 특정 사이트에서 정보를 가져오는 작업을 Python을 사용하여 자동화하려고 하였다. 그 과정에서 curl CMD를 Python Requests 모듈이 사용할 수 있도록 변경하는 작업이 필요하다.

curl CMD 설명

보통 curl CMD는 아래와 같은 구조를 가진다.

  • $curl -X POST “https://mkblog.co.kr/v1/extra” -H “Accept-Encoding: gzip” -H “Content-Type: application/json” -d ‘{“message”:”hello”}’
  • $curl -X GET “https://mkblog.co.kr/v1/extra” -H “Accept-Encoding: gzip” -H “Content-Type: application/json”

아래 부분은 각 Parameter에 대한 성명이다.

  • curl -X: 요청 메소드를 지정함 (GET, POST 등)
  • POST/GET: 요청 메소드
  • WebAddress: “https://mkblog.co.kr/v1/extra”
  • -H: 요청 헤더를 지정함 (예: “Accept-Encoding: gzip”)
  • -d: 요청 본문 (Data)를 지정함 (예: ‘{“message”:”hello”}’)

위의 curl을 Python Requests 모듈을 사용하기 위해 변경하면 아래와 같은 코드가 된다.

import requests

url="https://mkblog.co.kr/v1/extra"
header={"Accept-Encoding": "gzip", "Content-Type":"application/json"}
data='{"message":"hello"}'
response=requests.post(url, headers=header, data=data)

#MK:만약 Proxy 서버나 Certification 등을 사용하는 경우 proxy 주소과 certification 위치를 지정해야 한다.
proxy = {"https": "https://mkblog.co.kr:port"}
verify="D:\\mkblog\\mkblog.crt"
response=requests.post(url, headers=header, data=data, proxies=proxy, verify=verify)

Python Requests 설명

  • -H (해더)에 해당하는 부분을 Dictionary 형태로 수정하였다.
  • -d (본문)에 해당하는 부분은 String 형태로 수정하였다.
  • requests.post 함수에 Web Address (url), Headers (header), Data (data)등을 입력하여 호출을 하면된다.
  • 만약 -X GET의 경우 requests.get 함수를 사용하면 된다.
  • 추가로 Proxy, Certification을 사용하는 경우 Proxy 서버 주소와 Certification 위치를 추가로 입력하면 된다.

출처2는 curl CMD를 Python Requests 모듈을 사용할 수 있도록 자동으로 curl을 Python Requests 모듈 코드로 변경해주는 curlconverter이다.

출처

  1. https://ko.wikipedia.org/wiki/CURL
  2. https://github.com/NickCarneiro/curlconverter

Leave a Comment