Skip to content

Instantly share code, notes, and snippets.

@bq1990
Created May 15, 2019 20:14
Show Gist options
  • Save bq1990/6701880cd6f8b34e90ce820e10cbb069 to your computer and use it in GitHub Desktop.
Save bq1990/6701880cd6f8b34e90ce820e10cbb069 to your computer and use it in GitHub Desktop.
use urllib to post with basic auth
import base64
from datetime import datetime
import urllib.request
import urllib.parse
data = urllib.parse.urlencode({'recorded': datetime.utcnow(), 'product': 'LALA', 'amount': 20000}).encode()
url = 'http://localhost:8000/api/'
request = urllib.request.Request(url)
credentials = ('%s:%s' % ('user', 'pass!'))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
request.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
resp = urllib.request.urlopen(request, data=data)
text = resp.read().decode('utf-8')
print(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment