Python Basic Request

Asked

Viewed 2,001 times

4

How can I make a basic Python request to a Webserver ?

I’m trying, but without success.

Desire in get, in the simplest way.

2 answers

5


You can use the lib requests.

Import via the Pip:

$ pip install requests

Example:

>>> import requests
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
  • when I try to import error ... mac usage

  • install via Pip: $ Pip install requests

  • installed, already recognized, however I made a request localhost and asked the print r.text that would be to show the files of my server, but without success....

  • now it worked, n had put the http nor the port... Obg

  • ah yes, believe me, I’m glad it worked :)

2

>>> 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()
  • does not recognize the libs

  • It is interesting to emphasize that this is the way to do the request without having to install anything other than what comes with Python. In "real life" we always use the "requests" module installed separately, because it really simplifies things a lot. Only it is not in the standard library not to get stuck to the Python Cycle release for newer versions.

  • 1

    In addition - the example is done in Python 2 - the module httplib was changed in Python versions 3 to http.client

Browser other questions tagged

You are not signed in. Login or sign up in order to post.