当前位置: 首页>>代码示例>>Python>>正文


Python compat.urljoin方法代码示例

本文整理汇总了Python中requests.compat.urljoin方法的典型用法代码示例。如果您正苦于以下问题:Python compat.urljoin方法的具体用法?Python compat.urljoin怎么用?Python compat.urljoin使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests.compat的用法示例。


在下文中一共展示了compat.urljoin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pushover

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def pushover(image, **kwargs):
    assert 'message' in kwargs

    if not 'token' in kwargs:
        kwargs['token'] = os.environ['PUSHOVER_TOKEN']
    if not 'user' in kwargs:
        kwargs['user'] = os.environ['PUSHOVER_USER']

    url = urljoin(PUSHOVER_API, "messages.json")
    headers = { 'User-Agent': 'mqttwarn' }

    if image:
        attachment = { "attachment": ( "image.jpg", image, "image/jpeg" )}
        r = requests.post(url, data=kwargs, files=attachment, headers=headers)
    else:
        r = requests.post(url, data=kwargs, headers=headers)

    if r.json()['status'] != 1:
        raise PushoverError(r.content) 
开发者ID:jpmens,项目名称:mqttwarn,代码行数:21,代码来源:pushover.py

示例2: _request_get

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def _request_get(self, path, params=None, json=True, url=BASE_URL):
        """Perform a HTTP GET request."""
        url = urljoin(url, path)
        headers = self._get_request_headers()

        response = requests.get(url, params=params, headers=headers)
        if response.status_code >= 500:

            backoff = self._initial_backoff
            for _ in range(self._max_retries):
                time.sleep(backoff)
                backoff_response = requests.get(
                    url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT
                )
                if backoff_response.status_code < 500:
                    response = backoff_response
                    break
                backoff *= 2

        response.raise_for_status()
        if json:
            return response.json()
        else:
            return response 
开发者ID:tsifrer,项目名称:python-twitch-client,代码行数:26,代码来源:base.py

示例3: _request_get

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def _request_get(self, path, params=None):
        url = urljoin(BASE_HELIX_URL, path)
        headers = self._get_request_headers()

        self._wait_for_rate_limit_reset()

        response = requests.get(url, params=params, headers=headers)

        remaining = response.headers.get("Ratelimit-Remaining")
        if remaining:
            self._rate_limit_remaining = int(remaining)

        reset = response.headers.get("Ratelimit-Reset")
        if reset:
            self._rate_limit_resets.add(int(reset))

        # If status code is 429, re-run _request_get which will wait for the appropriate time
        # to obey the rate limit
        if response.status_code == codes.TOO_MANY_REQUESTS:
            return self._request_get(path, params=params)

        response.raise_for_status()
        return response.json() 
开发者ID:tsifrer,项目名称:python-twitch-client,代码行数:25,代码来源:base.py

示例4: _request

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def _request(self, path: str, query_params: dict={}):
        """Specialized wrapper around the requests module to request data from Onyphe
        :param path: The URL path after the onyphe FQDN
        :type path: str
        :param query_params: The dictionnary of query parameters that gets appended to the URL
        :type query_params: str
        """
        query_params["apikey"] = self.api_key
        url = urljoin(self.base_url, path)
        response = self._session.get(url=url, data=query_params)

        if response.status_code == 429:
            raise APIRateLimiting(response.text)
        try:
            response_data = response.json()
        except:
            raise APIError("Couldn't parse response JSON")

        if response_data["error"] > 0:
            raise APIError("got error {}: {}".format(
                response_data["error"], response_data["message"]))

        return response_data 
开发者ID:TheHive-Project,项目名称:Cortex-Analyzers,代码行数:25,代码来源:onyphe_api.py

