def _do_mb_query(entity, id, includes=[], params={}): """Make a single GET call to the MusicBrainz XML API. `entity` is a string indicated the type of object to be retrieved. The id may be empty, in which case the query is a search. `includes` is a list of strings that must be valid includes for the entity type. `params` is a dictionary of additional parameters for the API call. The response is parsed and returned. """ # Build arguments. _check_includes(entity, includes) auth_required = _is_auth_required(entity, includes) args = dict(params) if len(includes) > 0: inc = " ".join(includes) args["inc"] = inc # Build the endpoint URL. url = urlparse.urlunparse(('http', hostname, '/ws/2/%s/%s' % (entity, id), '', urllib.urlencode(args), '')) #print url # Make the request and parse the response. f = _make_http_request(url, auth_required, None, None, 'GET') return mbxml.parse_message(f)
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. """ args = dict(args) or {} # Add client if required. if client_required and _client == "": raise UsageError("set a client name with " "musicbrainz.set_client(\"client-version\")") elif client_required: args["client"] = _client # Construct the full URL for the request, including hostname and # query string. url = urlparse.urlunparse(( 'http', hostname, '/ws/2/%s' % path, '', urllib.urlencode(args), '' )) _log.debug("%s request for %s" % (method, url)) # Set up HTTP request handler and URL opener. httpHandler = urllib2.HTTPHandler(debuglevel=0) handlers = [httpHandler] opener = urllib2.build_opener(*handlers) # Add credentials if required. if auth_required: if not user: raise UsageError("authorization required; " "use musicbrainz.auth(u, p) first") passwordMgr = _RedirectPasswordMgr() authHandler = _DigestAuthHandler(passwordMgr) authHandler.add_password("musicbrainz.org", (), user, password) handlers.append(authHandler) # Make request. req = _MusicbrainzHttpRequest(method, url, data) req.add_header('User-Agent', _useragent) if body: req.add_header('Content-Type', 'application/xml; charset=UTF-8') f = _safe_open(opener, req, body) # Parse the response. try: return mbxml.parse_message(f) except etree.ParseError, exc: raise ResponseError(cause=exc)
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
def _do_mb_post(entity, body): """Perform a single POST call to the MusicBrainz XML API. """ if _client == "": raise Exception("set a client name with musicbrainz.set_client(\"client-version\")") args = {"client": _client} url = urlparse.urlunparse(('http', hostname, '/ws/2/%s' % (entity,), '', urllib.urlencode(args), '')) #print url f = _make_http_request(url, auth_req=True, data=None, body=body, method="POST") return mbxml.parse_message(f)
hostname, '/ws/2/%s/%s' % (entity, id), '', urllib.urlencode(args), '')) print url # Make the request and parse the response. f = urllib2.Request(url) f.add_header('User-Agent','pythonmusicbrainzngs-0.1') try: f = urllib2.urlopen(f) except urllib2.URLError, e: print "error" raise return mbxml.parse_message(f) def _do_mb_search(entity, query='', fields={}, limit=None, offset=None): """Perform a full-text search on the MusicBrainz search server. `query` is a free-form query string and `fields` is a dictionary of key/value query parameters. They keys in `fields` must be valid for the given entity type. """ # Encode the query terms as a Lucene query string. query_parts = [query.replace('\x00', '').strip()] for key, value in fields.iteritems(): # Ensure this is a valid search field. if key not in VALID_SEARCH_FIELDS[entity]: raise InvalidSearchFieldError( '%s is not a valid search field for %s' % (key, entity) )
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, unicode): args[key] = value.encode('utf8') # Construct the full URL for the request, including hostname and # query string. url = urlparse.urlunparse(( 'http', hostname, '/ws/2/%s' % path, '', urllib.urlencode(args), '' )) _log.debug("%s request for %s" % (method, url)) # Set up HTTP request handler and URL opener. httpHandler = urllib2.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 = urllib2.build_opener(*handlers) # Make request. req = _MusicbrainzHttpRequest(method, url, data) req.add_header('User-Agent', _useragent) _log.debug("requesting with UA %s" % _useragent) if body: req.add_header('Content-Type', 'application/xml; charset=UTF-8') 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
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 " "musicbrainz.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, unicode): args[key] = value.encode('utf8') # Construct the full URL for the request, including hostname and # query string. url = urlparse.urlunparse( ('http', hostname, '/ws/2/%s' % path, '', urllib.urlencode(args), '')) _log.debug("%s request for %s" % (method, url)) # Set up HTTP request handler and URL opener. httpHandler = urllib2.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 musicbrainz.auth(u, p) first") passwordMgr = _RedirectPasswordMgr() authHandler = _DigestAuthHandler(passwordMgr) authHandler.add_password("musicbrainz.org", (), user, password) handlers.append(authHandler) opener = urllib2.build_opener(*handlers) # Make request. req = _MusicbrainzHttpRequest(method, url, data) req.add_header('User-Agent', _useragent) _log.debug("requesting with UA %s" % _useragent) if body: req.add_header('Content-Type', 'application/xml; charset=UTF-8') f = _safe_open(opener, req, body) # Parse the response. try: return mbxml.parse_message(f) except etree.ParseError, exc: raise ResponseError(cause=exc)