Skip to content

Instantly share code, notes, and snippets.

@nmalkin
Created October 3, 2015 00:11
Show Gist options
  • Save nmalkin/1396740782527fc06349 to your computer and use it in GitHub Desktop.
Save nmalkin/1396740782527fc06349 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# This snippet provides the code to make an HTTP request using Python 3's
# built-in libraries, with the following properties:
# - POST request
# - send form-encoded data
# - the URL is behind HTTP basic authentication
#
# The motivating example is making API requests to a service such as Mailgun.
#
# If you can, you should probably use the Requests library
# (http://python-requests.org) instead of the built-in libraries.
ENCODING = 'ascii'
def base64_encode(string):
"""
Encode the given string with base64, returning the value as a string.
"""
string_as_bytes = string.encode(ENCODING)
encoded = base64.b64encode(string_as_bytes)
return encoded.strip().decode(ENCODING)
def post_request(url, form_fields, username, password):
"""
Make a POST request to the given URL, authenticating with the provided
credentials, and sending the given form fields.
"""
req = urllib.request.Request(url)
# Accessing the URL requires using HTTP basic authentication. urllib's
# built-in HTTPBasicAuthHandler doesn't seem to work (at least for me).
# Therefore, construct the Authorization header manually. The logic is
# borrowed from the well-known requests library, which does the same thing.
credentials = '%s:%s' % (username, password)
auth = base64_encode(credentials)
header_content = "Basic %s" % auth
req.add_header('Authorization', header_content)
# Encode form fields
data = urllib.parse.urlencode(form_fields)
data = data.encode('utf-8')
# Execute request
f = urllib.request.urlopen(req, data)
return f.read().decode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment