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


Python urllib.urlencode函数代码示例

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


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

示例1: request

    def request(self, operation, parameters={}):
        """
        Sends the request to the Turk server and returns a response object.
        """

        if not self.signature or not self.accesskey:
            raise RuntimeError("Signature or access key missing")

        timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        hmacstr = hmac.new(config.signature, "AWSMechanicalTurkRequester" + operation + timestamp, hashlib.sha1)
        hmacstr = base64.encodestring(hmacstr.digest()).strip()

        logger.info("Request to MTurk: {0}".format(operation))
        for paramk, paramv in parameters.items():
            logger.debug("  {0}: {1}".format(paramk, paramv))

        baseurl = "/?" + urllib.urlencode(
            {
                "Service": "AWSMechanicalTurkRequester",
                "AWSAccessKeyId": config.accesskey,
                "Version": "2008-08-02",
                "Operation": operation,
                "Signature": hmacstr,
                "Timestamp": timestamp,
            }
        )
        url = baseurl + "&" + urllib.urlencode(parameters)
        url = "https://" + self.server + url

        req = urllib2.Request(url=url)
        data = urllib2.urlopen(req)

        response = Response(operation, data)
        return response
开发者ID:weiliu89,项目名称:turkic,代码行数:34,代码来源:api.py

示例2: get_login_url

 def get_login_url(self, next=None):
     if not next:
         next = self.request.full_url()
     if not next.startswith("http://") and not next.startswith("https://"):
         next = urlparse.urljoin(self.request.full_url(), next)
     if self.get_argument("code", None):
         return (
             "http://"
             + self.request.host
             + self.reverse_url("login")
             + "?"
             + urllib.urlencode({"next": next, "code": self.get_argument("code")})
         )
     redirect_uri = (
         "http://" + self.request.host + self.reverse_url("login") + "?" + urllib.urlencode({"next": next})
     )
     if self.get_argument("code", None):
         args["code"] = self.get_argument("code")
     return "https://www.facebook.com/dialog/oauth?" + urllib.urlencode(
         {
             "client_id": options.facebook_app_id,
             "redirect_uri": redirect_uri,
             "scope": "offline_access,publish_actions",
         }
     )
开发者ID:Mondego,项目名称:pyreco,代码行数:25,代码来源:allPythonContent.py

示例3: auth_flickr

def auth_flickr(request):
    from agro.sources import utils
    api, secret, url = 'e22dd4a81125531e047036ed1ab2a9e7', '72a484d250375bdf', ''
    token = ''
    user_name, user_id = '', ''

    frob = request.GET.get('frob', '')

    if frob:
        api_sig = md5.new('%sapi_key%sfrob%smethodflickr.auth.getToken' % (secret, api, frob)).hexdigest()
        params = urllib.urlencode({'api_key':api, 'frob':frob, 'method':'flickr.auth.getToken', 'api_sig':api_sig})
        res = utils.get_remote_data("http://api.flickr.com/services/rest/?" + params)

        if res.get("stat", "") == "fail":
            log.error("flickr retrieve failed.")
            log.error("%s" % res.get("stat"))
            return False

        #token = res.get('auth')
        auth_res = res.getchildren()[0]
        token = auth_res.find('token').text
        user = auth_res.find('user')
        user_name = user.get('username')
        user_id = user.get('nsid')

    else:
        if request.method == 'POST':
            perms = 'read'
            api_sig = md5.new('%sapi_key%sperms%s' % (secret, api, perms)).hexdigest()
            params = urllib.urlencode({'api_key':api, 'perms':perms, 'api_sig':api_sig})
            return HttpResponseRedirect('http://flickr.com/services/auth/?%s' % params)
        else:
            pass

    return render_to_response('flickr_auth.html', {'api':api, 'secret':secret, 'user_name':user_name, 'user_id':user_id, 'token':token,}, context_instance=RequestContext(request))
开发者ID:blturner,项目名称:agro,代码行数:35,代码来源:auth_views.py

