Python 多次请求 urllib
Python urllib requesting multiple times
我编写了以下 python 代码,它连接到 URL 以使用 json 获取数据。但是,当我的服务器记录这些请求时,它们每次都会发出两次。
我假设这与它首先使用 try
然后在满足 try 方法时重新请求 URL 这一事实有关。关于如何做到这一点以便它只向服务器发送一次请求的任何建议?谢谢
import json
import urllib.request, urllib.error, urllib.parse
remoteURL = "http://192.168.0.29/" + "?id=" + id
json_obj = urllib.request.urlopen(remoteURL)
try:
with urllib.request.urlopen(remoteURL) as response:
if response.read(1):
string = json_obj.read().decode('utf-8')
json_obj = json.loads(string)
responseName = json_obj['Name']
print(responseName)
else:
print("Error")
except:
print("URL Failed")
第一个请求:
json_obj = urllib.request.urlopen(remoteURL)
第二个请求:
with urllib.request.urlopen(remoteURL) as response:
我编写了以下 python 代码,它连接到 URL 以使用 json 获取数据。但是,当我的服务器记录这些请求时,它们每次都会发出两次。
我假设这与它首先使用 try
然后在满足 try 方法时重新请求 URL 这一事实有关。关于如何做到这一点以便它只向服务器发送一次请求的任何建议?谢谢
import json
import urllib.request, urllib.error, urllib.parse
remoteURL = "http://192.168.0.29/" + "?id=" + id
json_obj = urllib.request.urlopen(remoteURL)
try:
with urllib.request.urlopen(remoteURL) as response:
if response.read(1):
string = json_obj.read().decode('utf-8')
json_obj = json.loads(string)
responseName = json_obj['Name']
print(responseName)
else:
print("Error")
except:
print("URL Failed")
第一个请求:
json_obj = urllib.request.urlopen(remoteURL)
第二个请求:
with urllib.request.urlopen(remoteURL) as response: