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

Python urllib.splitquery函数代码示例

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

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



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

示例1: __connect

  def __connect(self, verb, url, payload={}):
    headers   = {
        'Date': self.__getRFC822Date(),
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    }
    splitUrl  = urllib.splitquery(url)
    path      = splitUrl[0]
    if splitUrl[1] is not None:
      query   = splitUrl[1]
      fullUrl = '%s/%s.%s?%s' % (self.base, path, self.ext, query)
    else:
      query   = ''
      fullUrl = '%s/%s.%s' % (self.base, path, self.ext)
    verb      = verb.upper()
    http      = httplib2.Http()

    # Building the Authentication
    md5       = hashlib.md5()
    md5.update(self.secretKey)
    secret    = md5.hexdigest()
    fpath     = urllib.splitquery('/' + '/'.join(fullUrl.split('/')[3:]))[0]
    payload   = urllib.urlencode(payload)
    signMe    = '%s\n%s\n%s\n%s\n%s\n%s\n' % (verb,
                                              headers['Date'],
                                              fpath,
                                              query,
                                              payload,
                                              secret
                                             )
    md5      = hashlib.md5()
    md5.update(signMe)
    headers['Cerb-Auth']  = '%s:%s' % (self.accessKey, md5.hexdigest())
    
    # Now we perform the request
    if verb == 'PUT' or verb == 'POST':
      headers['Content-Length'] = str(len(str(payload)))
      response, data = http.request(fullUrl, 
                                    verb, 
                                    headers=headers,
                                    body=payload)    
    else:
      response, data = http.request(fullUrl, 
                                    verb, 
                                    headers=headers)
    
    if DEBUG:
      print '--- REQUEST ---'
      print verb, fullUrl
      print 'HEADERS:'
      for header in headers:
        print '%20s : %s' % (header, headers[header])
      print 'PAYLOAD:\n%s' % payload
      print '\n--- RESPONSE ---'
      print 'HEADERS:'
      for header in response:
        print '%20s : %s' % (header, response[header])
      print 'PAYLOAD:'
      print data
    return json.loads(data)
开发者ID:SteveMcGrath,项目名称:CerbAPI,代码行数:59,代码来源:Cerb7.py


示例2: testQueryStringCreation

  def testQueryStringCreation(self):
    url = TEST_URL 
    page = MapApplicationPage(self.browser, url)
    page.checkTitle(PAGE_TITLE)
    time.sleep(1)

    sharingUrl = page.getSharingUrl()
    qs = urlparse.parse_qs(urllib.splitquery(sharingUrl)[1])
    for field in ['showNoImporta', 'showWhatever', 'showArbitrary',
                  'cartogram', 'showCities']:
      if field in qs:
        self.assertTrue(qs[field][0] == 't')

    for field in ['noImportaIndex', 'whateverIndex', 'arbitraryIndex']:
      if field in qs:
        self.assertTrue(qs[field][0] == '0')

    self.assertTrue(qs['markerLng'][0] == '-100', 'has marker lng')
    self.assertTrue(qs['markerLat'][0] == '40', 'has marker lat')
    self.assertTrue(qs['lat'][0] == '38', 'has lat')
    self.assertTrue(qs['lng'][0] == '-95', 'has lng')
    self.assertTrue(qs['zoom'][0] == '4', 'has zoom')

    page.showAsCartogram(False)
    time.sleep(1)
    self.queryStringCreationHelper(page, 'cartogram', 'f')

    page.showLayerset('noImporta', False)
    self.queryStringCreationHelper(page, 'showNoImporta', 'f');


    page.showLayerset('whatever', False) 
    sharingUrl = page.getSharingUrl()
    qs = urlparse.parse_qs(urllib.splitquery(sharingUrl)[1])
    self.assertTrue(qs['showWhatever'][0] == 'f', 'showWhatever=f not shown')

    page.showCities(False)
    time.sleep(1)
    self.queryStringCreationHelper(page, 'showCities', 'f')

    page.changeLayerToIndex('whatever', 1)
    self.queryStringCreationHelper(page, 'whateverIndex', '1')

    page.changeLayerToIndex('arbitrary', 1)
    self.queryStringCreationHelper(page, 'arbitraryIndex', '1')

    page.changeLayerToIndex('noImporta', 1)
    self.queryStringCreationHelper(page, 'noImportaIndex', '1')

    page.zoomIn()
    time.sleep(1)  # zoom takes a minute to settle
    self.queryStringCreationHelper(page, 'zoom', '5')

    # TODO not quite sure how to change center or marker location

    page.tearDown()
