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


Python URLObject.relative方法代码示例

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


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

示例1: make_jira_blueprint

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
def make_jira_blueprint(consumer_key, rsa_key, base_url,
                        redirect_url=None, redirect_to=None,
                        login_url=None, authorized_url=None):
    """
    Make a blueprint for authenticating with JIRA using OAuth 1.

    Args:
        consumer_key (str): The consumer key for your Application Link on JIRA
        rsa_key (str or path): The RSA private key for your Application Link
            on JIRA. This can be the contents of the key as a string, or a path
            to the key file on disk.
        base_url (str): The base URL of your JIRA installation. For example,
            for Atlassian's hosted OnDemand JIRA, the base_url would be
            ``https://jira.atlassian.com``
        redirect_url (str): the URL to redirect to after the authentication
            dance is complete
        redirect_to (str): if ``redirect_url`` is not defined, the name of the
            view to redirect to after the authentication dance is complete.
            The actual URL will be determined by :func:`flask.url_for`
        login_url (str, optional): the URL path for the ``login`` view.
            Defaults to ``/jira``
        authorized_url (str, optional): the URL path for the ``authorized`` view.
            Defaults to ``/jira/authorized``.

    :rtype: :class:`~flask_dance.consumer.OAuth1ConsumerBlueprint`
    :returns: A :ref:`blueprint <flask:blueprints>` to attach to your Flask app.
    """
    if os.path.isfile(rsa_key):
        with open(rsa_key) as f:
            rsa_key = f.read()
    base_url = URLObject(base_url)

    jira_bp = OAuth1ConsumerBlueprint("jira", __name__,
        client_key=consumer_key,
        rsa_key=rsa_key,
        signature_method=SIGNATURE_RSA,
        base_url=base_url,
        request_token_url=base_url.relative("plugins/servlet/oauth/request-token"),
        access_token_url=base_url.relative("plugins/servlet/oauth/access-token"),
        authorization_url=base_url.relative("plugins/servlet/oauth/authorize"),
        redirect_url=redirect_url,
        redirect_to=redirect_to,
        login_url=login_url,
        authorized_url=authorized_url,
    )
    jira_bp.session.headers["Content-Type"] = "application/json"

    @jira_bp.before_app_request
    def set_applocal_session():
        ctx = stack.top
        ctx.jira_oauth = jira_bp.session

    return jira_bp
开发者ID:psykzz,项目名称:flask-dance,代码行数:55,代码来源:jira.py

示例2: OAuth1Session

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
class OAuth1Session(BaseOAuth1Session):
    """
    A :class:`requests.Session` subclass that can do some special things:

    * lazy-loads OAuth1 tokens from the backend via the blueprint
    * handles OAuth1 authentication
      (from :class:`requests_oauthlib.OAuth1Session` superclass)
    * has a ``base_url`` property used for relative URL resolution
    """
    def __init__(self, blueprint=None, base_url=None, *args, **kwargs):
        super(OAuth1Session, self).__init__(*args, **kwargs)
        self.blueprint = blueprint
        self.base_url = URLObject(base_url)

    @lazy
    def token(self):
        return self.blueprint.token

    def prepare_request(self, request):
        if self.base_url:
            request.url = self.base_url.relative(request.url)
        return super(OAuth1Session, self).prepare_request(request)

    def request(self, method, url, data=None, headers=None, **kwargs):
        t = self.token
        if t and "oauth_token" in t and "oauth_token_secret" in t:
            # This really, really violates the Law of Demeter, but
            # I don't see a better way to set these parameters. :(
            self.auth.client.resource_owner_key = to_unicode(t["oauth_token"])
            self.auth.client.resource_owner_secret = to_unicode(t["oauth_token_secret"])

        return super(OAuth1Session, self).request(
            method=method, url=url, data=data, headers=headers, **kwargs
        )
开发者ID:pdex,项目名称:flask-dance,代码行数:36,代码来源:requests.py

示例3: OAuth2Session

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
class OAuth2Session(BaseOAuth2Session):
    """
    A :class:`requests.Session` subclass that can do some special things:

    * lazy-loads OAuth2 tokens from the backend via the blueprint
    * handles OAuth2 authentication
      (from :class:`requests_oauthlib.OAuth2Session` superclass)
    * has a ``base_url`` property used for relative URL resolution
    """
    def __init__(self, blueprint=None, base_url=None, *args, **kwargs):
        super(OAuth2Session, self).__init__(*args, **kwargs)
        self.blueprint = blueprint
        self.base_url = URLObject(base_url)
        lazy.invalidate(self, "token")

    @lazy
    def token(self):
        return self.blueprint.token

    def request(self, method, url, data=None, headers=None, **kwargs):
        if self.base_url:
            url = self.base_url.relative(url)

        self._client.token = self.token
        if self.token:
            self._client._populate_attributes(self.token)

        return super(OAuth2Session, self).request(
            method=method, url=url, data=data, headers=headers, **kwargs
        )
开发者ID:pdex,项目名称:flask-dance,代码行数:32,代码来源:requests.py

示例4: OAuth1SessionWithBaseURL

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
class OAuth1SessionWithBaseURL(OAuth1Session):
    def __init__(self, base_url=None, *args, **kwargs):
        super(OAuth1SessionWithBaseURL, self).__init__(*args, **kwargs)
        self.base_url = URLObject(base_url)

    def prepare_request(self, request):
        if self.base_url:
            request.url = self.base_url.relative(request.url)
        return super(OAuth1SessionWithBaseURL, self).prepare_request(request)
开发者ID:psykzz,项目名称:flask-dance,代码行数:11,代码来源:oauth1.py

示例5: OAuth2SessionWithBaseURL

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
class OAuth2SessionWithBaseURL(OAuth2Session):
    def __init__(self, base_url=None, *args, **kwargs):
        super(OAuth2SessionWithBaseURL, self).__init__(*args, **kwargs)
        self.base_url = URLObject(base_url)

    def request(self, method, url, data=None, headers=None, **kwargs):
        if self.base_url:
            url = self.base_url.relative(url)
        return super(OAuth2SessionWithBaseURL, self).request(
            method=method, url=url, data=data, headers=headers, **kwargs
        )
开发者ID:psykzz,项目名称:flask-dance,代码行数:13,代码来源:oauth2.py

示例6: import_api_results

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
    def import_api_results(self, endpoint, model):
        base_url = URLObject(settings.DH_METADATA_URL)
        meta_url = base_url.relative(endpoint)

        response = requests.get(meta_url, verify=not settings.DEBUG)
        if response.ok:
            results = response.json()
            for result in results:
                print(result)
                model_instance, created = model.objects.get_or_create(id=result['id'], defaults=result)
                updated = False
                for field in ['name', 'disabled_on']:
                    if getattr(model_instance, field) != result[field]:
                        setattr(model_instance, field, result[field])
                        updated = True
                if updated:
                    model_instance.save()
开发者ID:UKTradeInvestment,项目名称:export-wins-data,代码行数:19,代码来源:import_and_transform_metadata.py

示例7: URLObjectRelativeTest

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
class URLObjectRelativeTest(unittest.TestCase):

    def setUp(self):
        self.url = URLObject("https://github.com/zacharyvoase/urlobject?spam=eggs#foo")

    def test_relative_with_scheme_returns_the_given_URL(self):
        assert self.url.relative('http://example.com/abc') == 'http://example.com/abc'

    def test_relative_with_netloc_returns_the_given_URL_but_preserves_scheme(self):
        assert self.url.relative('//example.com/abc') == 'https://example.com/abc'

    def test_relative_with_path_replaces_path_and_removes_query_string_and_fragment(self):
        assert self.url.relative('another-project') == 'https://github.com/zacharyvoase/another-project'
        assert self.url.relative('.') == 'https://github.com/zacharyvoase/'
        assert self.url.relative('/dvxhouse/intessa') == 'https://github.com/dvxhouse/intessa'
        assert self.url.relative('/dvxhouse/intessa') == 'https://github.com/dvxhouse/intessa'

    def test_relative_with_empty_string_removes_fragment_but_preserves_query(self):
        # The empty string is treated as a path meaning 'the current location'.
        assert self.url.relative('') == self.url.without_fragment()

    def test_relative_with_query_string_removes_fragment(self):
        assert self.url.relative('?name=value') == self.url.without_fragment().with_query('name=value')

    def test_relative_with_fragment_removes_nothing(self):
        assert self.url.relative('#foobar') == self.url.with_fragment('foobar')

    def test_compound_relative_urls(self):
        assert self.url.relative('//example.com/a/b') == 'https://example.com/a/b'
        assert self.url.relative('//example.com/a/b#bar') == 'https://example.com/a/b#bar'
        assert self.url.relative('//example.com/a/b?c=d#bar') == 'https://example.com/a/b?c=d#bar'
        assert self.url.relative('/a/b?c=d#bar') == 'https://github.com/a/b?c=d#bar'
        assert self.url.relative('?c=d#bar') == 'https://github.com/zacharyvoase/urlobject?c=d#bar'
        assert self.url.relative('#bar') == 'https://github.com/zacharyvoase/urlobject?spam=eggs#bar'
开发者ID:vmalloc,项目名称:urlobject,代码行数:36,代码来源:urlobject_test.py

示例8: make_jira_blueprint

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
def make_jira_blueprint(
        base_url, consumer_key=None, rsa_key=None,
        redirect_url=None, redirect_to=None, login_url=None, authorized_url=None,
        session_class=None, backend=None):
    """
    Make a blueprint for authenticating with JIRA using OAuth 1. This requires
    a consumer key and RSA key for the JIRA appication link. You should either
    pass them to this constructor, or make sure that your Flask application
    config defines them, using the variables JIRA_OAUTH_CONSUMER_KEY and
    JIRA_OAUTH_RSA_KEY.

    Args:
        base_url (str): The base URL of your JIRA installation. For example,
            for Atlassian's hosted Cloud JIRA, the base_url would be
            ``https://jira.atlassian.com``
        consumer_key (str): The consumer key for your Application Link on JIRA
        rsa_key (str or path): The RSA private key for your Application Link
            on JIRA. This can be the contents of the key as a string, or a path
            to the key file on disk.
        redirect_url (str): the URL to redirect to after the authentication
            dance is complete
        redirect_to (str): if ``redirect_url`` is not defined, the name of the
            view to redirect to after the authentication dance is complete.
            The actual URL will be determined by :func:`flask.url_for`
        login_url (str, optional): the URL path for the ``login`` view.
            Defaults to ``/jira``
        authorized_url (str, optional): the URL path for the ``authorized`` view.
            Defaults to ``/jira/authorized``.
        session_class (class, optional): The class to use for creating a
            Requests session. Defaults to
            :class:`~flask_dance.consumer.requests.OAuth1Session`.
        backend: A storage backend class, or an instance of a storage
                backend class, to use for this blueprint. Defaults to
                :class:`~flask_dance.consumer.backend.session.SessionBackend`.

    :rtype: :class:`~flask_dance.consumer.OAuth1ConsumerBlueprint`
    :returns: A :ref:`blueprint <flask:blueprints>` to attach to your Flask app.
    """
    if rsa_key and os.path.isfile(rsa_key):
        with open(rsa_key) as f:
            rsa_key = f.read()
    base_url = URLObject(base_url)

    jira_bp = OAuth1ConsumerBlueprint("jira", __name__,
        client_key=consumer_key,
        rsa_key=rsa_key,
        signature_method=SIGNATURE_RSA,
        base_url=base_url,
        request_token_url=base_url.relative("plugins/servlet/oauth/request-token"),
        access_token_url=base_url.relative("plugins/servlet/oauth/access-token"),
        authorization_url=base_url.relative("plugins/servlet/oauth/authorize"),
        redirect_url=redirect_url,
        redirect_to=redirect_to,
        login_url=login_url,
        authorized_url=authorized_url,
        session_class=session_class,
        backend=backend,
    )
    jira_bp.session.headers["Content-Type"] = "application/json"
    jira_bp.from_config["client_key"] = "JIRA_OAUTH_CONSUMER_KEY"
    jira_bp.from_config["rsa_key"] = "JIRA_OAUTH_RSA_KEY"

    @jira_bp.before_app_request
    def set_applocal_session():
        ctx = stack.top
        ctx.jira_oauth = jira_bp.session

    return jira_bp