示例5: report

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def report(self, reason=None):
        """Report this object to the moderators.

        :param reason: The user-supplied reason for reporting a comment
            or submission. Default: None (blank reason)
        :returns: The json response from the server.

        """
        url = self.reddit_session.config['report']
        data = {'id': self.fullname}
        if reason:
            data['reason'] = reason
        response = self.reddit_session.request_json(url, data=data)
        # Reported objects are automatically hidden as well
        # pylint: disable=W0212
        self.reddit_session.evict(
            [self.reddit_session.config['user'],
             urljoin(self.reddit_session.user._url, 'hidden')])
        # pylint: enable=W0212
        return response 
开发者ID:tildeclub,项目名称:ttrv,代码行数:22,代码来源:objects.py

示例6: vote

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def vote(self, direction=0):
        """Vote for the given item in the direction specified.

        Note: votes must be cast by humans. That is, API clients proxying a
        human's action one-for-one are OK, but bots deciding how to vote on
        content or amplifying a human's vote are not. See the reddit rules for
        more details on what constitutes vote cheating.

        Source for note: http://www.reddit.com/dev/api#POST_api_vote

        :returns: The json response from the server.

        """
        url = self.reddit_session.config['vote']
        data = {'id': self.fullname,
                'dir': six.text_type(direction)}
        if self.reddit_session.user:
            # pylint: disable=W0212
            urls = [urljoin(self.reddit_session.user._url, 'disliked'),
                    urljoin(self.reddit_session.user._url, 'liked')]
            # pylint: enable=W0212
            self.reddit_session.evict(urls)
        return self.reddit_session.request_json(url, data=data) 
开发者ID:tildeclub,项目名称:ttrv,代码行数:25,代码来源:objects.py

示例7: get_submission

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def get_submission(self, url=None, submission_id=None, comment_limit=0,
                       comment_sort=None, params=None):
        """Return a Submission object for the given url or submission_id.

        :param comment_limit: The desired number of comments to fetch. If <= 0
            fetch the default number for the session's user. If None, fetch the
            maximum possible.
        :param comment_sort: The sort order for retrieved comments. When None
            use the default for the session's user.
        :param params: Dictionary containing extra GET data to put in the url.

        """
        if bool(url) == bool(submission_id):
            raise TypeError('One (and only one) of id or url is required!')
        if submission_id:
            url = urljoin(self.config['comments'], submission_id)
        return objects.Submission.from_url(self, url,
                                           comment_limit=comment_limit,
                                           comment_sort=comment_sort,
                                           params=params) 
开发者ID:tildeclub,项目名称:ttrv,代码行数:22,代码来源:__init__.py

示例8: _get_sorter

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def _get_sorter(subpath='', **defaults):
    """Return function to generate specific subreddit Submission listings."""
    @restrict_access(scope='read')
    def _sorted(self, *args, **kwargs):
        """Return a get_content generator for some RedditContentObject type.

        The additional parameters are passed directly into
        :meth:`.get_content`. Note: the `url` parameter cannot be altered.

        """
        if not kwargs.get('params'):
            kwargs['params'] = {}
        for key, value in six.iteritems(defaults):
            kwargs['params'].setdefault(key, value)
        url = urljoin(self._url, subpath)  # pylint: disable=W0212
        return self.reddit_session.get_content(url, *args, **kwargs)
    return _sorted 
开发者ID:tildeclub,项目名称:ttrv,代码行数:19,代码来源:internal.py

示例9: _raise_redirect_exceptions

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def _raise_redirect_exceptions(response):
    """Return the new url or None if there are no redirects.

    Raise exceptions if appropriate.

    """
    if response.status_code not in [301, 302, 307]:
        return None
    new_url = urljoin(response.url, response.headers['location'])
    if 'reddits/search' in new_url:  # Handle non-existent subreddit
        subreddit = new_url.rsplit('=', 1)[1]
        raise InvalidSubreddit('`{0}` is not a valid subreddit'
                               .format(subreddit))
    elif not RE_REDIRECT.search(response.url):
        raise RedirectException(response.url, new_url)
    return new_url 
开发者ID:tildeclub,项目名称:ttrv,代码行数:18,代码来源:internal.py

