• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python urlobject.URLObject类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: get_pulls

def get_pulls(owner_repo, labels=None, state="open", since=None, org=False):
    url = URLObject("https://api.github.com/repos/{}/issues".format(owner_repo))
    if labels:
        url = url.set_query_param('labels', ",".join(labels))
    if since:
        url = url.set_query_param('since', since.isoformat())
    if state:
        url = url.set_query_param('state', state)
    url = url.set_query_param('sort', 'updated')

    org_fn = None
    if org:
        try:
            with open("people.yaml") as fpeople:
                people = yaml.load(fpeople)
            def_org = "other"
        except IOError:
            people = {}
            def_org = "---"

        def org_fn(issue):
            user_info = people.get(issue["user.login"])
            if not user_info:
                user_info = {"institution": "unsigned"}
            return user_info.get("institution", def_org)

    issues = JPullRequest.from_json(paginated_get(url), org_fn)
    if org:
        issues = sorted(issues, key=operator.itemgetter("org"))

    return issues
开发者ID:jeancfo,项目名称:repo-tools,代码行数:31,代码来源:pulls.py


示例2: process_url

def process_url(url, tracking_id):
    amazon_url = URLObject(url)

    amazon_url = amazon_url.with_scheme('https')
    amazon_url = amazon_url.set_query_param('tag', tracking_id)

    return amazon_url
开发者ID:jachin,项目名称:brocket,代码行数:7,代码来源:__init__.py


示例3: proxied

def proxied(url):
    url = URLObject(url)
    netloc = url.netloc or settings.SERVER_NAME
    cache = get_cache()
    if netloc not in cache:
        return url
    return url.with_netloc(cache[netloc])
开发者ID:paulvisen,项目名称:flask-todo,代码行数:7,代码来源:cdn.py


示例4: get_pulls

def get_pulls(labels=None, state="open", since=None, org=False):
    url = URLObject("https://api.github.com/repos/edx/edx-platform/issues")
    if labels:
        url = url.set_query_param('labels', ",".join(labels))
    if since:
        url = url.set_query_param('since', since.isoformat())
    if state:
        url = url.set_query_param('state', state)
    url = url.set_query_param('sort', 'updated')

    org_fn = None
    if org:
        try:
            with open("mapping.yaml") as fmapping:
                user_mapping = yaml.load(fmapping)
            def_org = "other"
        except IOError:
            user_mapping = {}
            def_org = "---"

        def org_fn(issue):
            return user_mapping.get(issue["user.login"], {}).get("institution", def_org)

    issues = JPullRequest.from_json(paginated_get(url), org_fn)
    if org:
        issues = sorted(issues, key=operator.itemgetter("org"))

    return issues
开发者ID:nedbat,项目名称:jreport,代码行数:28,代码来源:pulls.py


示例5: test_multiple_parses_are_idempotent

 def test_multiple_parses_are_idempotent(self):
     url = u'http://xn-hllo-bpa.com/path%20withspaces?query=es%25capes&foo=bar#frag%28withescapes%29'
     parse1 = URLObject.parse(url)
     self.assertEqual(unicode(url), unicode(parse1))
     parse2 = URLObject.parse(unicode(parse1))
     self.assertEqual(unicode(url), unicode(parse2))
     self.assertEqual(unicode(parse1), unicode(parse2))
开发者ID:davidmoss,项目名称:urlobject,代码行数:7,代码来源:test.py


示例6: as_value

    def as_value(self, data, context):
        # The queries of the current URL, not using sequences here
        # since the order of sorting arguments matter
        url = URLObject(context['request'].get_full_path())
        queries = url.query.dict

        name, orderings = data['with'], data['by']
        query = self.find_query(queries.get(name), orderings, orderings[0])
        url = url.set_query_param(name, query)

        # If this isn't a block tag we probably only want the URL
        if not self._meta.block:
            return url

        label = self.nodelist.render(context)
        if not label.strip():
            raise TemplateSyntaxError("No label was specified")

        parts = []
        for part in query.split(','):
            part = part.strip()
            if part.startswith('-'):
                part = part.lstrip('-')
                # Translators: Used in title of descending sort fields
                text = _("'%(sort_field)s' (desc)")
            else:
                # Translators: Used in title of ascending sort fields
                text = _("'%(sort_field)s' (asc)")
            parts.append(text % {'sort_field': part})
        # Translators: Used for the link/form input title excluding the sort fields
        title = (_('Sort by: %(sort_fields)s') %
                 {'sort_fields': get_text_list(parts, _('and'))})

        extra_context = dict(data, title=title, label=label, url=url, query=query)
        return render_to_string(self.using(data), extra_context, context)
开发者ID:adamchainz,项目名称:django-sorter,代码行数:35,代码来源:sorter_tags.py


