def request(self,
                method,
                url,
                params=None,
                data=None,
                headers=None,
                auth=None,
                timeout=None,
                allow_redirects=False):
        """Sends an HTTP request

        :param str method: The HTTP method to use
        :param str url: The URL to request
        :param dict params: Query parameters to append to the URL
        :param dict data: Parameters to go in the body of the HTTP request
        :param dict headers: HTTP Headers to send with the request
        :param tuple auth: Basic Auth arguments
        :param float timeout: Socket/Read timeout for the request
        :param boolean allow_redirects: Whether or not to allow redirects

        :return: An http response
        :rtype: A :class:`Response <twilio.rest.http.response.Response>` object

        See the requests documentation for explanation of all these parameters
        """
        http = httplib2.Http(
            timeout=timeout,
            ca_certs=get_cert_file(),
            proxy_info=self.proxy_info,
        )
        http.follow_redirects = allow_redirects

        if auth is not None:
            http.add_credentials(auth[0], auth[1])

        if data is not None:
            udata = {}
            for k, v in iteritems(data):
                key = k.encode('utf-8')
                if isinstance(v, (list, tuple, set)):
                    udata[key] = [self.encode_atom(x) for x in v]
                elif isinstance(v, (integer_types, binary_type, string_types)):
                    udata[key] = self.encode_atom(v)
                else:
                    raise ValueError('data should be an integer, '
                                     'binary, or string, or sequence ')
            data = urlencode(udata, doseq=True)

        if params is not None:
            enc_params = urlencode(params, doseq=True)
            if urlparse(url).query:
                url = '%s&%s' % (url, enc_params)
            else:
                url = '%s?%s' % (url, enc_params)

        resp, content = http.request(url, method, headers=headers, body=data)

        return Response(int(resp.status), content.decode('utf-8'))
Пример #2
0
    def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
                allow_redirects=False):
        """
        Make an HTTP Request with parameters provided.

        :param str method: The HTTP method to use
        :param str url: The URL to request
        :param dict params: Query parameters to append to the URL
        :param dict data: Parameters to go in the body of the HTTP request
        :param dict headers: HTTP Headers to send with the request
        :param tuple auth: Basic Auth arguments
        :param float timeout: Socket/Read timeout for the request
        :param boolean allow_redirects: Whether or not to allow redirects
        See the requests documentation for explanation of all these parameters

        :return: An http response
        :rtype: A :class:`Response <twilio.rest.http.response.Response>` object
        """
        if timeout is not None and timeout <= 0:
            raise ValueError(timeout)

        kwargs = {
            'method': method.upper(),
            'url': url,
            'params': params,
            'data': data,
            'headers': headers,
            'auth': auth,
            'hooks': self.request_hooks
        }

        if params:
            self.logger.info('{method} Request: {url}?{query}'.format(query=urlencode(params), **kwargs))
            self.logger.info('PARAMS: {params}'.format(**kwargs))
        else:
            self.logger.info('{method} Request: {url}'.format(**kwargs))
        if data:
            self.logger.info('PAYLOAD: {data}'.format(**kwargs))

        self.last_response = None
        session = self.session or Session()
        if self.proxy:
            session.proxies = self.proxy
        request = Request(**kwargs)
        self.last_request = TwilioRequest(**kwargs)

        prepped_request = session.prepare_request(request)
        response = session.send(
            prepped_request,
            allow_redirects=allow_redirects,
            timeout=timeout if timeout is not None else self.timeout,
        )

        self.logger.info('{method} Response: {status} {text}'.format(
            method=method, status=response.status_code, text=response.text)
        )

        self.last_response = Response(int(response.status_code), response.text, response.headers)

        return self.last_response
Пример #3
0
    def __str__(self):
        auth = ''
        if self.auth and self.auth != self.ANY:
            auth = '{} '.format(self.auth)

        params = ''
        if self.params and self.params != self.ANY:
            params = '?{}'.format(urlencode(self.params, doseq=True))

        data = ''
        if self.data and self.data != self.ANY:
            if self.method == 'GET':
                data = '\n -G'
            data += '\n{}'.format('\n'.join(' -d "{}={}"'.format(k, v) for k, v in self.data.items()))

        headers = ''
        if self.headers and self.headers != self.ANY:
            headers = '\n{}'.format('\n'.join(' -H "{}: {}"'.format(k, v)
                                              for k, v in self.headers.items()))

        return '{auth}{method} {url}{params}{data}{headers}'.format(
            auth=auth,
            method=self.method,
            url=self.url,
            params=params,
            data=data,
            headers=headers,
        )
