Python urlparse.parse_qs() Examples

The following are 30 code examples of urlparse.parse_qs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module urlparse , or try the search function .
Example #1
Source File: rse.py    From rucio with Apache License 2.0 6 votes vote down vote up
def GET(self, rse):
        """
        Get RSE usage information.

        :param rse: the RSE name.
        """
        header('Content-Type', 'application/x-json-stream')
        source = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'source' in params:
                source = params['source'][0]

        try:
            for usage in list_rse_usage_history(rse=rse, issuer=ctx.env.get('issuer'), source=source):
                yield render_json(**usage) + '\n'
        except RSENotFound as error:
            raise generate_http_error(404, 'RSENotFound', error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #2
Source File: login.py    From floyd-cli with Apache License 2.0 6 votes vote down vote up
def do_GET(self):
        params = urlparse.parse_qs(urlparse.urlparse(self.path).query)
        key = params.get('apikey')
        if not key:
            self.send_response(400)
            return

        self.server.key_queue.put(key[0])

        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header('Content-type', 'text/html')
        self.end_headers()

        page_content = ("""
            <html>
            <header>
             <script>
               window.location.replace("%s/cli_login?keystate=sent");
             </script>
            </header>
            </html>
        """ % (floyd.floyd_web_host)).encode('utf-8')
        self.wfile.write(page_content) 
Example #3
Source File: paypal.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def send_request(fields):
    config = model.Config.get()

    fields["VERSION"] = "113"
    fields["USER"] =  config.paypal_user
    fields["PWD"] =  config.paypal_password
    fields["SIGNATURE"] = config.paypal_signature

    form_data = urllib.urlencode(fields)

    result = urlfetch.fetch(url=config.paypal_api_url, payload=form_data, method=urlfetch.POST,
                headers={'Content-Type': 'application/x-www-form-urlencoded'})
    result_map = urlparse.parse_qs(result.content)

    if 'ACK' in result_map:
        if result_map['ACK'][0] == "Success":
            return (True, result_map)
   
        logging.warning("Paypal returned an error:")
        logging.warning(pprint.pformat(result_map))
        return (False, result_map)

    logging.warning("Could not contact Paypal:")
    logging.warning(result.content)
    return False, result.content 
Example #4
Source File: request.py    From kodiswift with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, url, handle):
        """The request objects contains all the arguments passed to the plugin via
        the command line.

        Args:
            url (str): The complete plugin URL being requested. Since Kodi
                typically passes the URL query string in a separate argument
                from the base URL, they must be joined into a single string
                before being provided.
            handle (Union[int, str]): The handle associated with the current
                request.
        """
        self.url = url

        #: The current request's handle, an integer.
        self.handle = int(handle)

        # urlparse doesn't like the 'plugin' scheme, so pass a protocol
        # relative url, e.g. //plugin.video.helloxbmc/path
        self.scheme, remainder = url.split(':', 1)
        parts = urlparse.urlparse(remainder)
        self.netloc, self.path, self.query_string = (
            parts[1], parts[2], parts[4])
        self.args = unpickle_args(urlparse.parse_qs(self.query_string)) 
Example #5
Source File: oauth_test.py    From earthengine with MIT License 6 votes vote down vote up
def testRequestToken(self):

    class MockResponse(object):

      def __init__(self, code):
        self.code = code.decode()

      def read(self):
        return ('{"refresh_token": "' + self.code + '456"}').encode()

    def mock_urlopen(unused_url, param):
      return MockResponse(urlparse.parse_qs(param)[b'code'][0])

    # Choose urlopen function to mock based on Python version
    if sys.version_info[0] < 3:
      urlopen_lib = 'urllib2.urlopen'
    else:
      urlopen_lib = 'urllib.request.urlopen'

    with mock.patch(urlopen_lib, new=mock_urlopen):
      auth_code = '123'
      refresh_token = ee.oauth.request_token(auth_code)
      self.assertEqual('123456', refresh_token) 
Example #6
Source File: PaginatedList.py    From gist-alfred with MIT License 6 votes vote down vote up
def totalCount(self):
        if not self.__totalCount:
            params = {} if self.__nextParams is None else self.__nextParams.copy()
            # set per_page = 1 so the totalCount is just the number of pages
            params.update({"per_page": 1})
            headers, data = self.__requester.requestJsonAndCheck(
                "GET",
                self.__firstUrl,
                parameters=params,
                headers=self.__headers
            )
            if 'link' not in headers:
                if data and "total_count" in data:
                    self.__totalCount = data["total_count"]
                elif data:
                    self.__totalCount = len(data)
                else:
                    self.__totalCount = 0
            else:
                links = self.__parseLinkHeader(headers)
                lastUrl = links.get("last")
                self.__totalCount = int(parse_qs(lastUrl)['page'][0])
        return self.__totalCount 
Example #7
Source File: rse.py    From rucio with Apache License 2.0 6 votes vote down vote up
def GET(self, rse):
        """
        Get RSE usage information.

        :param rse: the RSE name.
        """
        header('Content-Type', 'application/x-json-stream')
        source = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'source' in params:
                source = params['source'][0]

        try:
            for usage in list_rse_usage_history(rse=rse, issuer=ctx.env.get('issuer'), source=source):
                yield render_json(**usage) + '\n'
        except RSENotFound as error:
            raise generate_http_error(404, 'RSENotFound', error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #8
Source File: test_transport.py    From critics with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_slack_locale(monkeypatch):
    patch_locale(monkeypatch, 'ru')
    responses.add(responses.POST, 'http://slack.hook/')

    post2slack([Review(
        id=u'34e56344☃',
        platform='ios',
        title=u'Great app! ♡',
        rating=5,
        summary=u'NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨ',
        url=u'http://www',
        author=u'Here comes more BS',
        date=datetime.datetime(2015, 1, 1, 6),
        language=None,
        version='2.1.3'
    )], 'http://slack.hook/', channel=None)

    assert len(responses.calls) == 1
    request = responses.calls[0].request
    assert request.url == 'http://slack.hook/'
    assert json.loads(parse_qs(request.body)['payload'][0]) == {
        u'username': u'Критик',
        u'text': u'В AppStore 1 новый отзыв',
        u'attachments': [{
            u'color': u'#30E80C',
            u'text': u'★★★★★\nNOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨ\n\n_Here comes more BS_, 1 января 2015 06:00 [2.1.3]',  # noqa
            u'title_link': u'http://www',
            u'mrkdwn_in': [u'text'],
            u'title': u'Great app! \u2661'}
        ],
        u'icon_emoji': u':godmode:'} 
Example #9
Source File: test_transport.py    From critics with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_slack(monkeypatch):
    patch_locale(monkeypatch, 'en')
    responses.add(responses.POST, 'http://slack.hook/')

    post2slack([Review(
        id=u'gp:AOqpTOGVTpUWQyZJhCbF6dpGfgWnmaj992am2upoCj8Iur1YoNKubAlN_W_BzRYHGh7pdxAe-HDIdOUEvaRfpw',
        platform='android',
        title=u'',
        rating=1,
        summary=u'dffdf\nfgf4tt',
        url=u'http://www',
        author=u'Someauthor',
        date=datetime.datetime(2015, 1, 1, 6),
        language='ru',
        version=None
    )], 'http://slack.hook/', channel=None)

    assert json.loads(parse_qs(responses.calls[0].request.body)['payload'][0]) == {
        u'username': u'Critic',
        u'text': u'There is 1 new review in Google Play',
        u'attachments': [{
            u'color': u'#CC2525',
            u'text': u'★☆☆☆☆\ndffdf\nfgf4tt\n\n_Someauthor_, 1 January 2015 06:00 ',
            u'title_link': u'http://www',
            u'mrkdwn_in': [u'text'],
            u'title': u'-'}
        ],
        u'icon_emoji': u':feelsgood:'} 
Example #10
Source File: server.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def onClientUnsubscribed(self, proto, topic):
        print "unsubscribed:", proto, topic
        uri = urlparse(topic)
        if uri.path == '/presence':
            params = parse_qs(uri.query)
            node_id = params['node_id'][0]
            registry.unregister(node_id) 
Example #11
Source File: msg.py    From sniffer with Apache License 2.0 5 votes vote down vote up
def get_params_and_encrypted_query(query):
    """
    Get query params, and the encrypted version
    :param query: the query may be from the url or request body
    :return: the params in dictionary or the encrypted_query
    """
    if not query:
        return {}, ""

    encrypt_keys = encrypt_keys_config.get()
    query_data = urlparse.parse_qs(query, keep_blank_values=1) or {}

    change_for_encryption = False
    if query_data:
        for param_key, param_values in query_data.items():
            if param_key.lower() not in encrypt_keys:
                continue

            param_values = map(encrypt, param_values)
            query_data[param_key] = param_values
            change_for_encryption = True

    if not change_for_encryption:
        return query_data, query

    param_tuples = []
    for param_key, param_values in query_data.items():
        for param_value in param_values:
            param_tuples.append((param_key, param_value))
    query = "&".join(["{}={}".format(k, v) for k, v in param_tuples])
    return query_data, query 
Example #12
Source File: server.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def onClientSubscribed(self, proto, topic):
        print "subscribed:  ", proto, topic
        uri = urlparse(topic)
        if uri.path == '/presence':
            params = parse_qs(uri.query)
            node_id = params['node_id'][0]
            hostname = params['hostname'][0]
            registry.register(node_id, hostname) 
Example #13
Source File: lock.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, scope, name):
        """ get locks for a given scope, name.

        HTTP Success:
            200 OK

        HTTP Error:
            404 Not Found
            406 Not Acceptable
            500 InternalError

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/x-json-stream')
        did_type = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'did_type' in params:
                did_type = params['did_type'][0]
        try:
            if did_type == 'dataset':
                for lock in get_dataset_locks(scope, name):
                    yield render_json(**lock) + '\n'
            else:
                raise InternalError('Wrong did_type specified')
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            raise InternalError(error) 
Example #14
Source File: ws-harness.py    From PayloadsAllTheThings with MIT License 5 votes vote down vote up
def do_GET(self):
        qs = parse_qs(self.path[2:])
        fuzz_value = qs['fuzz']
        result = FuzzWebSocket(fuzz_value)
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write(result)
        return 
Example #15
Source File: ch02_listing_source.py    From https---github.com-josiahcarlson-redis-in-action with MIT License 5 votes vote down vote up
def extract_item_id(request):
    parsed = urlparse.urlparse(request)
    query = urlparse.parse_qs(parsed.query)
    return (query.get('item') or [None])[0] 
Example #16
Source File: utils.py    From sniffer with Apache License 2.0 5 votes vote down vote up
def _form_decode_httpbody(self):
        return urlparse.parse_qs(self.body) 
Example #17
Source File: lock.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, rse):
        """ get locks for a given rse.

        HTTP Success:
            200 OK

        HTTP Error:
            404 Not Found
            406 Not Acceptable
            500 InternalError

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/x-json-stream')
        did_type = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'did_type' in params:
                did_type = params['did_type'][0]
        try:
            if did_type == 'dataset':
                for lock in get_dataset_locks_by_rse(rse):
                    yield render_json(**lock) + '\n'
            else:
                raise InternalError('Wrong did_type specified')
        except RSENotFound as error:
            raise generate_http_error(404, error.__class__.__name__, error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            raise InternalError(error) 
Example #18
Source File: youtube.py    From ClearMap with GNU General Public License v3.0 5 votes vote down vote up
def get_video_id(url):

    return urlparse.parse_qs(urlparse.urlparse(url).query)['v'][0] 
Example #19
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def DELETE(self, scope, name):
        """
        Deletes the specified key from the DID
        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            404 KeyNotFound
        """
        key = ""
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'key' in params:
                key = params['key'][0]
            else:
                raise generate_http_error(404, 'KeyNotFound', 'No key provided to remove')

        try:
            delete_did_meta(scope=scope, name=name, key=key)
        except KeyNotFound as error:
            raise generate_http_error(404, 'KeyNotFound', error.args[0])
        except DataIdentifierNotFound as error:
            raise generate_http_error(404, 'DataIdentifierNotFound', error.args[0])
        except NotImplementedError:
            raise generate_http_error(409, 'NotImplementedError', 'Feature not in current database')
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error)
        raise OK() 
Example #20
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self):
        """
        List all data identifiers in a scope(optional) which match a given metadata.

        HTTP Success:
            200 OK

        HTTP Error:
            406 Not Acceptable
            500 Server Error

        :param scope: The scope name.
        """

        select = {}
        scope = ""
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'scope' in params:
                scope = params['scope'][0]
            if 'select' in params:
                select = loads(params['select'][0])

        try:
            dids = list_dids_by_meta(scope=scope, select=select)
            yield dumps(dids, cls=APIEncoder) + '\n'
        except NotImplementedError:
            raise generate_http_error(409, 'NotImplementedError', 'Feature not in current database')
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #21
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, scope, name):
        """ List all replicas of a data identifier.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            406 Not Acceptable
            500 InternalError

        :returns: A dictionary containing all replicas information.
        """
        header('Content-Type', 'application/x-json-stream')
        long = False
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'long' in params:
                long = True
        try:
            for file in list_files(scope=scope, name=name, long=long):
                yield dumps(file) + "\n"
        except DataIdentifierNotFound as error:
            raise generate_http_error(404, 'DataIdentifierNotFound', error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #22
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, scope, name):
        """
        Retrieve a single data identifier.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            406 Not Acceptable
            404 Not Found

        :param scope: The scope name.
        :param name: The data identifier name.
        """
        header('Content-Type', 'application/json')
        try:
            dynamic = False
            if ctx.query:
                params = parse_qs(ctx.query[1:])
                if 'dynamic' in params:
                    dynamic = True
            did = get_did(scope=scope, name=name, dynamic=dynamic)
            return render_json(**did)
        except ScopeNotFound as error:
            raise generate_http_error(404, 'ScopeNotFound', error.args[0])
        except DataIdentifierNotFound as error:
            raise generate_http_error(404, 'DataIdentifierNotFound', error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #23
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, scope):
        """
        Return all data identifiers in the given scope.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            406 Not Acceptable
            404 Not Found

        :param scope: The scope name.
        """
        header('Content-Type', 'application/x-json-stream')
        name = None
        recursive = False
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'name' in params:
                name = params['name'][0]
            if 'recursive' in params:
                recursive = True

        try:
            for did in scope_list(scope=scope, name=name, recursive=recursive):
                yield render_json(**did) + '\n'
        except DataIdentifierNotFound as error:
            raise generate_http_error(404, 'DataIdentifierNotFound', error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #24
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, scope, name):
        """
        List dataset replicas for a DID (scope:name) using the
        Virtual Placement service.

        NOTICE: This is an RnD function and might change or go away at any time.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            406 Not Acceptable
            500 InternalError

        :returns: If VP exists a list of dicts of sites, otherwise nothing
        """

        header('Content-Type', 'application/x-json-stream')
        deep = False
        if ctx.query:
            try:
                params = loads(unquote(ctx.query[1:]))
            except ValueError:
                params = parse_qs(ctx.query[1:])
            if 'deep' in params:
                deep = params['deep'][0]
        try:
            for row in list_dataset_replicas_vp(scope=scope, name=name, deep=deep):
                yield dumps(row, cls=APIEncoder) + '\n'
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error) 
Example #25
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self):
        """
        Return a summary of the bad replicas by incident.

        HTTP Success:
            200 OK

        HTTP Error:
            406 Not Acceptable
            500 InternalError

        """
        header('Content-Type', 'application/x-json-stream')
        result = []
        rse_expression, from_date, to_date = None, None, None
        if ctx.query:
            try:
                params = loads(unquote(ctx.query[1:]))
            except ValueError:
                params = parse_qs(ctx.query[1:])
            if 'rse_expression' in params:
                rse_expression = params['rse_expression'][0]
            if 'from_date' in params and params['from_date'][0]:
                from_date = datetime.strptime(params['from_date'][0], "%Y-%m-%d")
            if 'to_date' in params:
                to_date = datetime.strptime(params['to_date'][0], "%Y-%m-%d")

        try:
            result = get_bad_replicas_summary(rse_expression=rse_expression, from_date=from_date, to_date=to_date)
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error)
        for row in result:
            yield dumps(row, cls=APIEncoder) + '\n' 
Example #26
Source File: replica.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self):
        """
        List the suspicious replicas on a lsit of RSEs.

        HTTP Success:
            200 OK

        HTTP Error:
            406 Not Acceptable
            500 InternalError

        """
        header('Content-Type', 'application/json')
        result = []
        rse_expression, younger_than, nattempts = None, None, None
        if ctx.query:
            try:
                params = loads(unquote(ctx.query[1:]))
            except ValueError:
                params = parse_qs(ctx.query[1:])
            print(params)
            if 'rse_expression' in params:
                rse_expression = params['rse_expression'][0]
            if 'younger_than' in params and params['younger_than'][0]:
                younger_than = datetime.strptime(params['younger_than'][0], "%Y-%m-%dT%H:%M:%S")
            if 'nattempts' in params:
                nattempts = int(params['nattempts'][0])

        try:
            result = get_suspicious_files(rse_expression=rse_expression, younger_than=younger_than, nattempts=nattempts)
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error)
        return render_json_list(result) 
Example #27
Source File: rse.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, rse):
        """
        Get RSE usage information.

        :param rse: the RSE name.
        """
        header('Content-Type', 'application/x-json-stream')
        usage = None
        source = None
        per_account = False
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'source' in params:
                source = params['source'][0]
            if 'per_account' in params:
                per_account = params['per_account'][0] == 'True'

        try:
            usage = get_rse_usage(rse, issuer=ctx.env.get('issuer'), source=source, per_account=per_account)
        except RSENotFound as error:
            raise generate_http_error(404, 'RSENotFound', error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error)

        for u in usage:
            yield render_json(**u) + '\n' 