示例7: show_pulls

def show_pulls(jrep, labels=None, show_comments=False, state="open", since=None, org=False):
    issues = get_pulls(labels, state, since, org)

    category = None
    for index, issue in enumerate(issues):
        issue.finish_loading()
        if issue.get("org") != category:
            # new category! print category header
            category = issue["org"]
            print("-- {category} ----".format(category=category))

        if 0:
            import pprint
            pprint.pprint(issue.obj)
        print(issue.format(ISSUE_FMT))

        if show_comments:
            comments_url = URLObject(issue['comments_url'])
            comments_url = comments_url.set_query_param("sort", "created")
            comments_url = comments_url.set_query_param("direction", "desc")
            comments = paginated_get(comments_url)
            last_five_comments = reversed(more_itertools.take(5, comments))
            for comment in last_five_comments:
                print(comment.format(COMMENT_FMT))

    # index is now set to the total number of pull requests
    print()
    print("{num} pull requests".format(num=index+1))
开发者ID:nedbat,项目名称:jreport,代码行数:28,代码来源:pulls.py


示例8: process_request

    def process_request(self, request):
        token = request.GET.get(self.param_name)
        if not token:
            return

        redirect_url = URLObject(request.get_full_path())
        redirect_url = redirect_url.del_query_param(self.param_name)

        response = redirect(unicode(redirect_url))
        try:
            token_data = tempus_loads(token, max_age=self.max_age)
            tempus = getattr(request, 'tempus', None)
            if tempus:
                current_tempus = tempus.copy()
                current_tempus.update(token_data)
                request.tempus = current_tempus
            else:
                request.tempus = token_data
        except SignatureExpired:
            value = self.__process_func(request, 'expired_func')
            if value:
                return value
        except BadSignature:
            value = self.__process_func(request, 'unsuccess_func')
            if value:
                return value
        else:
            value = self.__process_func(request, 'success_func')
            if value:
                return value

        add_never_cache_headers(response)
        return response
开发者ID:Mondego,项目名称:pyreco,代码行数:33,代码来源:allPythonContent.py


示例9: jira_paginated_get

def jira_paginated_get(url, obj_name, session=None, start=0, retries=3, **fields):
    """
    Like ``paginated_get``, but uses JIRA's conventions for a paginated API, which
    are different from Github's conventions.
    """
    session = session or requests.Session()
    url = URLObject(url)
    more_results = True
    while more_results:
        result_url = (
            url.set_query_param("startAt", str(start))
               .set_query_params(**fields)
        )
        for _ in xrange(retries):
            try:
                result_resp = session.get(result_url)
                result = result_resp.json()
                break
            except ValueError:
                continue
        if not result_resp.ok:
            raise requests.exceptions.RequestException(result)
        result = result_resp.json()
        for obj in result[obj_name]:
            yield obj
        returned = len(result[obj_name])
        total = result["total"]
        if start + returned < total:
            start += returned
        else:
            more_results = False
开发者ID:dan-f,项目名称:openedx-webhooks,代码行数:31,代码来源:utils.py


示例10: jira_group_members

def jira_group_members(groupname, session=None, start=0, retries=3, debug=False):
    """
    JIRA's group members API is horrible. This makes it easier to use.
    """
    session = session or requests.Session()
    url = URLObject("/rest/api/2/group").set_query_param("groupname", groupname)
    more_results = True
    while more_results:
        end = start + 49  # max 50 users per page
        expand = "users[{start}:{end}]".format(start=start, end=end)
        result_url = url.set_query_param("expand", expand)
        for _ in xrange(retries):
            try:
                if debug:
                    print(result_url, file=sys.stderr)
                result_resp = session.get(result_url)
                result = result_resp.json()
                break
            except ValueError:
                continue
        result_resp.raise_for_status()
        result = result_resp.json()
        if not result:
            break
        users = result["users"]["items"]
        for user in users:
            yield user
        returned = len(users)
        total = result["users"]["size"]
        if start + returned < total:
            start += returned
        else:
            more_results = False
开发者ID:stovar04,项目名称:openedx-webhooks,代码行数:33,代码来源:utils.py


示例11: should_transition