Пример #4
0
    def __str__(self):
        auth = ''
        if self.auth and self.auth != self.ANY:
            auth = '{} '.format(self.auth)

        params = ''
        if self.params and self.params != self.ANY:
            params = '?{}'.format(urlencode(self.params, doseq=True))

        data = ''
        if self.data and self.data != self.ANY:
            if self.method == 'GET':
                data = '\n -G'
            data += '\n{}'.format('\n'.join(' -d "{}={}"'.format(k, v)
                                            for k, v in self.data.items()))

        headers = ''
        if self.headers and self.headers != self.ANY:
            headers = '\n{}'.format('\n'.join(
                ' -H "{}: {}"'.format(k, v) for k, v in self.headers.items()))

        return '{auth}{method} {url}{params}{data}{headers}'.format(
            auth=auth,
            method=self.method,
            url=self.url,
            params=params,
            data=data,
            headers=headers,
        )
Пример #5
0
def make_request(method,
                 url,
                 params=None,
                 data=None,
                 headers=None,
                 cookies=None,
                 files=None,
                 auth=None,
                 timeout=None,
                 allow_redirects=False,
                 proxies=None):
    """Sends an HTTP request Returns :class:`Response <models.Response>`

    See the requests documentation for explanation of all these parameters

    Currently proxies, files, and cookies are all ignored
    """
    http = httplib2.Http(timeout=timeout, ca_certs=get_cert_file())
    http.follow_redirects = allow_redirects

    if auth is not None:
        http.add_credentials(auth[0], auth[1])

    if data is not None:
        udata = {}
        for k, v in iteritems(data):
            key = k.encode('utf-8')
            if isinstance(v, (integer_types, binary_type)):
                udata[key] = v
            elif isinstance(v, string_types):
                udata[key] = v.encode('utf-8')
            else:
                raise ValueError('data should be an integer, '
                                 'binary, or string')
        data = urlencode(udata)

    if params is not None:
        enc_params = urlencode(params, doseq=True)
        if urlparse(url).query:
            url = '%s&%s' % (url, enc_params)
        else:
            url = '%s?%s' % (url, enc_params)

    resp, content = http.request(url, method, headers=headers, body=data)

    # Format httplib2 request as requests object
    return Response(resp, content.decode('utf-8'), url)
 def to_payload(self):
     if self.params:
         sorted_params = sorted([(k, v) for k, v in iteritems(self.params)])
         encoded_params = urlencode(sorted_params)
         param_string = '?{}'.format(encoded_params)
     else:
         param_string = ''
     return 'scope:{}:{}{}'.format(self.service, self.privilege, param_string)
Пример #7
0
 def __str__(self):
     if self.params:
         sorted_params = sorted([(k, v) for k, v in iteritems(self.params)])
         encoded_params = urlencode(sorted_params)
         param_string = '?%s' % encoded_params
     else:
         param_string = ''
     return "scope:%s:%s%s" % (self.service, self.privilege, param_string)
Пример #8
0
 def __str__(self):
     if self.params:
         sorted_params = sorted([(k, v) for k, v in iteritems(self.params)])
         encoded_params = urlencode(sorted_params)
         param_string = '?%s' % encoded_params
     else:
         param_string = ''
     return "scope:%s:%s%s" % (self.service, self.privilege, param_string)
    def allow_event_stream(self, **kwargs):
        """
        Allow the user of this token to access their event stream.
        """
        scope = ScopeURI('stream', 'subscribe', {'path': '/2010-04-01/Events'})
        if kwargs:
            scope.add_param('params', urlencode(kwargs, doseq=True))

        self.capabilities["events"] = scope
Пример #10
0
    def allow_event_stream(self, **kwargs):
        """
        Allow the user of this token to access their event stream.
        """
        scope = ScopeURI('stream', 'subscribe', {'path': '/2010-04-01/Events'})
        if kwargs:
            scope.add_param('params', urlencode(kwargs, doseq=True))

        self.capabilities["events"] = scope
Пример #11
0
 def to_payload(self):
     if self.params:
         sorted_params = sorted([(k, v) for k, v in iteritems(self.params)])
         encoded_params = urlencode(sorted_params)
         param_string = '?{}'.format(encoded_params)
     else:
         param_string = ''
     return 'scope:{}:{}{}'.format(self.service, self.privilege,
                                   param_string)
Пример #12
0
    def allow_event_stream(self, **kwargs):
        """Allow the user of this token to access their event stream."""
        scope_params = {
            "path": "/2010-04-01/Events",
        }
        if kwargs:
            scope_params['params'] = urlencode(kwargs, doseq=True)

        self.capabilities["events"] = ScopeURI("stream", "subscribe",
                                               scope_params)
Пример #13
0
    def allow_event_stream(self, **kwargs):
        """Allow the user of this token to access their event stream."""
        scope_params = {
            "path": "/2010-04-01/Events",
        }
        if kwargs:
            scope_params['params'] = urlencode(kwargs, doseq=True)

        self.capabilities["events"] = ScopeURI("stream", "subscribe",
                                               scope_params)
