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

Python urllib.request函数代码示例

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

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



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

示例1: create_account

def create_account(strategy, backend, user, response, details, is_new=False, *args, **kwargs):
    if is_new:
        acc = Account.objects.create(user=user)
        acc.verified = True
        acc.save()
        if backend.name == "facebook":
            print(str(response))
            url = "http://graph.facebook.com/{0}/picture".format(response["id"])

            resp = request("GET", url, params={"type": "large"})
            acc.profile_pic.save(str(acc.user.id) + ".jpg", ContentFile(resp.content))
            acc.save()

        elif backend.name == "twitter":
            print(str(response))
            url = response["profile_image_url"]
            url = url.replace("_normal", "")
            resp = request("GET", url, params={})
            acc.profile_pic.save(str(acc.user.id) + ".jpg", ContentFile(resp.content))
            acc.save()

        elif backend.name == "google-oauth2":
            url = response["image"]["url"]
            url = url.replace("?sz=50", "?sz=250")
            resp = request("GET", url, params={})
            acc.profile_pic.save(str(acc.user.id) + ".jpg", ContentFile(resp.content))
            acc.save()
开发者ID:Bibekpandey,项目名称:udghos,代码行数:27,代码来源:pipeline.py


示例2: register

 def register(self, identity: Identity, public_key: PKey):
     title = get_key_fingerprint(public_key)
     data = json.dumps({
         'title': title,
         'key': format_openssh_pubkey(public_key)
     })
     try:
         request(identity, self.LIST_URL, 'POST', data=data.encode())
     except urllib.request.HTTPError as e:
         if e.code != 422:
             raise
         content_type = e.headers.get('Content-Type')
         mimetype, options = parse_options_header(content_type)
         if mimetype != 'application/json':
             raise
         charset = options.get('charset', 'utf-8')
         response = json.loads(e.read().decode(charset))
         for error in response.get('errors', []):
             if not isinstance(error, dict):
                 continue
             elif error.get('field') != 'key':
                 continue
             message = error.get('message', '').strip().lower()
             if message != 'key is already in use':
                 continue
             raise DuplicatePublicKeyError(message)
         raise
开发者ID:kimdwkimdw,项目名称:geofront,代码行数:27,代码来源:github.py


示例3: postPrams