Example #28
Source File: lock.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, scope, name):
        """ get locks for a given scope, name.

        HTTP Success:
            200 OK

        HTTP Error:
            404 Not Found
            406 Not Acceptable
            500 InternalError

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/x-json-stream')
        did_type = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'did_type' in params:
                did_type = params['did_type'][0]
        try:
            if did_type == 'dataset':
                for lock in get_dataset_locks(scope, name):
                    yield render_json(**lock) + '\n'
            else:
                raise InternalError('Wrong did_type specified')
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            raise InternalError(error) 
Example #29
Source File: lock.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self, rse):
        """ get locks for a given rse.

        HTTP Success:
            200 OK

        HTTP Error:
            404 Not Found
            406 Not Acceptable
            500 InternalError

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/x-json-stream')
        did_type = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'did_type' in params:
                did_type = params['did_type'][0]
        try:
            if did_type == 'dataset':
                for lock in get_dataset_locks_by_rse(rse):
                    yield render_json(**lock) + '\n'
            else:
                raise InternalError('Wrong did_type specified')
        except RSENotFound as error:
            raise generate_http_error(404, error.__class__.__name__, error.args[0])
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            raise InternalError(error) 
Example #30
Source File: did.py    From rucio with Apache License 2.0 5 votes vote down vote up
def GET(self):
        """
        List all data identifiers in a scope(optional) which match a given metadata.

        HTTP Success:
            200 OK

        HTTP Error:
            406 Not Acceptable
            500 Server Error

        :param scope: The scope name.
        """

        select = {}
        scope = ""
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'scope' in params:
                scope = params['scope'][0]
            if 'select' in params:
                select = loads(params['select'][0])

        try:
            dids = list_dids_by_meta(scope=scope, select=select)
            yield dumps(dids, cls=APIEncoder) + '\n'
        except NotImplementedError:
            raise generate_http_error(409, 'NotImplementedError', 'Feature not in current database')
        except Exception as error:
            print(format_exc())
            raise InternalError(error)