开发者ID:Bachmann1234,项目名称:flask-dance,代码行数:70,代码来源:jira.py

示例9: OAuth1Session

# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import relative [as 别名]
class OAuth1Session(BaseOAuth1Session):
    """
    A :class:`requests.Session` subclass that can do some special things:

    * lazy-loads OAuth1 tokens from the storage via the blueprint
    * handles OAuth1 authentication
      (from :class:`requests_oauthlib.OAuth1Session` superclass)
    * has a ``base_url`` property used for relative URL resolution

    Note that this is a session between the consumer (your website) and the
    provider (e.g. Twitter), and *not* a session between a user of your website
    and your website.
    """

    def __init__(self, blueprint=None, base_url=None, *args, **kwargs):
        super(OAuth1Session, self).__init__(*args, **kwargs)
        self.blueprint = blueprint
        self.base_url = URLObject(base_url)

    @cached_property
    def token(self):
        """
        Get and set the values in the OAuth token, structured as a dictionary.
        """
        return self.blueprint.token

    def load_token(self):
        t = self.token
        if t and "oauth_token" in t and "oauth_token_secret" in t:
            # This really, really violates the Law of Demeter, but
            # I don't see a better way to set these parameters. :(
            self.auth.client.resource_owner_key = to_unicode(t["oauth_token"])
            self.auth.client.resource_owner_secret = to_unicode(t["oauth_token_secret"])
            return True
        return False

    @property
    def authorized(self):
        """ This is the property used when you have a statement in your code
        that reads "if <provider>.authorized:", e.g. "if twitter.authorized:".

        The way it works is kind of complicated: this function just tries
        to load the token, and then the 'super()' statement basically just
        tests if the token exists (see BaseOAuth1Session.authorized).

        To load the token, it calls the load_token() function within this class,
        which in turn checks the 'token' property of this class (another
        function), which in turn checks the 'token' property of the blueprint
        (see base.py), which calls 'storage.get()' to actually try to load
        the token from the cache/db (see the 'get()' function in
        storage/sqla.py).
        """
        self.load_token()
        return super(OAuth1Session, self).authorized

    @property
    def authorization_required(self):
        """
        .. versionadded:: 1.3.0

        This is a decorator for a view function. If the current user does not
        have an OAuth token, then they will be redirected to the
        :meth:`~flask_dance.consumer.oauth1.OAuth1ConsumerBlueprint.login`
        view to obtain one.
        """

        def wrapper(func):
            @wraps(func)
            def check_authorization(*args, **kwargs):
                if not self.authorized:
                    endpoint = "{name}.login".format(name=self.blueprint.name)
                    return redirect(url_for(endpoint))
                return func(*args, **kwargs)

            return check_authorization

        return wrapper

    def prepare_request(self, request):
        if self.base_url:
            request.url = self.base_url.relative(request.url)
        return super(OAuth1Session, self).prepare_request(request)

    def request(
        self, method, url, data=None, headers=None, should_load_token=True, **kwargs
    ):
        if should_load_token:
            self.load_token()
        return super(OAuth1Session, self).request(
            method=method, url=url, data=data, headers=headers, **kwargs
        )
开发者ID:singingwolfboy,项目名称:flask-dance,代码行数:93,代码来源:requests.py


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