示例4: search

 def search(self, **searchparams):
   results = memcache.get(urlencode(searchparams)) # cicabogár, ennek valójában nem itt lenne a helye
   if results is "tutinemezaválasz": #not None:
     return results
   else:
     searchurl = "http://iwiw.hu/search/pages/user/ajaxsearch.jsp?do=AdvancedSearch&page=0&"
     iwiwsearch = urlfetch.fetch(searchurl + urlencode(searchparams), headers={'Cookie': self.logincookie}).content
     leves = BeautifulSoup(iwiwsearch)
     cuccok = []
     for kartya in leves.findAll("div", "cardContainer"):
       nev = kartya.findAll("a")[1].string.strip()
       name = nev.split("[")[0]
       try:
         nick = re.search("\[(?P<nick>.*)\]", nev).group(1)
       except AttributeError:
         nick = ""
       profile_url = kartya.findAll("a")[1]["href"]
       try:
          pic_popup_url = kartya.find("a", "user_image")["onclick"].split("'")[1]
       except KeyError:
         pic_popup_url = ""
       try:
         pic_thumbnail = kartya.find("a", "user_image").img["src"]
       except KeyError:
         pic_thumbnail = ""
       try:
         city = kartya.find("div", "city").string.strip()
       except AttributeError:
         city = ""
       tutu = {"name": name, "nick": nick, "profile_url": profile_url, "pic_popup_url": pic_popup_url, "pic_thumbnail": pic_thumbnail, "city": city}
       cuccok.append(tutu)
     memcache.add(urlencode(searchparams), cuccok)
     return cuccok
开发者ID:gazs,项目名称:Cyrano,代码行数:33,代码来源:iwiw.py

示例5: test_ie_cors_put_delete

    def test_ie_cors_put_delete(self):
        username = "another test"
        email = "mailto:[email protected]"
        password = "test"
        auth = "Basic %s" % base64.b64encode("%s:%s" % (username, password))
        form = {'username':username,'email': email,'password':password,'password2':password}
        response = self.client.post(reverse(views.register),form, X_Experience_API_Version="1.0.0")

        testagent = '{"name":"another test","mbox":"mailto:[email protected]"}'
        sid = "test_ie_cors_put_delete_set_1"
        sparam1 = {"stateId": sid, "activityId": self.activityId, "agent": testagent}
        path = '%s?%s' % (self.url, urllib.urlencode({"method":"PUT"}))
        
        content = {"test":"test_ie_cors_put_delete","obj":{"actor":"another test"}}
        param = "stateId=%s&activityId=%s&agent=%s&content=%s&Content-Type=application/x-www-form-urlencoded&Authorization=%s&X-Experience-API-Version=1.0.0" % (sid, self.activityId, testagent, content, auth)
        put1 = self.client.post(path, param, content_type='application/x-www-form-urlencoded')
 
        self.assertEqual(put1.status_code, 204)
        self.assertEqual(put1.content, '')
        
        r = self.client.get(self.url, {"stateId": sid, "activityId": self.activityId, "agent": testagent}, X_Experience_API_Version="1.0.0", Authorization=auth)
        self.assertEqual(r.status_code, 200)
        import ast
        c = ast.literal_eval(r.content)

        self.assertEqual(c['test'], content['test'])
        self.assertEqual(r['etag'], '"%s"' % hashlib.sha1('%s' % content).hexdigest())
 
        dparam = "agent=%s&activityId=%s&Authorization=%s&Content-Type=application/x-www-form-urlencoded&X-Experience-API-Version=1.0.0" % (testagent,self.activityId,auth)
        path = '%s?%s' % (self.url, urllib.urlencode({"method":"DELETE"}))
        f_r = self.client.post(path, dparam, content_type='application/x-www-form-urlencoded')
        self.assertEqual(f_r.status_code, 204)
开发者ID:Lindy21,项目名称:CSE498-LRS,代码行数:32,代码来源:ActivityStateTests.py

示例6: _insert_links

def _insert_links(data_dict, limit, offset):
    '''Adds link to the next/prev part (same limit, offset=offset+limit)
    and the resource page.'''
    data_dict['_links'] = {}

    # get the url from the request
    urlstring = toolkit.request.environ['CKAN_CURRENT_URL']

    # change the offset in the url
    parsed = list(urlparse.urlparse(urlstring))
    query = urllib2.unquote(parsed[4])

    arguments = dict(urlparse.parse_qsl(query))
    arguments_start = dict(arguments)
    arguments_prev = dict(arguments)
    arguments_next = dict(arguments)
    if 'offset' in arguments_start:
        arguments_start.pop('offset')
    arguments_next['offset'] = int(offset) + int(limit)
    arguments_prev['offset'] = int(offset) - int(limit)

    parsed_start = parsed[:]
    parsed_prev = parsed[:]
    parsed_next = parsed[:]
    parsed_start[4] = urllib.urlencode(arguments_start)
    parsed_next[4] = urllib.urlencode(arguments_next)
    parsed_prev[4] = urllib.urlencode(arguments_prev)

    # add the links to the data dict
    data_dict['_links']['start'] = urlparse.urlunparse(parsed_start)
    data_dict['_links']['next'] = urlparse.urlunparse(parsed_next)
    if int(offset) - int(limit) > 0:
        data_dict['_links']['prev'] = urlparse.urlunparse(parsed_prev)
