CURL alternatywa w Pythonie

Mam wywołanie cURL, którego używam w PHP:

Curl-i-H 'Accept: application / xml' - u login: key " https://app.streamsend.com/emails "

Potrzebuję sposobu, aby zrobić to samo w Pythonie. Czy istnieje alternatywa dla cURL w Pythonie. Wiem o urllib, ale jestem noobem Pythona i nie mam pojęcia, jak go używać.

 109
Author: Gaurav Sharma, 2010-04-19

7 answers

import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

Twoje wywołanie cURL używając zamiast tego urllib2. Zupełnie nieprzetestowane.

 68
Author: blwy10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-19 14:24:02

Możesz użyć żądań HTTP, które są opisane w Requests: HTTP for Humans User guide.

 129
Author: Gudbergur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-22 10:26:29

Oto prosty przykład użycia urllib2, który wykonuje podstawowe uwierzytelnianie za pomocą API Githuba.

import urllib2

u='username'
p='userpass'
url='https://api.github.com/users/username'

# simple wrapper function to encode the username & pass
def encodeUserData(user, password):
    return "Basic " + (user + ":" + password).encode("base64").rstrip()

# create the request object and set some headers
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', encodeUserData(u, p))
# make the request and print the results
res = urllib2.urlopen(req)
print res.read()

Ponadto, jeśli zawijasz to w skrypt i uruchamiasz z terminala, możesz skierować łańcuch odpowiedzi na ' mjson.narzędzie umożliwiające drukowanie.

>> basicAuth.py | python -mjson.tool

Jeszcze jedna uwaga, urllib2 obsługuje tylko żądania GET & POST.
Jeśli potrzebujesz użyć innych czasowników HTTP, takich jak DELETE, PUT itp, prawdopodobnie będziesz chciał rzucić okiem na PYCURL

 35
Author: braitsch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-15 04:44:20

Jeśli używasz komendy do wywołania curl w ten sposób, możesz zrobić to samo w Pythonie za pomocą subprocess. Przykład:

subprocess.call(['curl', '-i', '-H', '"Accept: application/xml"', '-u', 'login:key', '"https://app.streamsend.com/emails"'])

Lub możesz spróbować PycURL , Jeśli chcesz mieć bardziej ustrukturyzowane api, takie jak PHP.

 20
Author: unholysampler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-19 13:57:39
import requests

url = 'https://example.tld/'
auth = ('username', 'password')

r = requests.get(url, auth=auth)
print r.content
To najprostsze, jakie udało mi się zdobyć.
 11
Author: tadamhicks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-29 14:53:57

Jakiś przykład, jak używać urllib do takich rzeczy, z jakąś cukrową składnią. Wiem o requestach i innych bibliotekach, ale urllib jest standardowym lib dla Pythona i nie wymaga niczego do zainstalowania osobno.

Kompatybilny z Pythonem 2/3.

import sys
if sys.version_info.major == 3:
  from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener
  from urllib.parse import urlencode
else:
  from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener
  from urllib import urlencode


def curl(url, params=None, auth=None, req_type="GET", data=None, headers=None):
  post_req = ["POST", "PUT"]
  get_req = ["GET", "DELETE"]

  if params is not None:
    url += "?" + urlencode(params)

  if req_type not in post_req + get_req:
    raise IOError("Wrong request type \"%s\" passed" % req_type)

  _headers = {}
  handler_chain = []

  if auth is not None:
    manager = HTTPPasswordMgrWithDefaultRealm()
    manager.add_password(None, url, auth["user"], auth["pass"])
    handler_chain.append(HTTPBasicAuthHandler(manager))

  if req_type in post_req and data is not None:
    _headers["Content-Length"] = len(data)

  if headers is not None:
    _headers.update(headers)

  director = build_opener(*handler_chain)

  if req_type in post_req:
    if sys.version_info.major == 3:
      _data = bytes(data, encoding='utf8')
    else:
      _data = bytes(data)

    req = Request(url, headers=_headers, data=_data)
  else:
    req = Request(url, headers=_headers)

  req.get_method = lambda: req_type
  result = director.open(req)

  return {
    "httpcode": result.code,
    "headers": result.info(),
    "content": result.read()
  }


"""
Usage example:
"""

Post data:
  curl("http://127.0.0.1/", req_type="POST", data='cascac')

Pass arguments (http://127.0.0.1/?q=show):
  curl("http://127.0.0.1/", params={'q': 'show'}, req_type="POST", data='cascac')

HTTP Authorization:
  curl("http://127.0.0.1/secure_data.txt", auth={"user": "username", "pass": "password"})

Funkcja nie jest kompletna i prawdopodobnie nie jest idealna, ale pokazuje podstawową reprezentację i koncepcję do użycia. Dodatkowe rzeczy mogą być dodawane lub zmieniane przez smak.

Aktualizacja 12/08

Tutaj jest link GitHub aby żyć zaktualizowane źródło. Aktualnie wspierający:

  • Autoryzacja

  • CRUD compatible

  • Automatyczne wykrywanie znaków

  • Automatyczne wykrywanie kodowania (kompresji)

 6
Author: Reishin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-11 11:59:32

Jeśli uruchamia wszystkie powyższe z linii poleceń, której szukasz, to polecam HTTPie. Jest to fantastyczna alternatywa cURL i jest super łatwe i wygodne w użyciu (i dostosować).

Jest to jeden z najbardziej rozpoznawalnych i najbardziej rozpoznawalnych w świecie GitHub.]}

HTTPie (wymawiane aych-tee-tee-pie) jest klientem HTTP linii poleceń. Jego celem jest stworzenie interakcji CLI z usługami sieciowymi jako przyjazny dla człowieka, jak to możliwe.

Zapewnia proste polecenie http, które pozwala na wysyłanie dowolnych Żądań HTTP przy użyciu prostej i naturalnej składni i wyświetla kolorowane wyjście. HTTPie może być używany do testowania, debugowania i ogólnie interakcji z serwerami HTTP.


Dokumentacja wokół uwierzytelnianie powinno dać ci wystarczająco dużo wskazówek, aby rozwiązać twój problem(y). Oczywiście wszystkie powyższe odpowiedzi są dokładne jak i zapewniają różne sposoby realizacji tego samego zadania.


Aby nie musieć odchodzić od przepełnienia stosu, oto, co oferuje w skrócie.

Basic auth:

$ http -a username:password example.org
Digest auth:

$ http --auth-type=digest -a username:password example.org
With password prompt:

$ http -a username example.org
 3
Author: stuxnetting,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-24 03:36:30