示例10: get_query

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def get_query(self, query_id):
        """Fetches information about a query from Redash.

        Args:
            query_id (int, str): Redash query ID

        Returns:
            query (dict): The response from redash, representing a Query model.
        """
        # Get query:
        # https://github.com/getredash/redash/blob/1573e06e710733714d47940cc1cb196b8116f670/redash/handlers/api.py#L74
        url_path = "queries/{}?api_key={}".format(query_id, self.redash_api_key)
        results, response = self._redash._make_request(
            requests.get,
            urljoin(self._redash.API_BASE_URL, url_path)
        )
        return results 
开发者ID:mozilla,项目名称:stmocli,代码行数:19,代码来源:stmo.py

示例11: __graph_url

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def __graph_url(self, params):
        """RRD Graph URL."""
        if 'radio_index' in params:
            start = params['start']
            if not start:
                start = self.default_start_time

            end = params['end']
            if not end:
                end = self.default_end_time

            params['start'] = APGraph.graph_time_format(start)
            params['end'] = APGraph.graph_time_format(end)

            params = APGraph.urlencode(params)
            path = urljoin(self.url, self.path)
            return u'%s?%s' % (path, params)
        return None 
开发者ID:mtoshi,项目名称:airwaveapiclient,代码行数:20,代码来源:ap_graph.py

示例12: __init__

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def __init__(self, version=1, session=None, headers=None, timeout=10, base_url=None, api_key=None,
                 ssl_no_verify=False):
        headers = dict(headers or {}, **{"X-Api-Key": api_key})

        #: Session for the requests
        self.session = session or CertifiSession()
        if ssl_no_verify:
            self.session.verify = False

        self.session.timeout = timeout
        self.session.headers.update(headers or {})

        if not base_url.endswith("/"):
            base_url += "/"

        if not base_url.startswith("http"):
            base_url = "http://%s" % base_url

        if not base_url.endswith("api/"):
            self.api_url = urljoin(base_url, "api/") 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:22,代码来源:drone.py

示例13: request

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def request(self, method, path, data=None, files=None, json=None,
                params=None):
        """Return the json content from the resource at ``path``.

        :param method: The request verb. E.g., get, post, put.
        :param path: The path of the request. This path will be combined with
            the ``oauth_url`` of the Requestor.
        :param data: Dictionary, bytes, or file-like object to send in the body
            of the request.
        :param files: Dictionary, mapping ``filename`` to file-like object.
        :param json: Object to be serialized to JSON in the body of the
            request.
        :param params: The query parameters to send with the request.

        Automatically refreshes the access token if it becomes invalid and a
        refresh token is available. Raises InvalidInvocation in such a case if
        a refresh token is not available.

        """
        params = deepcopy(params) or {}
        params['raw_json'] = 1
        if isinstance(data, dict):
            data = deepcopy(data)
            data['api_type'] = 'json'
            data = sorted(data.items())
        url = urljoin(self._requestor.oauth_url, path)
        return self._request_with_retries(
            data=data, files=files, json=json, method=method,
            params=params, url=url) 
开发者ID:iwannabelikemike,项目名称:plugin.video.sparkle,代码行数:31,代码来源:sessions.py

示例14: _get_source_id

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def _get_source_id(self):
        if self._source_id is None:
            payload = dict(action='open', name=self.name,
                           parameters=self.parameters)
            req = requests.post(urljoin(self.url, '/v1/source'),
                                data=msgpack.packb(payload, **pack_kwargs),
                                **self.headers)
            req.raise_for_status()
            response = msgpack.unpackb(req.content, **unpack_kwargs)
            self._parse_open_response(response) 
开发者ID:intake,项目名称:intake,代码行数:12,代码来源:base.py

示例15: get_url

# 需要导入模块: from requests import compat [as 别名]
# 或者: from requests.compat import urljoin [as 别名]
def get_url(self, path=''):
        # type: (str) -> str
        url = self.urljoin(self.config.api_url, self.base_path, path)
        return url 
开发者ID:cloudblue,项目名称:connect-python-sdk,代码行数:6,代码来源:base.py


注:本文中的requests.compat.urljoin方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。