开发者ID:duckysherwood,项目名称:mapzarf,代码行数:56,代码来源:TestQueryString.py


示例3: init

 def init(self,title,appkey):
     self.template_values = {
         'title': "Top Performing Fund",
         'appkey': "8a53f225-ab16-44b1-a239-aefaab198247",
         'body': "Invalid Session",
     }
     self.template_values['title'] = title
     self.template_values['appkey'] = appkey
     self.template_values['host']=urllib.splitquery(self.request.url)[0]
     self.first_time = self.request.get("txtweb-message")
     self.txtweb_mobile = self.request.get("txtweb-mobile")
     self.txtweb_message = self.request.get("txtweb-message")
     self.txtweb_password = self.request.get("txtweb-password")
     if self.first_time:
         self.save(("query", urllib.splitquery(self.request.url)[-1]))
开发者ID:itabhijitb,项目名称:txtweb-framework,代码行数:15,代码来源:txt2web.py


示例4: do_GET

 def do_GET(self):
     log = open("/tmp/log.txt","w")
     log.write("Calling Handler %s\n" % self.path)
     try:
         _, query_args = urllib.splitquery(self.path)
         arguments = dict([ urllib.splitvalue(query_arg) for query_arg in query_args.split('&') ])
         session_id = arguments.get('sessionid')
         log.write("Session id: %s\n" % session_id)
 
         if session_id is None:
             self.send_error(400)
             self.end_headers()
             self.wfile.write("fail: sessionid argument is required")
         else:
             try:
                 log.write("Changing password...\n")
                 change_password(session_id)
                 log.write("Password changed\n")
             except Exception, e:
                 log.write("There was an error %s\n", e)
                 traceback.print_exc(file=log)
                 traceback.print_exc()
                 self.send_error(500)
                 self.end_headers()
                 self.wfile.write("Internal error: %s" % str(e))
             else:
                 log.write("Sending 'ok'...\n")
开发者ID:Kiolali,项目名称:weblabdeusto,代码行数:27,代码来源:launch.py


示例5: document_quote

def document_quote (document):
    """Quote given document."""
    doc, query = urllib.splitquery(document)
    doc = url_quote_part(doc, '/=,')
    if query:
        return "%s?%s" % (doc, query)
    return doc
开发者ID:Zearin,项目名称:linkchecker,代码行数:7,代码来源:url.py


示例6: find_page

    def find_page(self, req):
        """
        """
        _page = None
        page_info = {}
        path, query = urllib.splitquery(req['uri'])
        pn = os.path.basename(path)

        name = None
        if pages_handles.has_key(pn):
            name = pages_handles[pn]

        page_info['pagename'] = pn
        page_info['handler'] = None
        page_info['result'] = None
        page_info['message'] = "find page handler"

        if name:
            print "--" * 8
            print "pagename = ", pn
            cmd = 'import ' + name + ' as dut_page'
            print "==", "exec", cmd
            exec (cmd)
            #print "==done","exec",cmd
            _page = dut_page
            page_info['handler'] = _page
        return _page, page_info
开发者ID:roytest001,项目名称:PythonCode,代码行数:27,代码来源:__init__.py


示例7: _get_host_from_uri

    def _get_host_from_uri (self, uri):
        hostport = None
        host = None
        dnssdhost = None
        (scheme, rest) = urllib.splittype (uri)
        if scheme == 'hp' or scheme == 'hpfax':
            if rest.startswith ("/net/"):
                (rest, ipparam) = urllib.splitquery (rest[5:])
                if ipparam != None and ipparam.startswith("ip="):
                    hostport = ipparam[3:]
                else:
                    if ipparam != None and ipparam.startswith("zc="):
                        dnssdhost = ipparam[3:]
                    else:
                        return None, None
            else:
                return None, None
        elif scheme == 'dnssd' or scheme == 'mdns':
            # The URIs of the CUPS "dnssd" backend do not contain the host
            # name of the printer
            return None, None
        else:
            (hostport, rest) = urllib.splithost (rest)
            if hostport == None:
                return None, None

        if hostport:
            (host, port) = urllib.splitport (hostport)
        return host, dnssdhost
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:29,代码来源:PhysicalDevice.py


示例8: refine_url

def refine_url(url, arg_drop_list = []):
    """Returns a refined url with all the arguments mentioned in arg_drop_list dropped."""
    if len(arg_drop_list) == 0:
        return url
    query = urlparse.urlsplit(url)[3]
    new_query = '&'.join(['='.join(j) for j in filter(lambda x: x[0] not in arg_drop_list, [i.split('=') for i in query.split('&')])])
    return (urllib.splitquery(url)[0] + '?' + new_query.rstrip('&')).rstrip('?')