def should_transition(issue):
    """
    Return a boolean indicating if the given issue should be transitioned
    automatically from "Needs Triage" to an open status.
    """
    issue_key = to_unicode(issue["key"])
    issue_status = to_unicode(issue["fields"]["status"]["name"])
    project_key = to_unicode(issue["fields"]["project"]["key"])
    if issue_status != "Needs Triage":
        print(
            "{key} has status {status}, does not need to be processed".format(
                key=issue_key, status=issue_status,
            ),
            file=sys.stderr,
        )
        return False

    # Open source pull requests do not skip Needs Triage.
    # However, if someone creates a subtask on an OSPR issue, that subtasks
    # might skip Needs Triage (it just follows the rest of the logic in this
    # function.)
    is_subtask = issue["fields"]["issuetype"]["subtask"]
    if project_key == "OSPR" and not is_subtask:
        print(
            "{key} is an open source pull request, and does not need to be processed.".format(
                key=issue_key
            ),
            file=sys.stderr,
        )
        return False

    user_url = URLObject(issue["fields"]["creator"]["self"])
    user_url = user_url.set_query_param("expand", "groups")

    user_resp = jira_get(user_url)
    if not user_resp.ok:
        raise requests.exceptions.RequestException(user_resp.text)

    user = user_resp.json()
    user_group_map = {g["name"]: g["self"] for g in user["groups"]["items"]}
    user_groups = set(user_group_map)

    exempt_groups = {
        # group name: set of projects that they can create non-triage issues
        "edx-employees": {"ALL"},
        "clarice": {"MOB"},
        "bnotions": {"MOB"},
        "opencraft": {"SOL"},
    }
    for user_group in user_groups:
        if user_group not in exempt_groups:
            continue
        exempt_projects = exempt_groups[user_group]
        if "ALL" in exempt_projects:
            return True
        if project_key in exempt_projects:
            return True

    return False
开发者ID:sarina,项目名称:openedx-webhooks,代码行数:59,代码来源:jira.py


示例12: test_with_auth_with_two_args_replaces_whole_auth_string_with_username_and_password

    def test_with_auth_with_two_args_replaces_whole_auth_string_with_username_and_password(self):
        # Replaces username-only auth string
        url = URLObject('https://[email protected]/')
        assert url.with_auth('zack', '1234') == 'https://zack:[email protected]/'

        # Replaces username and password.
        url = URLObject('https://alice:[email protected]/')
        assert url.with_auth('zack', '1234') == 'https://zack:[email protected]/'
开发者ID:vmalloc,项目名称:urlobject,代码行数:8,代码来源:urlobject_test.py


示例13: clean_url

    def clean_url(self):
        url = URLObject(self.cleaned_data["url"])

        # URLObject doesn't handle ipv6 very well yet. In the meantime, ...
        if url.netloc.count(":") > 3:
            raise forms.ValidationError(_("Enter a valid URL."))

        URLValidator()(url.without_auth())
        if url.scheme not in ["http", "https"]:
            raise forms.ValidationError(
                _("Invalid URL scheme: '%s'. Only HTTP and HTTPS are " "supported.") % url.scheme
            )

        if url.netloc.hostname in ["localhost", "127.0.0.1", "::1"]:
            raise forms.ValidationError(_("Enter a valid URL."))

        try:
            validate_ipv46_address(url.netloc.hostname)
        except forms.ValidationError:
            pass
        else:
            raise forms.ValidationError(_("Enter a valid URL."))

        existing = self.user.feeds.filter(url=url)
        if self.instance is not None:
            existing = existing.exclude(pk=self.instance.pk)

        if existing.exists():
            raise forms.ValidationError(_("It seems you're already subscribed to this feed."))

        auth = None
        if url.auth != (None, None):
            auth = url.auth

        # Check this is actually a feed
        with user_lock("feed_check", self.user.pk, timeout=30):
            headers = {"User-Agent": USER_AGENT % "checking feed", "Accept": feedparser.ACCEPT_HEADER}
            try:
                response = requests.get(six.text_type(url.without_auth()), headers=headers, timeout=10, auth=auth)
            except Exception:
                if "SENTRY_DSN" in os.environ:
                    client = Client()
                    client.captureException()
                raise forms.ValidationError(_("Error fetching the feed."))
            if response.status_code != 200:
                raise forms.ValidationError(_("Invalid response code from URL: " "HTTP %s.") % response.status_code)
        try:
            parsed = feedparser.parse(response.content)
        except Exception:
            raise forms.ValidationError(_("Error parsing the feed."))
        if not is_feed(parsed):
            raise forms.ValidationError(_("This URL doesn't seem to be a valid feed."))
        self.cleaned_data["title"] = parsed.feed.title
        # Cache this in case update_favicon needs it and it's not in the
        # scheduler data yet.
        if hasattr(parsed.feed, "link"):
            cache.set(u"feed_link:{0}".format(url), parsed.feed.link, 600)
        return url
开发者ID:bors-ltd,项目名称:feedhq,代码行数:58,代码来源:forms.py