def postPrams(option, url, username, password):
	global parameters

	requestMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='Build your request:' --column='Option' 'Add parameter' 'Send request'`")
	requestMenu = requestMenu.split("\n")
	requestMenu = requestMenu[len(requestMenu) - 1]

	if requestMenu == "Add parameter":
		parameter = addParameter()
		if parameter != "":
			parameter = parameter.split("|")
			name = parameter[0]
			value = parameter[1]
			parameters[name] = value
			postPrams(option, url, username, password)
		else:
			postPrams(option, url, username, password)
	elif requestMenu == "Send request":
		request("POST", url, username, password, parameters)
		if option == "No authentication (plain text)" or option == "Basic authentication (plain text)":
			os.system("zenity --text-info --title='PTTP' --filename='response.txt'")
		else:
			os.system("zenity --text-info --html --title='PTTP' --filename='response.txt'")
		os.remove("response.txt")
		parameters = {}
		menu()
	else:
		menu()
开发者ID:NickGeek,项目名称:pttp,代码行数:28,代码来源:pttp.py


示例4: _ensure_ddoc_exists

    def _ensure_ddoc_exists(self):
        if self._ensured_ddoc_exists:
            return

        try:
            remote_ddoc = request('GET',
                                  url(self.url, '_design', 'hypothesis'),
                                  headers=self.headers)
        except urllib.request.HTTPError as err:
            if err.code != 404:
                raise

            request('PUT',
                    url(self.url, '_design', 'hypothesis'),
                    data=json.dumps(self.ddoc()).encode(),
                    headers=self.headers)
        else:
            local_ddoc = self.ddoc()
            expected_view = local_ddoc['views']['by_key']
            stored_view = remote_ddoc.get('views', {}).get('by_key', {})

            if expected_view != stored_view:
                remote_ddoc.setdefault('views', {})
                remote_ddoc['views']['by_key'] = expected_view
                request('PUT',
                        url(self.url, '_design', 'hypothesis'),
                        data=json.dumps(remote_ddoc).encode(),
                        headers=self.headers)

        self._ensured_ddoc_exists = True
开发者ID:kxepal,项目名称:hypothesis-couchdb,代码行数:30,代码来源:example_db.py


示例5: _callbackConnect

    def _callbackConnect(self, params, error=False, server=None, **kwargs):
        """
        Callback after /version response. Continue execution of query

        :param method: HTTP method
        :param path: Remote path
        :param body: params to send (dictionary or pathlib.Path)
        :param original_context: Original context
        :param callback: callback method to call when the server replies
        """

        if error is not False:
            if self._retry < self.getMaxRetryConnection():
                self._retryConnection(server=server)
                return
            for request, callback in self._query_waiting_connections:
                if callback is not None:
                    self._connectionError(callback)
            return

        if "version" not in params or "local" not in params:
            if self._retry < self.getMaxRetryConnection():
                self._retryConnection(server=server)
                return
            msg = "The remote server {} is not a GNS3 server".format(self.url())
            log.error(msg)
            for request, callback in self._query_waiting_connections:
                if callback is not None:
                    callback({"message": msg}, error=True, server=server)
            self._query_waiting_connections = []
            return

        if params["version"].split("-")[0] != __version__.split("-")[0]:
            msg = "Client version {} is not the same as server (controller) version {}".format(__version__, params["version"])
            # Stable release
            if __version_info__[3] == 0:
                log.error(msg)
                for request, callback in self._query_waiting_connections:
                    if callback is not None:
                        callback({"message": msg}, error=True, server=server)
                return
            # We don't allow different major version to interact even with dev build
            elif parse_version(__version__)[:2] != parse_version(params["version"])[:2]:
                log.error(msg)
                for request, callback in self._query_waiting_connections:
                    if callback is not None:
                        callback({"message": msg}, error=True, server=server)
                return
            log.warning("{}\nUsing different versions may result in unexpected problems. Please upgrade or use at your own risk.".format(msg))

        self._connected = True
        self._retry = 0
        self.connection_connected_signal.emit()
        for request, callback in self._query_waiting_connections:
            if request:
                request()
        self._query_waiting_connections = []
开发者ID:GNS3,项目名称:gns3-gui,代码行数:57,代码来源:http_client.py


示例6: _callbackConnect

    def _callbackConnect(self, params, error=False, server=None, **kwargs):
        """
        Callback after /version response. Continue execution of query

        :param method: HTTP method
        :param path: Remote path
        :param body: params to send (dictionary or pathlib.Path)
        :param original_context: Original context
        :param callback: callback method to call when the server replies
        """

        if error is not False:
            if self._retry < self.MAX_RETRY_CONNECTION:
                self._retryConnection(server=server)
                return
            for request, callback in self._query_waiting_connections:
                if callback is not None:
                    self._connectionError(callback)
            return

        if "version" not in params or "local" not in params:
            if self._retry < self.MAX_RETRY_CONNECTION:
                self._retryConnection(server=server)
                return
            msg = "The remote server {} is not a GNS3 server".format(self.url())
            log.error(msg)
            for request, callback in self._query_waiting_connections:
                if callback is not None:
                    callback({"message": msg}, error=True, server=server)
            self._query_waiting_connections = []
            return

        if params["version"].split("-")[0] != __version__.split("-")[0]:
            msg = "Client version {} differs with server version {}".format(__version__, params["version"])
            log.error(msg)
            # Stable release
            if __version_info__[3] == 0:
                for request, callback in self._query_waiting_connections:
                    if callback is not None:
                        callback({"message": msg}, error=True, server=server)
                return
            # We don't allow different major version to interact even with dev build
            elif parse_version(__version__)[:2] != parse_version(params["version"])[:2]:
                for request, callback in self._query_waiting_connections:
                    if callback is not None:
                        callback({"message": msg}, error=True, server=server)
                return
            log.warning("Use a different client and server version can create bugs. Use it at your own risk.")

        self._connected = True
        self._retry = 0
        self.connection_connected_signal.emit()
        for request, callback in self._query_waiting_connections:
            if request:
                request()
        self._query_waiting_connections = []
开发者ID:maherja,项目名称:gns3-gui,代码行数:56,代码来源:http_client.py


示例7: save

    def save(self, key: str, value: list):
        self._ensure_setup()

        request(
            method='PUT',
            url=url(self.url, str(uuid.uuid4())),
            data=json.dumps({'key': format_key(key),
                             'value': value,
                             'type': 'example'}).encode(),
            headers=self.headers)
开发者ID:kxepal,项目名称:hypothesis-couchdb,代码行数:10,代码来源:example_db.py


示例8: _ensure_db_exists

    def _ensure_db_exists(self):
        if self._ensured_db_exists:
            return

        try:
            request('GET', url(self.url), headers=self.headers)
        except urllib.request.HTTPError as err:
            if err.code != 404:
                raise
            request('PUT', url(self.url), headers=self.headers)

        self._ensured_db_exists = True
开发者ID:kxepal,项目名称:hypothesis-couchdb,代码行数:12,代码来源:example_db.py


示例9: licht_toggle

def licht_toggle(q, wildcards):
    #Prozessverarbeitung
    receivers = json.loads(request("http://zimmer:2525/remote/list")) #JSON request
    found = False
    for id, val in enumerate(receivers):
        if (receivers[val]['title'].lower() == wildcards[0]):
            found = True
            request("http://zimmer:2525/remote/switch?id=" + str(val))


    if (found == False):
        print("Diese Lampe kenne ich nicht")
    else:
        print("Ich habe die gewuenschte Lampe umgeschaltet")
开发者ID:cuskinfor,项目名称:SiriAPI8,代码行数:14,代码来源:my-personal-example.py


示例10: save

def save(links, dirName, img_type, image_links=False):
  for i in range(len(links)):
    img_name = '{}{:03}.{}'.format(dirName, i+1, img_type)
    if not os.path.exists(img_name.replace('.jpg', '.png')) and not os.path.exists(img_name.replace('.png', '.jpg')):
      print('\r  Downloading {0} of {1}'.format(*(i+1, len(links))), end="")
      if image_links:
        img_url = links[i]
      elif 'bato.to' in links[i]:
        img_url = re.search('<div.*?>\\s*<img[^<]*?src=\"([^\"]*?)\"[^>]*?/>\\s*</div>', get_html(links[i]), re.DOTALL|re.MULTILINE).group(1)
      elif 'goodmanga.net' in links[i]:
        img_url = re.search('</div>\\s*<a.*?>\\s*<img[^<]*?src=\"(.*?)\".*?>\\s*</a>', get_html(links[i]), re.DOTALL|re.MULTILINE).group(1)
      else:
        img_url = re.search('<a.*?>\\s*<img[^<]*?src=\"(.*?)\".*?>\\s*</a>', get_html(links[i]), re.DOTALL|re.MULTILINE).group(1)
      for j in range(2):
        for k in range(7):
          try:
            data = request(img_url)
            break
          except:
            if j == 0 and k == 6 and 'bato.to' in img_url:
              if img_url.endswith('png'):
                img_url = re.sub('png$', 'jpg', img_url)
                img_name = '{}{:03}.{}'.format(dirName, i+1, 'jpg')
              else:
                img_url = re.sub('jpg$', 'png', img_url)
                img_name = '{}{:03}.{}'.format(dirName, i+1, 'png')
            if j == 1 and k == 6:
              raise
            pass
          time.sleep(1.7)
      with open(img_name, 'wb') as f:
        f.write(data)
  print()
开发者ID:shaggytwodope,项目名称:Manga,代码行数:33,代码来源:manga.py


示例11: get_page_by_id

def get_page_by_id( page_id ):
  random_page = request( {'action':'query', 'pageids':page_id, 'prop':'revisions', 'rvprop':'content', 'rvlimit':1, 'format':'json', 'grnnamespace':0} )
  data = json.loads(random_page.decode('utf-8'))
  page_id, page_data = data['query']['pages'].popitem()
  title = page_data['title']
  content = page_data['revisions'][0]['*']
  return ( title, page_id, content )
开发者ID:MickaelG,项目名称:wp_scripts,代码行数:7,代码来源:wiki.py


示例12: verify

def verify(name, type, content, package=package, project=project, parent=parent, endpoint=endpoint):
    # send job verify2 to api
    sock = request('verify2', name, type, content, package, project, parent, endpoint)

    # decode result into sane json
    resp = decode(sock.recv())

    while resp['status'] == 'processing':
        # parse results into a number indication prove result
        if 'Proved' in resp['result']['result']:
            result = 0
        elif 'Timeout' in resp['result']['result']:
            result = 1
        elif 'Skipped' in resp['result']['result']:
            result = 2
        else:
            result = 3

        # yield verification with id and result
        yield {'id': resp['result']['id'], 'result': result}

        # decode result into sane json
        resp = decode(sock.recv())

    # make sure job completed
    if resp['status'] != 'complete':
        try:
            raise ResolveCompilerError(resp['errors'][0]['errors'])
        except KeyError:
            raise ResolveAPIError(resp['bugs'][0]['bugs'])
开发者ID:fkmclane,项目名称:vim-resolve,代码行数:30,代码来源:api.py


示例13: login

def login(key, resp):
    success = False
    resp = request(
        config["target"][key]["url_login"],
        config["target"][key]["encoding"],
        config["target"][key]["query_login"].format(
            username=urllib.parse.quote_plus(config["target"][key]["username"]),
            password=urllib.parse.quote_plus(config["target"][key]["password"]),
            pwdmd5=hashlib.md5(config["target"][key]["password"].encode(config["target"][key]["encoding"])).hexdigest(),
            pwdmd5_utf=hashlib.md5(config["target"][key]["password"].encode("utf-8")).hexdigest(),
            formhash=formhash(key, resp),
            smfhash=smfhash(key, resp),
        ),
    )
    if not resp:
        prtmsg("err_login_fail")
        return False
    if config["target"][key].get("regex_login_success"):
        if re.search(config["target"][key]["regex_login_success"], resp):
            prtmsg("msg_login_success", key)
            success = True
        elif config["target"][key].get("regex_login_fail"):
            match = re.search(config["target"][key]["regex_login_fail"], resp)
            if match:
                prtmsg("err_login_fail_reason", key, reason=msg_cleanup(groupsel(match, key, "login_fail")))
            else:
                prtmsg("err_login_fail", key)
        else:
            prtmsg("err_login_fail", key)
    else:
        prtmsg("msg_login_unknown", key)
        success = True
    save_cookies()
    return success
开发者ID:HiddenKn,项目名称:newpostscheck,代码行数:34,代码来源:newpostscheck.py


示例14: apirequest

def apirequest(params):
    url = 'https://' + re.sub(r'wiki$', '', PREFIX) + '.wikipedia.org/w/api.php';
    params['format'] = 'json'
    params = urllib.parse.urlencode(params).encode('utf-8')
    data = request(url, params)
    if data is None: return None
    return json.loads(data.decode('utf-8'))
开发者ID:cscott,项目名称:wp-image-info,代码行数:7,代码来源:regen.py


示例15: getRankSong

def getRankSong(url):
    lists = []
    tree = request(url)
    soup = tree.find('div', {'class': 'songList'})
    for i in soup.find_all('ul'):
        for a in i.find_all('a'):
            lists.append((a.text.encode('utf-8'), MODE_SONG, a['href']))
    return lists
开发者ID:nomadyun,项目名称:StudyPython,代码行数:8,代码来源:music.py


示例16: getFilter

def getFilter(id):
    unit = "retrieveFilters.getFilter"

    url = "%s/rest/api/2/filter/%s" % (siteUrl, id)

    log(unit, "Sending getFilter(id = %s)" % id)

    return request(url)
开发者ID:dementati,项目名称:excel_scripts,代码行数:8,代码来源:retrieveFilters.py


示例17: addChina

def addChina():
	#央广网
	url = 'http://bfq.cnr.cn/zhibo/'
	link = request(url)
	urls=re.compile('http://.*?/playlist\.m3u8').findall(link)
	nms=re.compile('(?<!-)<td><ahref="javascript:onclick=changeTab1\(\d*?\);">(.*?)</a></td>').findall(link)
	for i, item in enumerate(urls):
		addLink('%d.%s'%(i+1, nms[i]), item)
开发者ID:nomadyun,项目名称:StudyPython,代码行数:8,代码来源:default.py


示例18: search

def search(filterId):
    unit = "retrieveFilters.search"

    url = "%s&fields=key,created,priority,status" % getSearchUrlByFilter(filterId)

    log(unit, "Sending search(filterId = %s)" % filterId)

    return request(url)
开发者ID:dementati,项目名称:excel_scripts,代码行数:8,代码来源:retrieveFilters.py


示例19: getMovie

def getMovie(movieid):
	movie = request(url + url_details + '?movie_id=' + movieid)
	if movie is False:
		print("Error getting movie " + movieid)
	elif movie['status'] == 'error':
		print("Error getting movie " + movieid + ": " + movie['status_message'])
	else:
		return movie['data']
开发者ID:HazCod,项目名称:yify-fs,代码行数:8,代码来源:yify.py


示例20: process

def process():
	with open(output_path, 'w', encoding=args.encoding) as output_file:
		if args.separate == 0:
			conditional_info("[INFO] Processing type: Batch")

			params = urllib.parse.urlencode({'tool': args.tool, 'input': full_text, 'token': token}).encode(pipeline_encoding)

			output_file.write("{0}\n".format(request(params)))
			print("[DONE] It took {0} seconds to process {1} sentences".format(str(time.time()-start_time).split('.')[0], sentence_count))
		else:
			conditional_info("[INFO] Processing type: Sentence-by-sentence")
			for sentence in sentences:

				params = urllib.parse.urlencode({'tool': args.tool, 'input': sentence, 'token': token}).encode(pipeline_encoding)

				output_file.write("{0}\n".format(request(params)))
				conditional_info("[INFO] Processing {0}".format(sentence))
			print("[DONE] It took {0} seconds to process all {1} sentences.".format(str(time.time()-start_time).split('.')[0], sentence_count))
开发者ID:JacobCWard,项目名称:ITU-Turkish-NLP-Pipeline-Caller,代码行数:18,代码来源:pipeline_caller.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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