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


Python urllib.urlquote函数代码示例

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


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


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