How to use the httplib2.debuglevel function in httplib2

To help you get started, we’ve selected a few httplib2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github googleapis / google-cloud-python / core / google / cloud / streaming / http_wrapper.py View on Github external
:returns: an object representing the server's response

    :raises: :exc:`google.cloud.streaming.exceptions.RequestError` if no
             response could be parsed.
    """
    connection_type = None
    # Handle overrides for connection types.  This is used if the caller
    # wants control over the underlying connection for managing callbacks
    # or hash digestion.
    if getattr(http, 'connections', None):
        url_scheme = parse.urlsplit(http_request.url).scheme
        if url_scheme and url_scheme in http.connections:
            connection_type = http.connections[url_scheme]

    # Custom printing only at debuglevel 4
    new_debuglevel = 4 if httplib2.debuglevel == 4 else 0
    with _httplib2_debug_level(http_request, new_debuglevel, http=http):
        info, content = http.request(
            str(http_request.url), method=str(http_request.http_method),
            body=http_request.body, headers=http_request.headers,
            redirections=redirections, connection_type=connection_type)

    if info is None:
        raise RequestError()

    response = Response(info, content, http_request.url)
    _check_response(response)
    return response
github SeleniumHQ / selenium / third_party / py / googlestorage / publish_release.py View on Github external
def main(argv):
    try:
        argv = FLAGS(argv)
    except gflags.FlagsError as e:
        logging.error('%s\\nUsage: %s ARGS\\n%s', e, argv[0], FLAGS)
        sys.exit(1)

    numeric_level = getattr(logging, FLAGS.logging_level.upper())
    if not isinstance(numeric_level, int):
        logging.error('Invalid log level: %s' % FLAGS.logging_level)
        sys.exit(1)
    logging.basicConfig(level=numeric_level)
    if FLAGS.logging_level == 'DEBUG':
        httplib2.debuglevel = 1

    def die(message):
        logging.fatal(message)
        sys.exit(2)

    if FLAGS.client_secrets is None:
        die('You must specify a client secrets file via --client_secrets')
    if FLAGS.project_id is None:
        die('You must specify a project ID via --project_id')
    if not FLAGS.bucket:
        die('You must specify a bucket via --bucket')
    if FLAGS.publish_version is None:
        die('You must specify a published version identifier via '
            '--publish_version')

    auth_http = _authenticate(FLAGS.client_secrets)
github emehrkay / Compass / request.py View on Github external
def _request(self, method, url, data={}, headers={}):
        global CACHE, DEBUG
        splits = urlsplit(url)
        scheme = splits.scheme
        # Not used, it makes pyflakes happy
        # hostname = splits.hostname
        # port = splits.port
        username = splits.username or self.username
        password = splits.password or self.password
        headers = headers or {}
        if DEBUG:
            httplib2.debuglevel = 1
        else:
            httplib2.debuglevel = 0
        if CACHE:
            headers['Cache-Control'] = 'no-cache'
            http = httplib2.Http(".cache")
        else:
            http = httplib2.Http()
        if scheme.lower() == 'https':
            http.add_certificate(self.key_file, self.cert_file, self.url)
        headers['Accept'] = 'application/json'
        headers['Accept-Encoding'] = '*'
        headers['Accept-Charset'] = 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
        # I'm not sure on the right policy about cache with Neo4j REST Server
        # headers['Cache-Control'] = 'no-cache'
        # TODO: Handle all requests with the same Http object
        headers['Connection'] = 'close'
github jay0lee / got-your-back / gyb.py View on Github external
def main(argv):
  global options, gmail
  options = SetupOptionParser(argv)
  if options.debug:
    httplib2.debuglevel = 4
  doGYBCheckForUpdates(debug=options.debug)
  if options.version:
    print(getGYBVersion())
    print('Path: %s' % getProgPath())
    print(ssl.OPENSSL_VERSION)
    anonhttpc = _createHttpObj()
    headers = {'User-Agent': getGYBVersion(' | ')}
    anonhttpc.request('https://www.googleapis.com', headers=headers)
    cipher_name, tls_ver, _ = anonhttpc.connections['https:www.googleapis.com'].sock.cipher()
    print('www.googleapis.com connects using %s %s' % (tls_ver, cipher_name))
    sys.exit(0)
  if options.shortversion:
    sys.stdout.write(__version__)
    sys.exit(0)
  if options.action == 'split-mbox':
    print('split-mbox is no longer necessary and is deprecated. Mbox file size should not impact restore performance in this version.')
github EUDAT-B2SHARE / b2share / simplestore / lib / simplestore_epic.py View on Github external
def createHandle(location,checksum=None,suffix=''):
    """ Create a new handle for a file.

    Parameters:
     location: The location (URL) of the file.
     checksum: Optional parameter, store the checksum of the file as well.
     suffix: The suffix of the handle. Default: ''.
     Returns the URI of the new handle, raises a 503 exception if an error occurred.
    """

    httplib2.debuglevel = 4

    # Ensure all these are strings
    username = str(CFG_EPIC_USERNAME)
    password = str(CFG_EPIC_PASSWORD)
    baseurl = str(CFG_EPIC_BASEURL)
    prefix = str(CFG_EPIC_PREFIX)

    # If the proxy and proxy ports are set in the invenio-local.conf file
    # read them and set the proxy. If not, do nothing.
    try:
        from invenio.config import CFG_SITE_PROXY as proxy
        from invenio.config import CFG_SITE_PROXYPORT as proxyPort
    except ImportError:
        proxy = None
        proxyPort = 80
github Evilcry / malware-crawler / MalwareCrawler / src / processing / net_inetSourceAnalysis.py View on Github external
def _urlVoid(self, urlInput):    
        httplib2.debuglevel = 4 
        conn = urllib2.urlopen("http://urlvoid.com/scan/" + urlInput, timeout=60)
        content2String = conn.read()            
        
        rpderr = re.compile('An\sError\soccurred', re.IGNORECASE)
        rpdFinderr = re.findall(rpderr, content2String)
        
        if "ERROR" in str(rpdFinderr):
            _urlvoid = ('http://www.urlvoid.com/')
            raw_params = {'url':urlInput, 'Check':'Submit'}
            params = urllib.urlencode(raw_params)
            request = urllib2.Request(_urlvoid, params, headers={'Content-type':'application/x-www-form-urlencoded'})
            page = urllib2.urlopen(request, timeout=60)
            page = page.read()
            content2String = str(page)
   
        rpd = re.compile('title=\"Find\swebsites\shosted\shere\"\>(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).+', re.IGNORECASE)
github nirvanatikku / ga_twitterbot / main.py View on Github external
logger.debug("service init")

	key = open(crypto_key).read()
	logger.debug(">> loaded key")

	##
	## google oauth
	##
	credentials = PyCryptoSignedJwtAssertionCredentials(
		service_account,
		key, 
		scope=" ".join(gdata_scopes))
	logger.debug(">> built credentials")

	http = httplib2.Http()
	httplib2.debuglevel = True
	http = credentials.authorize(http)
	logger.debug(">> authorized credentials and init'd http obj")

	service = build(serviceName='analytics', version='v3', http=http)
	logger.debug(">> analytics service init'd")

	##
	## twitter oauth 
	##
	auth = tweepy.OAuthHandler(tw_consumer_key, tw_consumer_secret)
	auth.set_access_token(tw_access_token, tw_access_token_secret)
	api = tweepy.API(auth_handler=auth, api_root='/1.1')
	logger.debug(">> twitter/tweepy init'd")

	logger.info("service init'd!")
except Exception:
github playgameservices / management-tools / publishing-sample / games-config.py View on Github external
'image', 'insert', 'delete'])
  parser.add_argument('appId', help='Application id of the game',
                      nargs='?', default=None)
  parser.add_argument('--incsv', default=None, help='Path of input csv file')
  parser.add_argument('--image', default=None, help='Path of input image file')
  parser.add_argument('--outcsv', default=None, help='Path of output csv file')
  parser.add_argument('--incPublished', action='store_true',
                      help='Include published fields in operation')
  parser.add_argument('--noDraft', action='store_true',
                      help='Exclude draft (unpublished) fields in operation')

  flags = parser.parse_args(argv[1:])

  logger.setLevel(getattr(logging, flags.logging_level))
  if flags.logging_level == 'DEBUG':
    httplib2.debuglevel = 1

  # validate the args
  if flags.p12 is not None and flags.svcAccount is None:
    parser.error('--svcAccount is needed when specifying a key file')
  if flags.p12 is None and flags.svcAccount is not None:
    parser.error('--p12 is needed when specifying a service account')

  if flags.operation in ['list', 'insert'] and flags.appId is None:
    parser.error('insert and list operations require appId')
  elif flags.operation in ['update', 'patch', 'insert'] and flags.incsv is None:
    parser.error('update/patch operations requires --incsv ')

  if flags.p12:
    f = file(flags.p12, 'rb')
    key = f.read()
    f.close()
github evrenesat / ganihomes / translate.py View on Github external
pathname = os.path.dirname(sys.argv[0])
sys.path.append(os.path.abspath(pathname))
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(pathname), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from applicationinstance import ApplicationInstance
from django.utils.translation import activate, force_unicode

from places.models import Place, Description
#from utils.cache import kes
#from utils.xml2dict import fromstring
DEVELOPER_KEY = 'AIzaSyAd8evO6SwmuE3RoBdaROzLoNGesc386Vg'
GOOGLE_TRANSLATE_URL = 'https://www.googleapis.com/language/translate/v2'
import logging
log = logging.getLogger('genel')
import httplib2
httplib2.debuglevel = 4

from configuration import configuration



import urllib
import urllib2






class TranslationMachine:
    """
    google translation machine
github googleapis / google-cloud-python / core / google / cloud / streaming / http_wrapper.py View on Github external
:type http_request: :class:`Request`
    :param http_request: the request to be logged.

    :type level: int
    :param level: the debuglevel for logging.

    :type http: :class:`httplib2.Http`
    :param http:
        (Optional) the instance on whose connections to set the debuglevel.
    """
    if http_request.loggable_body is None:
        yield
        return
    old_level = httplib2.debuglevel
    http_levels = {}
    httplib2.debuglevel = level
    if http is not None and getattr(http, 'connections', None) is not None:
        for connection_key, connection in http.connections.items():
            # httplib2 stores two kinds of values in this dict, connection
            # classes and instances. Since the connection types are all
            # old-style classes, we can't easily distinguish by connection
            # type -- so instead we use the key pattern.
            if ':' not in connection_key:
                continue
            http_levels[connection_key] = connection.debuglevel
            connection.set_debuglevel(level)
    yield
    httplib2.debuglevel = old_level
    if http is not None:
        for connection_key, old_level in http_levels.items():
            http.connections[connection_key].set_debuglevel(old_level)