Пример #14
0
    def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
                allow_redirects=False):
        """
        Make an HTTP Request with parameters provided.

        :param str method: The HTTP method to use
        :param str url: The URL to request
        :param dict params: Query parameters to append to the URL
        :param dict data: Parameters to go in the body of the HTTP request
        :param dict headers: HTTP Headers to send with the request
        :param tuple auth: Basic Auth arguments
        :param float timeout: Socket/Read timeout for the request
        :param boolean allow_redirects: Whether or not to allow redirects
        See the requests documentation for explanation of all these parameters

        :return: An http response
        :rtype: A :class:`Response <twilio.rest.http.response.Response>` object
        """

        kwargs = {
            'method': method.upper(),
            'url': url,
            'params': params,
            'data': data,
            'headers': headers,
            'auth': auth,
            'hooks': self.request_hooks
        }

        if params:
            _logger.info('{method} Request: {url}?{query}'.format(query=urlencode(params), **kwargs))
            _logger.info('PARAMS: {params}'.format(**kwargs))
        else:
            _logger.info('{method} Request: {url}'.format(**kwargs))
        if data:
            _logger.info('PAYLOAD: {data}'.format(**kwargs))

        self.last_response = None
        session = self.session or Session()
        request = Request(**kwargs)
        self.last_request = TwilioRequest(**kwargs)

        prepped_request = session.prepare_request(request)
        response = session.send(
            prepped_request,
            allow_redirects=allow_redirects,
            timeout=timeout,
        )

        _logger.info('{method} Response: {status} {text}'.format(method=method, status=response.status_code, text=response.text))

        self.last_response = Response(int(response.status_code), response.text)

        return self.last_response
Пример #15
0
    def allow_client_outgoing(self, application_sid, **kwargs):
        """
        Allow the user of this token to make outgoing connections. Keyword arguments are passed
        to the application.

        :param str application_sid: Application to contact
        """
        scope = ScopeURI('client', 'outgoing', {'appSid': application_sid})
        if kwargs:
            scope.add_param('appParams', urlencode(kwargs, doseq=True))

        self.capabilities['outgoing'] = scope
Пример #16
0
    def allow_client_outgoing(self, application_sid, **kwargs):
        """
        Allow the user of this token to make outgoing connections. Keyword arguments are passed
        to the application.

        :param str application_sid: Application to contact
        """
        scope = ScopeURI('client', 'outgoing', {'appSid': application_sid})
        if kwargs:
            scope.add_param('appParams', urlencode(kwargs, doseq=True))

        self.capabilities['outgoing'] = scope
Пример #17
0
def make_request(method, url, params=None, data=None, headers=None,
                 cookies=None, files=None, auth=None, timeout=None,
                 allow_redirects=False, proxies=None):
    """Sends an HTTP request Returns :class:`Response <models.Response>`

    See the requests documentation for explanation of all these parameters

    Currently proxies, files, and cookies are all ignored
    """
    http = httplib2.Http(timeout=timeout)
    http.follow_redirects = allow_redirects

    if auth is not None:
        http.add_credentials(auth[0], auth[1])

    if data is not None:
        udata = {}
        for k, v in iteritems(data):
            key = k.encode('utf-8')
            if isinstance(v, (integer_types, binary_type)):
                udata[key] = v
            elif isinstance(v, string_types):
                udata[key] = v.encode('utf-8')
            else:
                raise ValueError('data should be an integer, '
                                 'binary, or string')
        data = urlencode(udata)

    if params is not None:
        enc_params = urlencode(params, doseq=True)
        if urlparse(url).query:
            url = '%s&%s' % (url, enc_params)
        else:
            url = '%s?%s' % (url, enc_params)

    resp, content = http.request(url, method, headers=headers, body=data)

    # Format httplib2 request as requests object
    return Response(resp, content.decode('utf-8'), url)
Пример #18
0
    def allow_client_outgoing(self, application_sid, **kwargs):
        """Allow the user of this token to make outgoing connections.

        Keyword arguments are passed to the application.

        :param str application_sid: Application to contact
        """
        scope_params = {
            "appSid": application_sid,
        }
        if kwargs:
            scope_params["appParams"] = urlencode(kwargs, doseq=True)

        self.capabilities["outgoing"] = ScopeURI("client", "outgoing",
                                                 scope_params)
Пример #19
0
    def allow_client_outgoing(self, application_sid, **kwargs):
        """Allow the user of this token to make outgoing connections.

        Keyword arguments are passed to the application.

        :param string application_sid: Application to contact
        """
        scope_params = {
            "appSid": application_sid,
        }
        if kwargs:
            scope_params["appParams"] = urlencode(kwargs, doseq=True)

        self.capabilities["outgoing"] = ScopeURI("client", "outgoing",
                                                 scope_params)
