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


Python parse.quote_plus函数代码示例

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


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

示例1: getMapUrl

def getMapUrl(mapType, width, height, lat, lng, zoom):
    urlbase = "http://maps.google.com/maps/api/staticmap?"
    params = ''
    if len(tweetListBox.curselection()) != 0:
        selected = tweetListBox.curselection()[0]
        if testtwitter.tweets[selected]['coordinates'] is not None:
            tweetCoord = testtwitter.tweets[selected]['coordinates']['coordinates']
            params = "maptype={}&center={},{}&zoom={}&size={}x{}&format=gif&markers=color:red%7C{},{}&markers=color:blue%7Csize:small".format(mapType, lat, lng, zoom, width, height, tweetCoord[1], tweetCoord[0])
        else:
            params = "maptype={}&center={},{}&zoom={}&size={}x{}&format=gif&markers=color:red%7C{}&markers=color:blue%7Csize:small".format(mapType, lat, lng, zoom, width, height, quote_plus(testtwitter.tweets[selected]['user']['location']))

        counter = 0
        for tweet in testtwitter.tweets:
            if counter == selected:
                counter += 1
                continue
            if tweet['coordinates'] is not None:
                tweetCoord = tweet['coordinates']['coordinates']
                params += "%7C{},{}".format(tweetCoord[1], tweetCoord[0])
            else:
                params += "%7C{}".format(quote_plus(tweet['user']['location']))
            counter += 1
    else:
        params = "maptype={}&center={},{}&zoom={}&size={}x{}&format=gif&markers=color:blue%7Csize:small".format(mapType, lat, lng, zoom, width, height)
        for tweet in testtwitter.tweets:
            if tweet['coordinates'] is not None:
                tweetCoord = tweet['coordinates']['coordinates']
                params += "%7C{},{}".format(tweetCoord[1], tweetCoord[0])
            else:
                params += "%7C{}".format(quote_plus(tweet['user']['location']))
    return urlbase + params
开发者ID:jmding0714,项目名称:uiowapythonproj,代码行数:31,代码来源:hw10start.py

示例2: _get_search_content

 def _get_search_content(self, kind, ton, results):
     """Retrieve the web page for a given search.
     kind can be 'tt' (for titles), 'nm' (for names),
     'char' (for characters) or 'co' (for companies).
     ton is the title or the name to search.
     results is the maximum number of results to be retrieved."""
     if isinstance(ton, unicode):
         try:
             ton = ton.encode('utf-8')
         except Exception as e:
             try:
                 ton = ton.encode('iso8859-1')
             except Exception as e:
                 pass
     ##params = 'q=%s&%s=on&mx=%s' % (quote_plus(ton), kind, str(results))
     params = 'q=%s&s=%s&mx=%s' % (quote_plus(ton), kind, str(results))
     if kind == 'ep':
         params = params.replace('s=ep&', 's=tt&ttype=ep&', 1)
     cont = self._retrieve(self.urls['find'] % params)
     #print 'URL:', imdbURL_find % params
     if cont.find('Your search returned more than') == -1 or \
             cont.find("displayed the exact matches") == -1:
         return cont
     # The retrieved page contains no results, because too many
     # titles or names contain the string we're looking for.
     params = 'q=%s&ls=%s&lm=0' % (quote_plus(ton), kind)
     size = 131072 + results * 512
     return self._retrieve(self.urls['find'] % params, size=size)
开发者ID:sbraz,项目名称:imdbpy,代码行数:28,代码来源:__init__.py

