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

Python urllib.urlquote函数代码示例

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

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



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

示例1: __new__

    def __new__(
        self, server=None, user=None, passwd=None, db=None, port=1433,
        drv=ODBC_DRIVER, **engine_args
    ):
        """ It establishes a new database connection and returns engine

        Args:
            server (str): IP or Hostname to database
            user (str): Username for database
            passwd (str): Password for database
            db (str): Name of database
            port (int): Connection port
            drv (str): Name of underlying database driver for connection
            **engine_args (mixed): Kwargs to pass to ``create_engine``

        Return:
            sqlalchemy.engine.Engine
        """

        if drv != self.SQLITE:
            params = {
                'usr': urlquote(user),
                'pass': urlquote(passwd),
                'srv': server,
                'drv': drv,
                'db': db,
                'prt': port,
            }
            dsn = 'mssql+pyodbc://{usr}:{pass}@{srv}:{prt}/{db}?driver={drv}'
            return create_engine(dsn.format(**params), **engine_args)

        else:
            return create_engine('%s://' % self.SQLITE, **engine_args)
开发者ID:laslabs,项目名称:Python-Carepoint,代码行数:33,代码来源:db.py


示例2: compute_site_uri

    def compute_site_uri(self, *args, **kwargs):

        request_charset = self.request_charset

        out = self.site_uri + '/' + '/'.join(
            arg.encode(request_charset) for arg in args
            )

        if kwargs:
            out += '?'
            _set = 0
            _l = ''
            for key, value in kwargs.items():
                key = urlquote(key).replace(' ', '+')
                if value is None:
                    value = ''
                if isinstance(value, list):
                    for val in value:
                        if _set: _l = '&'
                        out += '%s%s=%s' % (
                            _l, key,
                            urlquote(val.encode(request_charset)).replace(' ', '+')
                            )
                        _set = 1
                else:
                    if _set: _l = '&'
                    out += '%s%s=%s' % (
                        _l, key, quote(value.encode(request_charset)).replace(' ', '+')
                        )
                    _set = 1

        return out
开发者ID:egilchri,项目名称:tweetapp,代码行数:32,代码来源:root.py


示例3: do_pastebin_json

    def do_pastebin_json(self, s):
        """Upload to pastebin via json interface."""

        url = urljoin(self.config.pastebin_url, '/json/new')
        payload = {
            'code': s,
            'lexer': 'pycon',
            'expiry': self.config.pastebin_expiry
        }

        self.interact.notify(_('Posting data to pastebin...'))
        try:
            response = requests.post(url, data=payload, verify=True)
            response.raise_for_status()
        except requests.exceptions.RequestException as exc:
          self.interact.notify(_('Upload failed: %s') % (str(exc), ))
          return

        self.prev_pastebin_content = s
        data = response.json()

        paste_url_template = Template(self.config.pastebin_show_url)
        paste_id = urlquote(data['paste_id'])
        paste_url = paste_url_template.safe_substitute(paste_id=paste_id)

        removal_url_template = Template(self.config.pastebin_removal_url)
        removal_id = urlquote(data['removal_id'])
        removal_url = removal_url_template.safe_substitute(removal_id=removal_id)

        self.prev_pastebin_url = paste_url
        self.interact.notify(_('Pastebin URL: %s - Removal URL: %s') %
                             (paste_url, removal_url))

        return paste_url
开发者ID:fenhl,项目名称:blython,代码行数:34,代码来源:repl.py


示例4: compute_url_for_host

 def compute_url_for_host(self, host, *args, **kwargs):
     out = self.scheme + '://' + host + '/' + '/'.join(
         arg.encode('utf-8') for arg in args
         )
     if kwargs:
         out += '?'
         _set = 0
         _l = ''
         for key, value in kwargs.items():
             key = urlquote(key).replace(' ', '+')
             if value is None:
                 value = ''
             if isinstance(value, list):
                 for val in value:
                     if _set: _l = '&'
                     out += '%s%s=%s' % (
                         _l, key,
                         urlquote(val.encode('utf-8')).replace(' ', '+')
                         )
                     _set = 1
             else:
                 if _set: _l = '&'
                 out += '%s%s=%s' % (
                     _l, key, urlquote(value.encode('utf-8')).replace(' ', '+')
                     )
                 _set = 1
     return out