Пример #20
0
 def __str__(self):
     params = urlencode(self.params) if self.params else None
     param_string = "?%s" % params if params else ''
     return "scope:%s:%s%s" % (self.service, self.privilege, param_string)
Пример #21
0
def make_request(method,
                 url,
                 params=None,
                 data=None,
                 headers=None,
                 cookies=None,
                 files=None,
                 auth=None,
                 timeout=None,
                 allow_redirects=False,
                 proxies=None):
    """Sends an HTTP request

    :param str method: The HTTP method to use
    :param str url: The URL to request
    :param dict params: Query parameters to append to the URL
    :param dict data: Parameters to go in the body of the HTTP request
    :param dict headers: HTTP Headers to send with the request
    :param float timeout: Socket/Read timeout for the request

    :return: An http response
    :rtype: A :class:`Response <models.Response>` object

    See the requests documentation for explanation of all these parameters

    Currently proxies, files, and cookies are all ignored
    """
    http = httplib2.Http(
        timeout=timeout,
        ca_certs=get_cert_file(),
        proxy_info=Connection.proxy_info(),
    )
    http.follow_redirects = allow_redirects

    if auth is not None:
        http.add_credentials(auth[0], auth[1])

    def encode_atom(atom):
        if isinstance(atom, (integer_types, binary_type)):
            return atom
        elif isinstance(atom, string_types):
            return atom.encode('utf-8')
        else:
            raise ValueError('list elements should be an integer, '
                             'binary, or string')

    if data is not None:
        udata = {}
        for k, v in iteritems(data):
            key = k.encode('utf-8')
            if isinstance(v, (list, tuple, set)):
                udata[key] = [encode_atom(x) for x in v]
            elif isinstance(v, (integer_types, binary_type, string_types)):
                udata[key] = encode_atom(v)
            else:
                raise ValueError('data should be an integer, '
                                 'binary, or string, or sequence ')
        data = urlencode(udata, doseq=True)

    if params is not None:
        enc_params = urlencode(params, doseq=True)
        if urlparse(url).query:
            url = '%s&%s' % (url, enc_params)
        else:
            url = '%s?%s' % (url, enc_params)

    resp, content = http.request(url, method, headers=headers, body=data)

    # Format httplib2 request as requests object
    return Response(resp, content.decode('utf-8'), url)
Пример #22
0
def make_request(method, url, params=None, data=None, headers=None,
                 cookies=None, files=None, auth=None, timeout=None,
                 allow_redirects=False, proxies=None):
    """Sends an HTTP request

    :param str method: The HTTP method to use
    :param str url: The URL to request
    :param dict params: Query parameters to append to the URL
    :param dict data: Parameters to go in the body of the HTTP request
    :param dict headers: HTTP Headers to send with the request
    :param float timeout: Socket/Read timeout for the request

    :return: An http response
    :rtype: A :class:`Response <models.Response>` object

    See the requests documentation for explanation of all these parameters

    Currently proxies, files, and cookies are all ignored
    """
    http = httplib2.Http(
        timeout=timeout,
        ca_certs=get_cert_file(),
        proxy_info=Connection.proxy_info(),
    )
    http.follow_redirects = allow_redirects

    if auth is not None:
        http.add_credentials(auth[0], auth[1])

    def encode_atom(atom):
            if isinstance(atom, (integer_types, binary_type)):
                return atom
            elif isinstance(atom, string_types):
                return atom.encode('utf-8')
            else:
                raise ValueError('list elements should be an integer, '
                                 'binary, or string')

    if data is not None:
        udata = {}
        for k, v in iteritems(data):
            key = k.encode('utf-8')
            if isinstance(v, (list, tuple, set)):
                udata[key] = [encode_atom(x) for x in v]
            elif isinstance(v, (integer_types, binary_type, string_types)):
                udata[key] = encode_atom(v)
            else:
                raise ValueError('data should be an integer, '
                                 'binary, or string, or sequence ')
        data = urlencode(udata, doseq=True)

    if params is not None:
        enc_params = urlencode(params, doseq=True)
        if urlparse(url).query:
            url = '%s&%s' % (url, enc_params)
        else:
            url = '%s?%s' % (url, enc_params)

    resp, content = http.request(url, method, headers=headers, body=data)

    # Format httplib2 request as requests object
    return Response(resp, content.decode('utf-8'), url)
Пример #23
0
 def __str__(self):
     params = urlencode(self.params) if self.params else None
     param_string = "?%s" % params if params else ''
     return "scope:%s:%s%s" % (self.service, self.privilege, param_string)