示例3: setUp

    def setUp(self):
        self.user = User.objects.create_user('rulz', '[email protected]', '12345')
        self.task = Task.objects.create(
            name='tarea', description='description tarea', owner=self.user
        )

        #oauth2_provider para crear los token al usuario que se loguea
        self.application = Application(
            name="todo",
            user=self.user,
            client_type=Application.CLIENT_PUBLIC,
            authorization_grant_type=Application.GRANT_PASSWORD,
        )
        self.application.save()

        self.token_request_data = {
            'grant_type': 'password',
            'username': 'rulz',
            'password': '12345'
        }

        self.auth_headers = self.get_basic_auth_header(
            urllib.quote_plus(self.application.client_id),
            urllib.quote_plus(self.application.client_secret)
        )

        self.response = self.client.post(reverse('oauth2_provider:token'),
                                         data=self.token_request_data, **self.auth_headers)
        content = json.loads(self.response.content.decode("utf-8"))
        self.headers = {'Authorization': 'Bearer %(token)s' % {'token': content['access_token']}}
开发者ID:rulz,项目名称:TODOList,代码行数:30,代码来源:tests.py

示例4: instance_url

    def instance_url(self):
        extn = quote_plus(self.id)

        if hasattr(self, "customer"):
            customer = self.customer

            base = Customer.class_url()
            owner_extn = quote_plus(customer)
            class_base = "sources"

        elif hasattr(self, "recipient"):
            recipient = self.recipient

            base = Recipient.class_url()
            owner_extn = quote_plus(recipient)
            class_base = "cards"

        elif hasattr(self, "account"):
            account = self.account

            base = Account.class_url()
            owner_extn = quote_plus(account)
            class_base = "external_accounts"

        else:
            raise error.InvalidRequestError(
                "Could not determine whether card_id %s is attached to a customer, " "recipient, or account." % self.id,
                "id",
            )

        return "%s/%s/%s/%s" % (base, owner_extn, class_base, extn)
开发者ID:Downtownapp,项目名称:aiostripe,代码行数:31,代码来源:resource.py

示例5: search

    def search(self, query):
        self.query = query
        params = []
        hparams = {
            'q': self.query,
            'group': self.group,
            'nresults': self.nresults,
            'start': self.start,
            'match':self.match,
            'nocollapse': 'true' if self.nocollapse else 'false',
            'nfo': 'true' if self.nfo else 'false',
            'passwd': 'true' if self.passwd else 'false',
            'complete': self.complete,
            'key': Request.key
        }
        for param in iter(hparams):
            if hparams[param]: 
                params.append('%s=%s' % (
                    quote_plus(str(param)), 
                    quote_plus(str(hparams[param]))))
        url = '%s?%s' % (Request.url, '&'.join(params))

        print(url)
        content = urlopen(url).read().decode('utf-8')

        return Result(json.loads(content))
开发者ID:oracle2b,项目名称:mysterbin-python,代码行数:26,代码来源:mysterbin.py

示例6: get_games_with_system

def get_games_with_system(search, system):
    scraper_sysid = __scrapermap__[system]
    results = []
    try:
        req = request.Request('http://thegamesdb.net/api/GetGamesList.php?name='+parse.quote_plus(search)+'&platform='+parse.quote_plus(scraper_sysid))
        req.add_unredirected_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31')
        f = request.urlopen(req)
        page = f.read().decode('utf-8').replace('\n','')
        if system == "Sega Genesis":
            req = request.Request('http://thegamesdb.net/api/GetGamesList.php?name='+parse.quote_plus(search)+'&platform='+parse.quote_plus('Sega Mega Drive'))
            req.add_unredirected_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31')
            f2 = request.urlopen(req)
            page = page + f2.read().replace("\n", "")
        games = re.findall("<Game><id>(.*?)</id><GameTitle>(.*?)</GameTitle>(.*?)<Platform>(.*?)</Platform></Game>",
                           page)
        for item in games:
            game = {}
            game["id"] = item[0]
            game["title"] = item[1]
            game["system"] = item[3]
            game["order"] = 1
            if game["title"].lower() == search.lower():
                game["order"] += 1
            if game["title"].lower().find(search.lower()) != -1:
                game["order"] += 1
            if game["system"] == scraper_sysid:
                game["system"] = system
                results.append(game)
        results.sort(key=lambda result: result["order"], reverse=True)
        return [SearchResult(result["title"], result["id"]) for result in results]
    except:
        return None