开发者ID:tav,项目名称:wikifactory,代码行数:27,代码来源:weblite.py


示例5: prepare_request

    def prepare_request(self,url,token=None,secret='',additional_params={},method='GET'):
        encode=lambda t:urlquote(str(t),'')
        urlquh=lambda t:urlquote(str(t),'~')

        params={'oauth_consumer_key':self.consumer_key,
                'oauth_signature_method':'HMAC-SHA1',
                'oauth_timestamp':str(int(time())),
                'oauth_nonce':''.join(list(choice(seqstr) for i in xrange(64))),
                'oauth_version':'1.0'}

        if token:
            params['oauth_token']=token
        elif self.callback_url:
            params['oauth_callback']=self.callback_url

        params.update(additional_params)
        for k,v in params.iteritems():
            if isinstance(v,unicode):
                params[k]=v.encode('utf8')

        params_str='&'.join([encode(k)+'='+urlquh(v) for k,v in sorted(params.iteritems())])
        params['oauth_signature']=hmac('&'.join([self.consumer_secret,secret]),
                                       '&'.join([method,encode(url),urlquh(params_str)]),
                                       sha1).digest().encode('base64').strip()
        return '&'.join([urlquote_plus(str(k),'~')+'='+urlquote_plus(str(v),'~') for k,v in sorted(params.iteritems())])
开发者ID:multiSnow,项目名称:ptapp,代码行数:25,代码来源:oauth.py


示例6: build_uri

def build_uri(username, password, hostname, port, database_name):
    uri_template = 'mysql+mysqldb://{username}:{password}@{hostname}' \
                   ':{port}/{database_name}?charset=utf8mb4'
    return uri_template.format(username=urlquote(username),
                               password=urlquote(password),
                               hostname=urlquote(hostname),
                               port=port,
                               database_name=urlquote(database_name))
开发者ID:alarmcom,项目名称:sync-engine,代码行数:8,代码来源:ignition.py


示例7: _gen_link

 def _gen_link(self, link):
     if link.startswith("http://"):
         link = "http://{0}".format(urlquote(link[7:]))
     elif link.startswith("https://"):
         link = "http://{0}".format(urlquote(link[8:]))
     else:
         link = "http://{0}".format(urlquote(link))
     return link
开发者ID:mastergreg,项目名称:spyglass-crawlie,代码行数:8,代码来源:crawlie.py


示例8: url_to_cache_name

def url_to_cache_name(label, url):
    tmp = ["gitlab_projects"]
    if label is not None:
        tmp.append(urlquote(label, safe=""))
    if url is not None:
        _, tail = url.split("://", 1)
        tmp.append(urlquote(tail, safe=""))
    return "_".join(tmp)
开发者ID:fkie,项目名称:rosrepo,代码行数:8,代码来源:gitlab.py


示例9: _gen_searchlink

 def _gen_searchlink(self, sid, params):
     link = self._sites[sid]['url']
     if link.startswith("http://"):
         link = "http://{0}".format(urlquote(link[7:].format(*params.split("&")), '/'))
     elif link.startswith("https://"):
         link = "http://{0}".format(urlquote(link[8:].format(*params.split("&")), '/'))
     else:
         link = "http://{0}".format(urlquote(link.format(*params.split("&")), '/'))
     return link
开发者ID:alexmavr,项目名称:spyglass-crawlie,代码行数:9,代码来源:crawlie.py


示例10: get_keypath

 def get_keypath(self, key, userid=None, appid=None):
     if userid is None:
         userid = self.userid
     if appid is None:
         appid = self.audience
     keypath = urljoin(self.root_url,"/app/%s/users/%s/keys/%s")
     keypath %= (urlquote(appid, safe=""),
                 urlquote(userid, safe=""),
                 urlquote(key, safe=""))
     return keypath
开发者ID:rtilder,项目名称:sauropod,代码行数:10,代码来源:test_sauropod.py


示例11: test_mssql_dsn

 def test_mssql_dsn(self, mk):
     Db(
         self.params['srv'],
         self.params['usr'],
         self.params['pass'],
         self.params['db'],
         self.params['prt'],
         self.params['drv'],
     )
     self.params['usr'] = urlquote(self.params['usr'])
     self.params['pass'] = urlquote(self.params['pass'])
     mk.assert_called_once_with(self.dsn.format(**self.params))
开发者ID:laslabs,项目名称:Python-Carepoint,代码行数:12,代码来源:test_db.py


示例12: get_authorization_url

  def get_authorization_url(self):
    """Get Authorization URL."""

    token = self._get_auth_token()

    if self.use_sandbox:
      return ("https://sandbox.evernote.com/OAuth.action?"
            "oauth_token=%s&oauth_callback=%s" % (token,
                                                  urlquote(self.callback_url)))
    else :
      return ("https://www.evernote.com/OAuth.action?"
            "oauth_token=%s&oauth_callback=%s" % (token,
                                                  urlquote(self.callback_url)))
开发者ID:wanasit,项目名称:AppEngine-OAuth-Library,代码行数:13,代码来源:oauth.py


示例13: urlize

def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
    """
    Converts any URLs in text into clickable links.

    Works on http://, https://, www. links and links ending in .org, .net or
    .com. Links can have trailing punctuation (periods, commas, close-parens)
    and leading punctuation (opening parens) and it'll still do the right
    thing.

    If trim_url_limit is not None, the URLs in link text longer than this limit
    will truncated to trim_url_limit-3 characters and appended with an elipsis.

    If nofollow is True, the URLs in link text will get a rel="nofollow"
    attribute.

    If autoescape is True, the link text and URLs will get autoescaped.
    """
    trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
    words = word_split_re.split(unicode(text))
    nofollow_attr = nofollow and ' rel="nofollow"' or ''
    for i, word in enumerate(words):
        match = None
        if '.' in word or '@' in word or ':' in word:
            match = punctuation_re.match(word)
        if match:
            lead, middle, trail = match.groups()
            # Make URL we want to point to.
            url = None
            if middle.startswith('http://') or middle.startswith('https://'):
                url = urlquote(middle, safe='/&=:;#?+*')
            elif middle.startswith('www.') or ('@' not in middle and \
                    middle and middle[0] in string.ascii_letters + string.digits and \
                    (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
                url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
            elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
                url = 'mailto:%s' % middle
                nofollow_attr = ''
            # Make link.
            if url:
                trimmed = trim_url(middle)
                if autoescape:
                    lead, trail = escape(lead), escape(trail)
                    url, trimmed = escape(url), escape(trimmed)
                middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
                words[i] = '%s%s%s' % (lead, middle, trail)
            else:
                if autoescape:
                    words[i] = escape(word)
        elif autoescape:
            words[i] = escape(word)
    return u''.join(words)
开发者ID:JustinTulloss,项目名称:harmonize.fm,代码行数:51,代码来源:html.py


示例14: get_node_url

 def get_node_url(self, nodename=""):
     """Return the url for nodes"""
     url = urlparse.urljoin(
         self.base_server_url(),
         'computer/%s' %
         urlquote(nodename))
     return url
开发者ID:jswager,项目名称:jenkinsapi,代码行数:7,代码来源:jenkins.py


示例15: create_resource

    def create_resource(self, resource, resource_data, resource_type, **kwargs):
        """Creates new resource and creates it's data by provided\
         `feed_id` and `resource_id`."""
        if not isinstance(resource, Resource):
            raise KeyError("'resource' should be an instance of Resource")
        if not isinstance(resource_data, ResourceData) or not resource_data.value:
            raise KeyError(
                "'resource_data' should be ResourceData with 'value' attribute")
        if not isinstance(resource_type, ResourceType):
            raise KeyError("'resource_type' should be an instance of ResourceType")
        if not kwargs or 'feed_id' not in kwargs:
            raise KeyError('Variable "feed_id" id mandatory field!')

        resource_id = urlquote(resource.id, safe='')
        r = self._post_inv_status('entity/f;{}/resource'.format(kwargs['feed_id']),
                                data={"name": resource.name, "id": resource.id,
                                "resourceTypePath": "rt;{}"
                                  .format(resource_type.path.resource_type_id)})
        if r:
            r = self._post_inv_status('entity/f;{}/r;{}/data'
                                    .format(kwargs['feed_id'], resource_id),
                                    data={'role': 'configuration', "value": resource_data.value})
        else:
            # if resource or it's data was not created correctly, delete resource
            self._delete_inv_status('entity/f;{}/r;{}'.format(kwargs['feed_id'], resource_id))
        return r
开发者ID:jteehan,项目名称:mgmtsystem,代码行数:26,代码来源:hawkular.py


示例16: get_authorization_url

  def get_authorization_url(self):
    """Get Authorization URL."""

    token = self._get_auth_token()
    return ("http://www.dropbox.com/0/oauth/authorize?"
            "oauth_token=%s&oauth_callback=%s" % (token,
                                                  urlquote(self.callback_url)))
开发者ID:wiraqutra,项目名称:dajare-cloud-api,代码行数:7,代码来源:oauth.py


示例17: ping_google

def ping_google(url):
    """Ping sitemap to Google"""
    sitemap_url = urlquote(url + "/google-sitemaps")
    g = urlopen('http://www.google.com/webmasters/sitemaps/ping?sitemap='+sitemap_url)
    result = g.read()
    g.close()
    return 0
开发者ID:kroman0,项目名称:products,代码行数:7,代码来源:utils.py


示例18: toggle_temporarily_offline

    def toggle_temporarily_offline(self, message="requested from jenkinsapi"):
        """
        Switches state of connected node (online/offline) and
        set 'temporarilyOffline' property (True/False)
        Calling the same method again will bring node status back.
        :param message: optional string can be used to explain why you
            are taking this node offline
        """
        initial_state = self.is_temporarily_offline()
        url = self.baseurl + \
            "/toggleOffline?offlineMessage=" + urlquote(message)
        try:
            html_result = self.jenkins.requester.get_and_confirm_status(url)
        except PostRequired:
            html_result = self.jenkins.requester.post_and_confirm_status(
                url,
                data={})

        self.poll()
        log.debug(html_result)
        state = self.is_temporarily_offline()
        if initial_state == state:
            raise AssertionError(
                "The node state has not changed: temporarilyOffline = %s" %
                state)
开发者ID:ahs3,项目名称:python-jenkinsapi,代码行数:25,代码来源:node.py


示例19: cmd_google

def cmd_google(word, word_eol, userdata=False):
    """ /GOOGLE Command Handler: userdata is debug."""
    debug = False
    for debugarg in ('-d', '--debug'):
        if debugarg in word:
            word.remove(debugarg)
            debug = True

    try:
        if len(word) < 2:
            print(help_str)
            return None
            
        userquery = '+'.join([urlquote(s) for s in word[1:]])
        site = 'https://www.google.com/search?q=%s' % (userquery)
        if debug:
            print('Opening site: {}'.format(site))
        nonzero = open_site(site, debug=debug)
        if nonzero:
            print('Unable to google.')
        else:
            if debug:
                print('\nGoogled {}'.format(site))
        return None
    except Exception as ex:
        print('Error during that google:\n{}'.format(ex))
        return None
开发者ID:welbornprod,项目名称:hexchat-plugins,代码行数:27,代码来源:xgoogler.py


示例20: setUp

    def setUp(self):
        """Setting up test."""
        self.logd("setUp")
        self.server_url = self.conf_get('main', 'url')
        # XXX here you can setup the credential access like this
        credential_host = self.conf_get('credential', 'host')
        credential_port = self.conf_getInt('credential', 'port')
        self.login, self.password = xmlrpc_get_credential(credential_host,
                                                           credential_port,
                                                           'members')
        #self.login = 'siyavula'
        #self.password = 'local'

        # Set the zope cookie. This is a little evil but avoids having to
        # call the login page.
        morsel = Morsel()
        morsel.key = '__ac'
        morsel.value = morsel.coded_value = urlquote(
            encodestring('%s:%s' % (self.login, self.password)))
        self._browser.cookies = {
            'rhaptos': {
                '/': {
                    '__ac': morsel
                }
            }
        }
开发者ID:Rhaptos,项目名称:cnx-buildout,代码行数:26,代码来源:test_Modulecreation.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python urllib.urlretrieve函数代码示例发布时间:2022-05-27
下一篇:
Python urllib.urlopen函数代码示例发布时间: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