예제 #1
0
    def __init__(self, authorizer, service_root, cache=None,
                 timeout=None, proxy_info=None, version=None,
                 base_client_name='', max_retries=Browser.MAX_RETRIES):
        """Root access to a lazr.restful API.

        :param credentials: The credentials used to access the service.
        :param service_root: The URL to the root of the web service.
        :type service_root: string
        """
        if version is not None:
            if service_root[-1] != '/':
                service_root += '/'
            service_root += str(version)
            if service_root[-1] != '/':
                service_root += '/'
        self._root_uri = URI(service_root)

        # Set up data necessary to calculate the User-Agent header.
        self._base_client_name = base_client_name

        # Get the WADL definition.
        self.credentials = authorizer
        self._browser = Browser(
            self, authorizer, cache, timeout, proxy_info, self._user_agent,
            max_retries)
        self._wadl = self._browser.get_wadl_application(self._root_uri)

        # Get the root resource.
        root_resource = self._wadl.get_resource_by_path('')
        bound_root = root_resource.bind(
            self._browser.get(root_resource), 'application/json')
        super(ServiceRoot, self).__init__(None, bound_root)
예제 #2
0
    def __init__(self,
                 authorizer,
                 service_root,
                 cache=None,
                 timeout=None,
                 proxy_info=None,
                 version=None,
                 base_client_name='',
                 max_retries=Browser.MAX_RETRIES):
        """Root access to a lazr.restful API.

        :param credentials: The credentials used to access the service.
        :param service_root: The URL to the root of the web service.
        :type service_root: string
        """
        if version is not None:
            if service_root[-1] != '/':
                service_root += '/'
            service_root += str(version)
            if service_root[-1] != '/':
                service_root += '/'
        self._root_uri = URI(service_root)

        # Set up data necessary to calculate the User-Agent header.
        self._base_client_name = base_client_name

        # Get the WADL definition.
        self.credentials = authorizer
        self._browser = Browser(self, authorizer, cache, timeout, proxy_info,
                                self._user_agent, max_retries)
        self._wadl = self._browser.get_wadl_application(self._root_uri)

        # Get the root resource.
        root_resource = self._wadl.get_resource_by_path('')
        bound_root = root_resource.bind(self._browser.get(root_resource),
                                        'application/json')
        super(ServiceRoot, self).__init__(None, bound_root)
예제 #3
0
class DotProjectBot(object):

    def __init__(self, base_url):
        self.br = Browser()
        self.base_url = base_url
        if not self.base_url.endswith('/'):
            self.base_url += '/'
        logging.basicConfig(level=logging.ERROR)

    def login(self, username, password):
        self.br.open(self.base_url)
        self.br.select_form(name="loginform")
        self.br['username'] = username
        self.br['password'] = password
        response = self.br.submit()

        if 'Login Failed' in response.read():
            raise LoginFailed('username and/or password are incorrect')
        else:
            logging.info("logged in")

    def log_task(self, dp_task_id, date, hours, description):
        url = self.base_url + 'index.php?m=tasks&a=view&task_id=%d&tab=1' % int(dp_task_id)
        response = self.br.open(url)
        if '<td class="error">Task ID is invalid' in response.read():
            raise InvalidTask("The task doesn't exists in dP or you don't have the permission to see it")

        self.br.select_form('editFrm')
        self.br.form.set_all_readonly(False)
        self.br['task_log_date'] = date.strftime('%Y%m%d')
        self.br['task_log_hours'] = str(hours)
        self.br['task_log_description'] = description
        response = self.br.submit()

        if not '<td class="message">Task Log inserted</td>' in response.read():
            raise LogFail('Something seems to be wrong. Please check %s' % url)
        else:
            msg = u"«%s (%s hs)» was logged succesfully" % (description, str(hours))
            logging.info(msg)
예제 #4
0
class ServiceRoot(Resource):
    """Entry point to the service. Subclass this for a service-specific client.

    :ivar credentials: The credentials instance used to access Launchpad.
    """

    # Custom subclasses of Resource to use when
    # instantiating resources of a certain WADL type.
    RESOURCE_TYPE_CLASSES = {'HostedFile': HostedFile,
                             'ScalarValue': ScalarValue}

    def __init__(self, authorizer, service_root, cache=None,
                 timeout=None, proxy_info=None, version=None,
                 base_client_name='', max_retries=Browser.MAX_RETRIES):
        """Root access to a lazr.restful API.

        :param credentials: The credentials used to access the service.
        :param service_root: The URL to the root of the web service.
        :type service_root: string
        """
        if version is not None:
            if service_root[-1] != '/':
                service_root += '/'
            service_root += str(version)
            if service_root[-1] != '/':
                service_root += '/'
        self._root_uri = URI(service_root)

        # Set up data necessary to calculate the User-Agent header.
        self._base_client_name = base_client_name

        # Get the WADL definition.
        self.credentials = authorizer
        self._browser = Browser(
            self, authorizer, cache, timeout, proxy_info, self._user_agent,
            max_retries)
        self._wadl = self._browser.get_wadl_application(self._root_uri)

        # Get the root resource.
        root_resource = self._wadl.get_resource_by_path('')
        bound_root = root_resource.bind(
            self._browser.get(root_resource), 'application/json')
        super(ServiceRoot, self).__init__(None, bound_root)

    @property
    def _user_agent(self):
        """The value for the User-Agent header.

        This will be something like:
        launchpadlib 1.6.1, lazr.restfulclient 1.0.0; application=apport

        That is, a string describing lazr.restfulclient and an
        optional custom client built on top, and parameters containing
        any authorization-specific information that identifies the
        user agent (such as the application name).
        """
        base_portion = "lazr.restfulclient %s" % __version__
        if self._base_client_name != '':
            base_portion = self._base_client_name + ' (' + base_portion + ')'

        message = Message()
        message['User-Agent'] = base_portion
        if self.credentials is not None:
            user_agent_params = self.credentials.user_agent_params
            for key in sorted(user_agent_params):
                value = user_agent_params[key]
                message.set_param(key, value, 'User-Agent')
        return message['User-Agent']

    def httpFactory(self, authorizer, cache, timeout, proxy_info):
        return RestfulHttp(authorizer, cache, timeout, proxy_info)

    def load(self, url):
        """Load a resource given its URL."""
        parsed = urlparse(url)
        if parsed.scheme == '':
            # This is a relative URL. Make it absolute by joining
            # it with the service root resource.
            if url[:1] == '/':
                url = url[1:]
            url = self._root_uri.append(url)
        document = self._browser.get(url)
        try:
            representation = simplejson.loads(unicode(document))
        except ValueError:
            raise ValueError("%s doesn't serve a JSON document." % url)
        type_link = representation.get("resource_type_link")
        if type_link is None:
            raise ValueError("Couldn't determine the resource type of %s."
                             % url)
        resource_type = self._root._wadl.get_resource_type(type_link)
        wadl_resource = WadlResource(self._root._wadl, url, resource_type.tag)
        return self._create_bound_resource(
            self._root, wadl_resource, representation, 'application/json',
            representation_needs_processing=False)
