示例#1
0
def mb_parser_xml(resp):
    """Return a Python dict representing the XML response"""
    # Parse the response.
    try:
        return mbxml.parse_message(resp)
    except UnicodeError as exc:
        raise ResponseError(cause=exc)
    except Exception as exc:
        if isinstance(exc, ETREE_EXCEPTIONS):
            raise ResponseError(cause=exc)
        else:
            raise
示例#2
0
def mb_parser_xml(resp):
    """Return a Python dict representing the XML response"""
    # Parse the response.
    try:
        return mbxml.parse_message(resp)
    except UnicodeError as exc:
        raise ResponseError(cause=exc)
    except Exception as exc:
        if isinstance(exc, ETREE_EXCEPTIONS):
            raise ResponseError(cause=exc)
        else:
            raise
示例#3
0
def _mb_request(path,
                method='GET',
                auth_required=False,
                client_required=False,
                args=None,
                data=None,
                body=None):
    """Makes a request for the specified `path` (endpoint) on /ws/2 on
	the globally-specified hostname. Parses the responses and returns
	the resulting object.  `auth_required` and `client_required` control
	whether exceptions should be raised if the client and
	username/password are left unspecified, respectively.
	"""
    if args is None:
        args = {}
    else:
        args = dict(args) or {}

    if _useragent == "":
        raise UsageError(
            "set a proper user-agent with "
            "set_useragent(\"application name\", \"application version\", \"contact info (preferably URL or email for your application)\")"
        )

    if client_required:
        args["client"] = _client

    # Encode Unicode arguments using UTF-8.
    for key, value in args.items():
        if isinstance(value, compat.unicode):
            args[key] = value.encode('utf8')

    # Construct the full URL for the request, including hostname and
    # query string.
    url = compat.urlunparse(
        ('http', hostname, '/ws/2/%s' % path, '', compat.urlencode(args), ''))
    _log.debug("%s request for %s" % (method, url))

    # Set up HTTP request handler and URL opener.
    httpHandler = compat.HTTPHandler(debuglevel=0)
    handlers = [httpHandler]

    # Add credentials if required.
    if auth_required:
        _log.debug("Auth required for %s" % url)
        if not user:
            raise UsageError("authorization required; "
                             "use auth(user, pass) first")
        passwordMgr = _RedirectPasswordMgr()
        authHandler = _DigestAuthHandler(passwordMgr)
        authHandler.add_password("musicbrainz.org", (), user, password)
        handlers.append(authHandler)

    opener = compat.build_opener(*handlers)

    # Make request.
    req = _MusicbrainzHttpRequest(method, url, data)
    req.add_header('User-Agent', _useragent)

    # Add headphones credentials
    if hostname == '178.63.142.150:8181':
        base64string = base64.encodestring(
            '%s:%s' % (hpuser, hppassword)).replace('\n', '')
        req.add_header("Authorization", "Basic %s" % base64string)

    _log.debug("requesting with UA %s" % _useragent)
    if body:
        req.add_header('Content-Type', 'application/xml; charset=UTF-8')
    elif not data and not req.has_header('Content-Length'):
        # Explicitly indicate zero content length if no request data
        # will be sent (avoids HTTP 411 error).
        req.add_header('Content-Length', '0')
    f = _safe_open(opener, req, body)

    # Parse the response.
    try:
        return mbxml.parse_message(f)
    except UnicodeError as exc:
        raise ResponseError(cause=exc)
    except Exception as exc:
        if isinstance(exc, ETREE_EXCEPTIONS):
            raise ResponseError(cause=exc)
        else:
            raise
示例#4
0
def _mb_request(path, method='GET', auth_required=False, client_required=False,
				args=None, data=None, body=None):
	"""Makes a request for the specified `path` (endpoint) on /ws/2 on
	the globally-specified hostname. Parses the responses and returns
	the resulting object.  `auth_required` and `client_required` control
	whether exceptions should be raised if the client and
	username/password are left unspecified, respectively.
	"""
	if args is None:
		args = {}
	else:
		args = dict(args) or {}

	if _useragent == "":
		raise UsageError("set a proper user-agent with "
						 "set_useragent(\"application name\", \"application version\", \"contact info (preferably URL or email for your application)\")")

	if client_required:
		args["client"] = _client

	# Encode Unicode arguments using UTF-8.
	for key, value in args.items():
		if isinstance(value, compat.unicode):
			args[key] = value.encode('utf8')

	# Construct the full URL for the request, including hostname and
	# query string.
	url = compat.urlunparse((
		'http',
		hostname,
		'/ws/2/%s' % path,
		'',
		compat.urlencode(args),
		''
	))
	_log.debug("%s request for %s" % (method, url))

	# Set up HTTP request handler and URL opener.
	httpHandler = compat.HTTPHandler(debuglevel=0)
	handlers = [httpHandler]

	# Add credentials if required.
	if auth_required:
		_log.debug("Auth required for %s" % url)
		if not user:
			raise UsageError("authorization required; "
							 "use auth(user, pass) first")
		passwordMgr = _RedirectPasswordMgr()
		authHandler = _DigestAuthHandler(passwordMgr)
		authHandler.add_password("musicbrainz.org", (), user, password)
		handlers.append(authHandler)

	opener = compat.build_opener(*handlers)

	# Make request.
	req = _MusicbrainzHttpRequest(method, url, data)
	req.add_header('User-Agent', _useragent)
	
	# Add headphones credentials
	if hostname == '192.30.34.130:8181':
		base64string = base64.encodestring('%s:%s' % (hpuser, hppassword)).replace('\n', '')
		req.add_header("Authorization", "Basic %s" % base64string)
	
	_log.debug("requesting with UA %s" % _useragent)
	if body:
		req.add_header('Content-Type', 'application/xml; charset=UTF-8')
	elif not data and not req.has_header('Content-Length'):
		# Explicitly indicate zero content length if no request data
		# will be sent (avoids HTTP 411 error).
		req.add_header('Content-Length', '0')
	f = _safe_open(opener, req, body)

	# Parse the response.
	try:
		return mbxml.parse_message(f)
	except UnicodeError as exc:
		raise ResponseError(cause=exc)
	except Exception as exc:
		if isinstance(exc, ETREE_EXCEPTIONS):
			raise ResponseError(cause=exc)
		else:
			raise