开发者ID:killman,项目名称:Networking,代码行数:7,代码来源:common.py


示例9: loadSplitPointsFromMeta

def loadSplitPointsFromMeta(metaUri):
    if not metaUri.startswith('meta+'):
        raise ValueError('not a meta table: %r' % metaUri)
    metaUri = metaUri[5:]
    
    import urllib,cgi
    p,q = urllib.splitquery(metaUri)
    q = cgi.parse_qs(q or '')
    tableName = q.get('name',[''])[0]

    if not tableName:
        raise ValueError('meta uri needs table name')

    from util.zero import zeroEncode,zeroDecode
    pred = '%r <= row < %r and column = "location"' % \
        (zeroEncode(tableName, '\x01', ''),
         zeroEncode(tableName, '\x02', ''))

    rows = []
    import pykdi
    for r,c,t,v in pykdi.Table(metaUri).scan(pred):
        n,x,r = zeroDecode(r)
        rows.append(r)

    f = 1.0 / (len(rows) + 1)
    return [((i+1)*f, r) for i,r in enumerate(rows)]
开发者ID:asiasun,项目名称:kdi,代码行数:26,代码来源:splits.py


示例10: process

    def process(self,type):

        content =""
        if type==1:#post方法,接收post参数
            datas = self.rfile.read(int(self.headers['content-length']))
            datas = urllib.unquote(datas).decode("utf-8", 'ignore')#指定编码方式
            datas = transDicts(datas)#将参数转换为字典
            if datas.has_key('data'):
                content = "data:"+datas['data']+"\r\n"

        query = urllib.splitquery(self.path)
        action = query[0]
        queryParams = {}

        if '?' in self.path:
            if query[1]:#接收get参数
                for qp in query[1].split('&'):
                    kv = qp.split('=')
                    queryParams[kv[0]] = urllib.unquote(kv[1]).decode("utf-8", 'ignore')
                    #print "queryParams:" + kv[0]+"==="+ queryParams[kv[0]]
                    #content+= kv[0]+':'+queryParams[kv[0]]+"\r\n"

        content_type,f = page(action,queryParams)
        self.send_response(200)
        self.send_header("Content-type", content_type)
        #self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        shutil.copyfileobj(f,self.wfile)
开发者ID:BigManager,项目名称:py_http,代码行数:28,代码来源:http_server.py


示例11: runAddon

 def runAddon(self, url):
     urlScheme = urlparse.urlparse(url)
     if urlScheme.scheme == 'plugin':             # Plugin diferente
         pluginId, urlArgs = urllib.splitquery(url)
         self.theGlobals['sys'].argv[0] = pluginId
         self.theGlobals['sys'].argv[2] = '?' + (urlArgs or '')
         self.theGlobals['sys'].argv[1] += 1
         self.kodiDirectory = [] 
         actualID = urlScheme.netloc
         addonDir = xbmc.translatePath('special://home/addons/' + actualID)
         if self.addonID != actualID:
             self.addonID = actualID
             self.theGlobals['sys'].modules = newModules(self.theGlobals['sys'].modules)                
             self.sourceCode = self.getCompiledAddonSource(actualID)
         try:
             msg = self.theGlobals['sys'].argv[0] + urllib.unquote(self.theGlobals['sys'].argv[2])
             self.log(msg, xbmc.LOGNONE)
             KodiAddonImporter.install_meta(addonDir, addonRoot, hookId = 'kodi_imports', atype = 'kodi')
             KodiAddonImporter.get_initial_state() 
             exec(self.sourceCode, self.theGlobals)
             KodiAddonImporter.restore_initial_state()
             KodiAddonImporter.remove_meta('kodi_imports')
         except:
             self.logger.exception('')
     else:                                       # Ejecuci�n de media (archivo, etc, etc)
         urlLink, sep, userAgent = url.partition('|')
         self.log('Opening: ' + urlLink, xbmc.LOGNOTICE)
         webbrowser.open(urlLink)
开发者ID:agmontesb,项目名称:kodiaddonide,代码行数:28,代码来源:KodiFrontEnd.py


示例12: _splitsuffix

 def _splitsuffix(self, url):
     'Split the suffix off of a url.'
     garbage, pathpart = urllib.splittype(url)
     garbage, path = urllib.splithost(pathpart or '')
     pathpart, garbage = urllib.splitquery(pathpart or '')
     pathpart, garbage = urllib.splitattr(pathpart or '')
     return os.path.splitext(pathpart)[1]