예제 #5
0
class ServiceRoot(Resource):
    """Entry point to the service. Subclass this for a service-specific client.

    :ivar credentials: The credentials instance used to access Launchpad.
    """

    # Custom subclasses of Resource to use when
    # instantiating resources of a certain WADL type.
    RESOURCE_TYPE_CLASSES = {
        'HostedFile': HostedFile,
        'ScalarValue': ScalarValue
    }

    def __init__(self,
                 authorizer,
                 service_root,
                 cache=None,
                 timeout=None,
                 proxy_info=None,
                 version=None,
                 base_client_name='',
                 max_retries=Browser.MAX_RETRIES):
        """Root access to a lazr.restful API.

        :param credentials: The credentials used to access the service.
        :param service_root: The URL to the root of the web service.
        :type service_root: string
        """
        if version is not None:
            if service_root[-1] != '/':
                service_root += '/'
            service_root += str(version)
            if service_root[-1] != '/':
                service_root += '/'
        self._root_uri = URI(service_root)

        # Set up data necessary to calculate the User-Agent header.
        self._base_client_name = base_client_name

        # Get the WADL definition.
        self.credentials = authorizer
        self._browser = Browser(self, authorizer, cache, timeout, proxy_info,
                                self._user_agent, max_retries)
        self._wadl = self._browser.get_wadl_application(self._root_uri)

        # Get the root resource.
        root_resource = self._wadl.get_resource_by_path('')
        bound_root = root_resource.bind(self._browser.get(root_resource),
                                        'application/json')
        super(ServiceRoot, self).__init__(None, bound_root)

    @property
    def _user_agent(self):
        """The value for the User-Agent header.

        This will be something like:
        launchpadlib 1.6.1, lazr.restfulclient 1.0.0; application=apport

        That is, a string describing lazr.restfulclient and an
        optional custom client built on top, and parameters containing
        any authorization-specific information that identifies the
        user agent (such as the application name).
        """
        base_portion = "lazr.restfulclient %s" % __version__
        if self._base_client_name != '':
            base_portion = self._base_client_name + ' (' + base_portion + ')'

        message = Message()
        message['User-Agent'] = base_portion
        if self.credentials is not None:
            user_agent_params = self.credentials.user_agent_params
            for key in sorted(user_agent_params):
                value = user_agent_params[key]
                message.set_param(key, value, 'User-Agent')
        return message['User-Agent']

    def httpFactory(self, authorizer, cache, timeout, proxy_info):
        return RestfulHttp(authorizer, cache, timeout, proxy_info)

    def load(self, url):
        """Load a resource given its URL."""
        parsed = urlparse(url)
        if parsed.scheme == '':
            # This is a relative URL. Make it absolute by joining
            # it with the service root resource.
            if url[:1] == '/':
                url = url[1:]
            url = str(self._root_uri.append(url))
        document = self._browser.get(url)
        try:
            representation = simplejson.loads(unicode(document))
        except ValueError:
            raise ValueError("%s doesn't serve a JSON document." % url)
        type_link = representation.get("resource_type_link")
        if type_link is None:
            raise ValueError("Couldn't determine the resource type of %s." %
                             url)
        resource_type = self._root._wadl.get_resource_type(type_link)
        wadl_resource = WadlResource(self._root._wadl, url, resource_type.tag)
        return self._create_bound_resource(
            self._root,
            wadl_resource,
            representation,
            'application/json',
            representation_needs_processing=False)
예제 #6
0
 def __init__(self, base_url):
     self.br = Browser()
     self.base_url = base_url
     if not self.base_url.endswith('/'):
         self.base_url += '/'
     logging.basicConfig(level=logging.ERROR)
예제 #7
0
 def __init__(self, uname, pwd, url=mainrest):
     Browser.__init__(self)
     self.login(uname, pwd, url)