开发者ID:SnowflakePowered,项目名称:snowflake-py,代码行数:32,代码来源:scraper.py

示例7: create_facebook_button

def create_facebook_button(url, quote, hashtags, config):
    return config['snippet_facebook'].format(
        url=url,
        urlq=quote_plus(url),
        quote=quote_plus((quote + format_hashtags(hashtags)).encode('utf-8')),
        icon_facebook=config['icon_facebook']
    )
开发者ID:max-arnold,项目名称:markdown-tweetable,代码行数:7,代码来源:extension.py

示例8: get_pinterets_share_link

    def get_pinterets_share_link(self,
                                 URL: str,
                                 media: str,
                                 description: str="",
                                 **kwargs) -> str:
        """
        Creates Pinterest share (pin) link with the UTM parameters.

        Arguments:
            URL -- Link that you want to share.
            media -- Media URL to pin.
            description (optional) -- Describe your pin.

        Keyword Arguments:
            You can pass query string parameters as keyword arguments.
            Example: utm_source, utm_medium, utm_campaign etc...

        Returns:
            URL -- Pinterest share (pin) link for the URL.
        """

        if "utm_source" not in kwargs:
            kwargs["utm_source"] = "pinterest"

        link = ("http://pinterest.com/pin/create/button/"
                "?media={media}&description={description}&url={URL}?{args}")
        link = link.format(
            URL=quote_plus(URL),
            media=quote_plus(media),
            description=quote_plus(description),
            args=quote_plus(urlencode(kwargs)),
        )

        return link
开发者ID:umutcoskun,项目名称:mirket,代码行数:34,代码来源:__init__.py

示例9: url

 def url(self):
     query = []
     if self.language is not None:
         query.append("l={}".format(quote_plus(self.language)))
     if self.since is not None:
         query.append("since={}".format(quote_plus(self.since)))
     return "https://github.com/trending?" + "&".join(query)
开发者ID:y-matsuwitter,项目名称:django_crawler_sample,代码行数:7,代码来源:models.py

示例10: print_conf

def print_conf(c):
    iss, tag = c.split('][', 2)
    fname= os.path.join('entities', quote_plus(unquote_plus(iss)), quote_plus(unquote_plus(tag)))
    cnf = json.loads(open(fname,'r').read())
    print(">>>", fname)
    print(json.dumps(cnf, sort_keys=True, indent=2,
                     separators=(',', ': ')))
开发者ID:rohe,项目名称:oidctest,代码行数:7,代码来源:asis.py

示例11: main

def main():
    try:
        aws_secret_key = os.environ['AWS_SECRET_ACCESS_KEY']
        aws_access_key = os.environ['AWS_ACCESS_KEY_ID']
    except KeyError:
        print("Please set your AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID environment variables.")
        return 1

    args = parse_args()

    connection = client.connect(args.host, error_trace=True)
    cur = connection.cursor()

    create_table(cur, os.path.join(os.path.dirname(__file__), "..", "schema.sql"))
    alter_table(cur, 0)

    for month in get_month_partitions(args.start, args.end):
        print('Importing Github data for {0} ...'.format(month))
        s3_url = 's3://{0}:{1}@crate.sampledata/github_archive/{2}-*'.format(quote_plus(aws_access_key),
            quote_plus(aws_secret_key), month)
        print('>>> {0}'.format(s3_url))
        cmd = '''COPY github PARTITION (month_partition=?) FROM ? WITH (compression='gzip')'''
        try:
            cur.execute(cmd, (month, s3_url,))
        except Exception as e:
            print("Error while importing {}: {}".format(s3_url, e))
            print(e.error_trace)

    alter_table(cur, 1)
    return 0
开发者ID:aslanbekirov,项目名称:crate-demo,代码行数:30,代码来源:s3tocrate.py

示例12: put

    def put(self, key, value, cache=None, options={}):
        """Query the server to set the key specified to the value specified in
        the specified cache.

        Keyword arguments:
        key -- the name of the key to be set. Required.
        value -- the value to set key to. Must be a string or JSON
                 serialisable. Required.
        cache -- the cache to store the item in. Defaults to None, which uses
                 self.name. If no name is set, raises a ValueError.
        options -- a dict of arguments to send with the request. See
                   http://dev.iron.io/cache/reference/api/#put_item for more
                   information on defaults and possible values.
        """
        if cache is None:
            cache = self.name
        if cache is None:
            raise ValueError("Cache name must be set")

        if not isinstance(value, six.string_types) and not isinstance(value,
                six.integer_types):
            value = json.dumps(value)

        options["body"] = value
        body = json.dumps(options)

        cache = quote_plus(cache)
        key = quote_plus(key)

        result = self.client.put("caches/%s/items/%s" % (cache, key), body,
                {"Content-Type": "application/json"})
        return Item(cache=cache, key=key, value=value)
开发者ID:hellysmile,项目名称:iron_cache_python,代码行数:32,代码来源:iron_cache.py

示例13: make_webenv

def make_webenv(config, rest):
    if args.tag:
        qtag = quote_plus(args.tag)
    else:
        qtag = 'default'

    ent_conf = None
    try:
        ent_conf = rest.construct_config(quote_plus(args.issuer), qtag)
    except Exception as err:
        print('iss:{}, tag:{}'.format(quote_plus(args.issuer), qtag))
        for m in traceback.format_exception(*sys.exc_info()):
            print(m)
        exit()

    setup_logging("%s/rp_%s.log" % (SERVER_LOG_FOLDER, args.port), logger)
    logger.info('construct_app_args')

    _path, app_args = construct_app_args(args, config, oper, func, profiles,
                                         ent_conf)

    # Application arguments
    app_args.update(
        {"msg_factory": oic_message_factory, 'profile_map': PROFILEMAP,
         'profile_handler': ProfileHandler,
         'client_factory': Factory(Client)})

    if args.insecure:
        app_args['client_info']['verify_ssl'] = False

    return app_args
开发者ID:rohe,项目名称:oidctest,代码行数:31,代码来源:op_test_tool.py

示例14: _get_bearer_token

def _get_bearer_token(key, secret):
    """
    OAuth2 function using twitter's "Application Only" auth method.
    With key and secret, make a POST request to get a bearer token that is used in future API calls
    """

    creds = parse.quote_plus(key) + ':' + parse.quote_plus(secret)
    encoded_creds = base64.b64encode(creds.encode('ascii'))

    all_headers = {
        "Authorization": "Basic " + encoded_creds.decode(encoding='UTF-8'),
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "User-Agent": API_USER_AGENT,
    }

    body_content = {
        'grant_type': 'client_credentials'
    }

    resp = requests.post(
        'https://api.twitter.com/oauth2/token',
        data=body_content,
        headers=all_headers
    )

    json = resp.json()

    if json['token_type'] != 'bearer' or 'access_token' not in json:
        raise OAuthError("Did not receive proper bearer token on initial POST")

    return json['access_token']
开发者ID:michaelbutler,项目名称:random-tweet,代码行数:31,代码来源:random_tweet_lib.py

示例15: set_ethernet_if

 def set_ethernet_if(self, cmd_list, if_id,
                     ip_address, descr):
     if_cmd = self.get_interface()
     cmd_list.append(VyattaSetAPICall("interfaces/{0}/{1}/address/{2}"
                                      .format(if_cmd, if_id, quote_plus(ip_address))))
     cmd_list.append(VyattaSetAPICall("interfaces/{0}/{1}/description/{2}"
                                      .format(if_cmd, if_id, quote_plus(descr))))
开发者ID:denismakogon,项目名称:pynfv,代码行数:7,代码来源:processor.py


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