开发者ID:Bermuda-io,项目名称:ckan,代码行数:33,代码来源:db.py

示例7: put

    def put(self,
            url,
            payload,
            contentType,
            username=None,
            password=None,
            **kwargs):

        """
        Makes a PUT request to the URL specified and includes the payload
        that gets passed in. The content type header gets set to the
        specified content type.
        """

        headers = {}
        if kwargs:
            if 'headers' in kwargs:
                headers = kwargs['headers']
                del kwargs['headers']
                self.logger.debug('Headers passed in:' + headers)
            if url.find('?') >= 0:
                url = url + '&' + urlencode(kwargs)
            else:
                url = url + '?' + urlencode(kwargs)

        self.logger.debug('About to do a PUT on:' + url)

        h = httplib2.Http()
        h.add_credentials(username, password)
        headers['User-Agent'] = self.user_agent
        if contentType is not None:
            headers['Content-Type'] = contentType
        return h.request(url, body=payload, method='PUT', headers=headers)
开发者ID:Contenteco,项目名称:nuxeo,代码行数:33,代码来源:net.py

示例8: netflix_request

    def netflix_request(self, path, callback, access_token=None,
                           post_args=None, **args):
        args['output'] = 'json'
        overridepost = False
        if(args.get('override') == 'POST'):
            args.pop('override')
            overridepost = True
            post_args = args
            args = {}
        # Add the OAuth resource request signature if we have credentials
        url = 'http://api.netflix.com' + path
        if access_token:
            #args['output'] = 'json'
            all_args = {}
            all_args.update(args)
            all_args.update(post_args or {})
            method = 'POST' if post_args is not None else 'GET'
            oauth = self._oauth_request_parameters(
                url, access_token, all_args, method=method)
            args.update(oauth)

        if args:
            url += '?' + urllib.urlencode(args)
        try:
            if post_args is not None:
                response = urlfetch.fetch(url, method='POST',
                    payload=urllib.urlencode(post_args), deadline=10)
            else:
                response = urlfetch.fetch(url, deadline=10)
        except urlfetch.DownloadError, e:
            logging.exception(e)
            response = None
开发者ID:dsims,项目名称:fongae,代码行数:32,代码来源:netflix.py

示例9: post

    def post(self):
        fontdata = self.request.POST.get('font', None)

        # Need to use isinstance as cgi.FieldStorage always evaluates to False.
        # See http://bugs.python.org/issue19097
        if not isinstance(fontdata, cgi.FieldStorage):
            self.redirect('/font_conversion.html?' +  urllib.urlencode(
                {'err_msg': 'Please select a font'}))
            return

        #TODO(bstell) make this work correctly.
        font_type = 'woff'
        name = os.path.splitext(os.path.basename(fontdata.filename))[0]

        try:
            font = TTFont(fontdata.file)
        except:
            self.redirect('/font_conversion.html?' +  urllib.urlencode(
                {'err_msg': 'failed to parse font'}))
            return

        self.response.headers['Content-Type'] = 'application/font-woff'
        self.response.headers['Content-Disposition'] = \
            'attachment; filename={0}.{1}'.format(name, font_type)
        font.flavor = font_type
        output = StringIO.StringIO()
        font.save(output)
        self.response.out.write(output.getvalue())
开发者ID:ahmet-celik,项目名称:fontuley,代码行数:28,代码来源:font_conversion.py

示例10: post

 def post(self, params):
     print 'create user', params['email']
     try:
         conn = httplib.HTTPSConnection("www.virustotal.com")
         conn.request(method='POST', url='/en/account/signup/',
                      body=urllib.urlencode(params), headers=self.headers)
         response = conn.getresponse()
         HTML=response.read()
         error=re.search('<ul\s+?class="errorlist"><li>(?P<errorlist>.+?)</li></ul>',HTML)
         if error:
             error1=error.group("errorlist")
             print error1
         else:
             print "creat Scucess:",params['email']
             self.db_sql(params)
         conn.close()
     except:
         time.sleep(5)
         conn = httplib.HTTPSConnection("www.virustotal.com")
         conn.request(method='POST', url='/en/account/signup/',
                      body=urllib.urlencode(params), headers=self.headers)
         response = conn.getresponse()
         HTML=response.read()
         error=re.search('<ul\s+?class="errorlist"><li>(?P<errorlist>.+?)</li></ul>',HTML)
         if error:
             error1=error.group("errorlist")
             print error1
         else:
             print "creat Scucess:",params['email']
             self.db_sql(params)
         conn.close()