开发者ID:F3DS,项目名称:f3ds,代码行数:7,代码来源:containers.py


示例13: do_GET

     def do_GET(self):
         if re.match("/images/[bcdWDF][123456789eswnrgw]\.png", self.path):
             self.send_response(200)
             self.send_header('Content-Type', 'image/png')
             self.send_header('Cache-Control', 'max-age=86400, must-revalidate')
             self.end_headers()
             from os import curdir, sep
             filename = curdir + sep + self.path
             print filename
             f = open(curdir + sep + self.path, 'rb')
             self.wfile.write(f.read())
             f.close()
         else:
             self.printCustomTextHTTPResponse(200)
             query_string = urllib.unquote_plus(self.path)
             path, query = urllib.splitquery(query_string)
             print query_string, path, query
             parameters = dict(urllib.splitvalue(v) for v in query.split("&")) if query else {}
             print parameters
 
             if 'sit' in parameters:
                 situation = parameters['sit']
             else:
                 situation = None
             #else:
                 #situation = query_string[1:]
             print "situation:", situation
             page = get_page(situation)
             self.wfile.write('<html>')
             self.wfile.write(page)
             self.wfile.write('</html>')
开发者ID:DrKenHo,项目名称:py-mcr,代码行数:31,代码来源:mahjongserver.py


示例14: __init__

    def __init__(self, soup, parent=False):
        """
        Parse the form attributes and fields from the soup.  Make sure
        to get the action right.  When parent is set, then the parent
        element is used as anchor for the search for form elements.
        """
        self._extra_args = {}
        self.soup = soup

        # Make sure to use base strings, not unicode
        for attr, value in soup.attrMap.iteritems():
            setattr(self, str(attr), str(value))

        # Set right anchor point for harvest
        if parent:
            self.soup = soup.parent

        # Harvest input elements.
        self._args = {}
        for item in self.soup.findAll("input"):
            # Make sure to initialize to '' to avoid None strings to appear
            # during submit
            self._args[str(item.get("name"))] = item.get("value") or ""

        # Harvest url
        self.scheme, self.host, self.action = urlsplit(self.action)
        self.action, args = urllib.splitquery(self.action)
        if args:
            args = args.split("&")
            for arg in args:
                attr, value = urllib.splitvalue(arg)
                self._extra_args[str(attr)] = value or ""
开发者ID:hbrunn,项目名称:bank-payment,代码行数:32,代码来源:urlagent.py


示例15: get_sector_id

    def get_sector_id(self, redirect_uri, client_info):
        """
        Pick the sector id given a number of factors
        :param redirect_uri: The redirect_uri used
        :param client_info: Information provided by the client in the
          client registration
        :return: A sector_id or None
        """

        _redirect_uri = urlparse.unquote(redirect_uri)

        part = urlparse.urlparse(_redirect_uri)
        if part.fragment:
            raise ValueError

        (_base, _query) = urllib.splitquery(_redirect_uri)

        sid = ""
        try:
            if _base in client_info["si_redirects"]:
                sid = client_info["sector_id"]
        except KeyError:
            try:
                uit = client_info["subject_type"]
                if uit == "pairwise":
                    sid = _base
            except KeyError:
                pass

        return sid
开发者ID:wayward710,项目名称:pyoidc,代码行数:30,代码来源:provider.py


示例16: _make_qs_uri_for_list

    def _make_qs_uri_for_list(self, uri, info):
        """
        Add the query string for an access to a list.

        If the 'info' flag is set then the _related query string modifier
        is specified. In all cases, the _id modifier is set.

        @param uri:             The URI to which the necessary query string
                                should be added.
        @param info:            A flag indicating whether the caller wishes to
                                receive related information about referenced
                                resources.

        @return:                A ready-formatted URI, with the required query
                                string attached.

        """
        path, qs = urllib.splitquery(uri)
        qs_list = [ self.id_qs ]
        if info:
            qs_list.append(self.related_qs)
        more_qs = "&".join(qs_list)
        if not qs:
            qs = ""
        else:
            qs += "&"
        qs += more_qs
        uri = "%s?%s" % (path, qs)
        return uri
开发者ID:vCider,项目名称:API,代码行数:29,代码来源:client.py