示例14: authorized

    def authorized(self):
        if "next" in request.args:
            next_url = request.args["next"]
        elif self.redirect_url:
            next_url = self.redirect_url
        elif self.redirect_to:
            next_url = url_for(self.redirect_to)
        else:
            next_url = "/"

        # check for error in request args
        error = request.args.get("error")
        if error:
            error_desc = request.args.get("error_description")
            error_uri = request.args.get("error_uri")
            log.warning(
                "OAuth 2 authorization error: %s description: %s uri: %s",
                error, error_desc, error_uri,
            )
            oauth_error.send(self,
                error=error, error_description=error_desc, error_uri=error_uri,
            )
            return redirect(next_url)

        state_key = "{bp.name}_oauth_state".format(bp=self)
        self.session._state = flask.session[state_key]
        del flask.session[state_key]

        secure = request.is_secure or request.headers.get("X-Forwarded-Proto", "http") == "https"
        self.session.redirect_uri = url_for(
            ".authorized", next=request.args.get('next'), _external=True,
            _scheme="https" if secure else "http",
        )

        url = URLObject(request.url)
        if request.headers.get("X-Forwarded-Proto", "http") == "https":
            url = url.with_scheme("https")
        try:
            token = self.session.fetch_token(
                self.token_url,
                authorization_response=url,
                client_secret=self.client_secret,
                **self.token_url_params
            )
        except MissingCodeError as e:
            e.args = (
                e.args[0],
                "The redirect request did not contain the expected parameters. Instead I got: {}".format(
                    json.dumps(request.args)
                )
            )
            raise
        results = oauth_authorized.send(self, token=token) or []
        if not any(ret == False for func, ret in results):
            self.token = token
        return redirect(next_url)
开发者ID:Bachmann1234,项目名称:flask-dance,代码行数:56,代码来源:oauth2.py


示例15: urls_are_equal

def urls_are_equal(url1, url2):
    """
    Compare to URLs for equality, ignoring the ordering of non-ordered elements.
    """
    url1 = URLObject(url1)
    url2 = URLObject(url2)
    return (
        url1.without_query() == url2.without_query() and
        url1.query_multi_dict == url2.query_multi_dict
    )
开发者ID:edx,项目名称:pa11ycrawler,代码行数:10,代码来源:test_spider.py


示例16: test_set_query_params_with_multiple_values_adds_or_replaces_the_same_parameter_multiple_times

 def test_set_query_params_with_multiple_values_adds_or_replaces_the_same_parameter_multiple_times(self):
     assert (self.url.set_query_params({'spam': ['bar', 'baz']}) ==
             'https://github.com/zacharyvoase/urlobject?spam=bar&spam=baz#foo')
     assert (self.url.set_query_params({'foo': ['bar', 'baz']}) ==
             'https://github.com/zacharyvoase/urlobject?spam=eggs&foo=bar&foo=baz#foo')
     # Ensure it removes all appearances of an existing name before adding
     # the new ones.
     url = URLObject('https://github.com/zacharyvoase/urlobject?foo=bar&foo=baz#foo')
     assert (url.set_query_params({'foo': ['spam', 'ham']}) ==
             'https://github.com/zacharyvoase/urlobject?foo=spam&foo=ham#foo')
开发者ID:vmalloc,项目名称:urlobject,代码行数:10,代码来源:urlobject_test.py


示例17: test_query_dict_noseq

    def test_query_dict_noseq(self):
        url = URLObject(scheme='http', host='www.google.com')
        url |= ('q', 'query')
        self.assertEqual(url.query_dict(seq=False), {u'q': u'query'})

        self.assertEqual(
            (url | ('q', 'another')).query_dict(seq=False),
            {u'q': u'another'})

        self.assertEqual(
            (url & ('q', 'another')).query_dict(seq=False),
            {u'q': u'another'})
开发者ID:davidmoss,项目名称:urlobject,代码行数:12,代码来源:test.py


示例18: test_query_list

    def test_query_list(self):
        url = URLObject(scheme='http', host='www.google.com')
        url |= ('q', 'query')
        self.assertEqual(url.query_list(), [(u'q', u'query')])

        self.assertEqual(
            (url | ('q', 'another')).query_list(),
            [(u'q', u'another')])

        self.assertEqual(
            (url & ('q', 'another')).query_list(),
            [(u'q', u'query'), (u'q', u'another')])
开发者ID:davidmoss,项目名称:urlobject,代码行数:12,代码来源:test.py


示例19: url_with_page_number

    def url_with_page_number(self, page_number):
        """
        Constructs a url used for getting the next/previous urls
        """
        url = URLObject(self.request.get_full_path())
        url = url.set_query_param('page', str(page_number))

        limit = self.get_limit()
        if limit != self.limit:
            url = url.set_query_param('limit', str(limit))

        return url
开发者ID:cspanring,项目名称:shareabouts-api,代码行数:12,代码来源:mixins.py


示例20: make_jira_blueprint

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,代码行数:53,代码来源:jira.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python query_string.QueryString类代码示例发布时间:2022-05-27
下一篇:
Python urlnorm.norm函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap