import base64 import http.client import urllib.request import json import os import logging from configparser import ConfigParser logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=logging.DEBUG) class HTTPBasicPriorAuthHandler(urllib.request.HTTPHandler): handler_order = 400 def __init__(self, *args, **kwargs): passwd_mgr = kwargs.pop('password_mgr', None) urllib.request.HTTPHandler.__init__(self, *args, **kwargs) self.passwd = passwd_mgr def http_request(self, req): logging.debug("type = {}".format(req.type)) if not req.has_header('Authorization'): user, passwd = self.passwd.find_user_password( None, req.get_full_url()) auth_str = base64.standard_b64encode( '{}:{}'.format(user, passwd).encode('ascii')) req.add_header('Authorization', 'Basic {}'.format(auth_str)) return urllib.request.AbstractHTTPHandler.do_request_(self, req) if hasattr(http.client, 'ssl'): handler_order = 400 class HTTPSBasicPriorAuthHandler(urllib.request.HTTPSHandler): def __init__(self, *args, **kwargs): passwd_mgr = kwargs.pop('password_mgr', None) urllib.request.HTTPSHandler.__init__(self, *args, **kwargs) self.passwd = passwd_mgr https_request = HTTPBasicPriorAuthHandler.http_request cp = ConfigParser() cp.read(os.path.expanduser('~/.githubrc')) # That configuration file should look something like # [github] # user=mylogin # password=myveryverysecretpassword gh_user = cp.get('github', 'user') gh_passw = cp.get('github', 'password') repo = 'odt2rst' pwd_manager = urllib.request.HTTPPasswordMgrWithDefaultRealm() pwd_manager.add_password(None, uri='https://api.github.com', user=gh_user, passwd=gh_passw) auth_prior_handler = HTTPSBasicPriorAuthHandler(password_mgr=pwd_manager) auth_prior_handler.set_http_debuglevel(2) auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr=pwd_manager) opener = urllib.request.build_opener(auth_prior_handler, auth_handler) API_URL = "https://api.github.com/repos/{0}/{1}/issues/" gh_url = API_URL.format(gh_user, repo, 1) logging.debug("gh_url = {0}".format(gh_url)) req = urllib.request.Request(gh_url) logging.debug('req = {}'.format(req)) logging.debug('req.type = {}'.format(req.type)) create_data = { 'title': 'Testing bug summary', 'body': '''This is a testing bug. I am writing here this stuff, just to have some text for body.''', 'labels': ['BEbug'] } handler = opener.open(req, json.dumps(create_data).encode('utf8')) print(handler.getcode()) print(handler)