示例17: get

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        testing_type = cgi.escape(self.request.get('type'))
        self.response.out.write('#testing'+testing_type+'\n')
        ##db
        if testing_type == "db":
            t1 = testdb(name="dbname",value="dbvalue")
            t1.put()
            t2 = testdb(name="dbname2",value="dbvalue2")
            t2.put()
            alltestdb = testdb.all().filter("name =", "dbname2").fetch(10)
            if alltestdb[0].value == "dbvalue2":
                self.response.out.write('+result: db test ok!\n')
                alltestdb[0].value = "dbvalue3"
                alltestdb[0].put()
                key_name = str(alltestdb[0].key())
                self.response.out.write(str(alltestdb[0].key()))
                newinc = db.get(db.Key(key_name))
                newinc.value = "123434"
                newinc.put()

        ##get token //pls remove
        if testing_type == "parse_url":
            query=urllib.splitquery("http://api.t.sina.com.cn/oauth/authorize?oauth_token=b4609686ef4fccbbc447d797b2e0ff36&oauth_callback=http%3A%2F%2Ftwsinabot.appspot.com%2Fcallback%3FUser%3Did1")[1]
            tmp_token = urlparse.parse_qs(query)['oauth_token']
            self.response.out.write("+result:\t"+tmp_token[0])
        

        if testing_type == "Get User Name":
            pass
开发者ID:qzhuyan,项目名称:nanomumu,代码行数:30,代码来源:tbotMain.py


示例18: do_GET

  def do_GET(self):
    """Handle GET request.

    self.path contains path, which should be displayed starting from the
    root of the backup.
    """
    path, query = urllib.splitquery(self.path.decode('utf-8'))
    node = self._find(path, self._root)
    if node is None:
      self.send_response(404)
      self.end_headers()
    else:
      options = (self._renderer.options_from_query(query)
                 if query else {})
      try:
        http_code, http_headers, http_payload = \
            self._renderer.render(node, options)
      except:
        self.send_response(503)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        self.wfile.write(''.join(traceback.format_exception(*sys.exc_info())))
        raise
      self.send_response(http_code)
      for header_name, header_value in http_headers:
        self.send_header(header_name, header_value)
      self.end_headers()
      self.wfile.write(http_payload)
开发者ID:yarcat,项目名称:manent,代码行数:28,代码来源:HTTPServer.py


示例19: createContext

def createContext(metadata, incident_settings, results, sessionKey, payload):
    server_info = getServerInfo(sessionKey)

    context = { }
    context.update({ "job_id" : metadata["job_id"] })
    context.update({ "alert_time" : metadata["alert_time"] })
    context.update({ "owner" : metadata["owner"] })
    context.update({ "name" : metadata["alert"] })
    context.update({ "title" : metadata["title"] })
    context.update({ "alert" : { "impact": metadata["impact"], "urgency": metadata["urgency"], "priority": metadata["priority"], "expires": metadata["ttl"] } })
    context.update({ "app" : metadata["app"] })
    context.update({ "category" : incident_settings['category'] })
    context.update({ "subcategory" : incident_settings['subcategory'] })
    context.update({ "tags" : incident_settings['tags'] })
    context.update({ "results_link" : payload['results_link'] })

    split_results_path = urllib.splitquery(payload['results_link'])[0].split('/')
    view_path = '/'.join(split_results_path[:-1]) + '/'
    view_link = view_path + 'alert?' + urllib.urlencode({'s': metadata['entry'][0]['links'].get('alternate') })
    context.update({ "view_link" : view_link })

    context.update({ "server" : { "version": server_info["version"], "build": server_info["build"], "serverName": server_info["serverName"] } })

    if "fields" in results:
        result_context = { "result" : results["fields"][0] }
        context.update(result_context)
        results_context = { "results" : results["fields"] }
        context.update(results_context)

    return context
开发者ID:simcen,项目名称:alert_manager,代码行数:30,代码来源:alert_manager.py


示例20: do_GET

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hi!</h1></body></html>")
        
        if '?' in self.path:
			query = urllib.splitquery(self.path)
			action = query[0]
 
        if query[1]:#接收get参数
			queryParams = {}
			for qp in query[1].split('&'):
				kv = qp.split('=')
				queryParams[kv[0]] = urllib.unquote(kv[1]).decode("utf-8", 'ignore')
				content+= kv[0]+':'+queryParams[kv[0]]+"\r\n"
 
        #指定返回编码
        enc="UTF-8"
        content = content.encode(enc)
        f = io.BytesIO()
        f.write(content)
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=%s" % enc)
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        shutil.copyfileobj(f,self.wfile)
开发者ID:windpenguin,项目名称:SplinterDemo,代码行数:26,代码来源:http2.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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