开发者ID:liebesu,项目名称:Virustotal_Crawler,代码行数:31,代码来源:reg_vt.py

示例11: urlread

def urlread(url, get={}, post={}, headers={}, timeout=None):
    req = urllib2.Request(url, urllib.urlencode(get), headers=headers)
    try:
        response = urllib2.urlopen(req, urllib.urlencode(post), timeout).read()
    except:
        response = urllib2.urlopen(req, urllib.urlencode(post)).read()
    return response
开发者ID:kolia1985,项目名称:odash-client,代码行数:7,代码来源:helpers.py

示例12: decorated_function

 def decorated_function(*args, **kwargs):
     try:
         results = f(*args, **kwargs)
         if 'redirect' in request.form:
             params = urllib.urlencode(results)
             return redirect(
                 '%s?%s' % (request.form['redirect'], params),
                 code=303)
         else:
             return jsonify(results=results)
     except AssertionError as ae:
         if 'redirect_error' in request.form:
             params = urllib.urlencode({'error': ae.args[0]})
             return redirect(
                 '%s?%s' % (request.form['redirect_error'], params),
                 code=303)
         else:
             return jsonify(error=ae.args[0]), 400
     except Exception as e:
         if 'redirect_error' in request.form:
             params = urllib.urlencode({'error': str(e)})
             return redirect(
                 '%s?%s' % (request.form['redirect_error'], params),
                 code=303)
         raise e
开发者ID:WilliamMayor,项目名称:api.timandmikaela.co.uk,代码行数:25,代码来源:web.py

示例13: chemical_analyses

def chemical_analyses():
    email = session.get('email', None)
    api_key = session.get('api_key', None)
    api = MetpetAPI(email, api_key).api

    filters = ast.literal_eval(json.dumps(request.args))
    offset = request.args.get('offset', 0)
    filters['offset'] = offset

    data = api.chemical_analysis.get(params=filters)
    next, previous, last, total_count = paginate_model('chemical_analyses',
                                                        data, filters)
    chemical_analyses = data.data['objects']

    first_page_filters = filters
    del first_page_filters['offset']

    if filters:
        first_page_url = url_for('chemical_analyses') + '?' + urlencode(first_page_filters)
    else:
        first_page_url = url_for('chemical_analyses') + urlencode(first_page_filters)

    return render_template('chemical_analyses.html',
                            chemical_analyses=chemical_analyses,
                            next_url=next,
                            prev_url=previous,
                            total=total_count,
                            first_page=first_page_url,
                            last_page=last)
开发者ID:adt123,项目名称:metpetdb_interface,代码行数:29,代码来源:app.py

示例14: api_call

 def api_call(self, p):
     for k, v in p.iteritems(): 
         if isinstance(v, list): p[k] = str(v[0])
     
     if p['service'] == "search":
         url = self.API_URL + "/memberSearch/"
     elif p['service'] == "report":
         url = self.API_URL + "/esReport/"
     elif p['service'] == "create":
         url = self.API_URL + "/cohort/create/"
     elif p['service'] == "update":
         url = self.API_URL + "/cohort/update/"
     elif p['service'] == "delete":
         url = self.API_URL + "/cohort/delete/"
     elif p['service'] == "config":
         url = self.API_URL + "/config/"
     else:
         url = self.API_URL + "/memberSearch/"
     
     del p['service']
     
     p['ticket']     = self.get_proxy_ticket()
     p['clientName'] = self.CLIENT_NAME
     p['clientId']   = self.CLIENT_ID
     
     self.call = url + "?" + urllib.urlencode(p)
     return url + "?" + urllib.urlencode(p)
开发者ID:zkpt-org,项目名称:tindproc,代码行数:27,代码来源:das.py

示例15: request

    def request(self, path, args=None, post_args=None):
        """Fetches the given path in the Graph API.

        We translate args to a valid query string. If post_args is given,
        we send a POST request to the given path with the given arguments.
        """
        if not args: args = {}
        if self.access_token:
            if post_args is not None:
                post_args["access_token"] = self.access_token
            else:
                args["access_token"] = self.access_token
        post_data = None if post_args is None else urllib.urlencode(post_args)

        file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" +
                                  urllib.urlencode(args), post_data)

        try:
            response = json.loads(file.read())
        finally:
            file.close()
        if response.get("error"):
            raise GraphAPIError(response["error"]["type"],
                                response["error"]["message"])
        return response
开发者ID:PaulWagener,项目名称:khan-website,代码行数:25,代码来源:facebook.py


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