(澳门银河官网) urllib2.urlopen传入一个Request为何会返回URLError?而传入固定url时可以返回HTTPError?
澳门银河官网
澳门银河官网
当前位置 : 澳门银河官网 > 澳门银河官网

(澳门银河官网) urllib2.urlopen传入一个Request为何会返回URLError?而传入固定url时可以返回HTTPError?

1.用URLlib2的urlopen向django发送了一个request:
传入一个固定的URL时:

try:
    response = urllib2.urlopen"http://cloud-server:8005/cloud_slice/handlefiles"
except urllib2.HTTPError, e:
    print "HTTPError:"
    if hasattre,"code":
        print e.code
    if hasattre,"reason":
        print e.reason
except urllib2.URLError, e:
    if hasattre,"code":
        print e.code
    if hasattre,"reason":
        print e.reason

在django端的进行了用户权限判断:

if not request.user.is_authenticated:
    logging.warning"handleFiles:User is not authenticated!"
    return HttpResponseForbidden
然后我得到了一个HTTPError的返回:
HTTPError:
403
FORBIDDEN

2.但如果传入的参数是一个包含data和headers的urllib2.Request,如下:
cloud_slice_url="http://cloud-server:8005/cloud_slice/handlefiles"
datagen, headers = multipart_encode{"file": openstlPath,"rb", "id": self._profile_id}
request = urllib2.Requestcloud_slice_url, datagen, headers
try:
    response = urllib2.urlopenrequest, timeout=1000
except urllib2.HTTPError, e:
    print "HTTPError:"
    if hasattre,"code":
        print e.code
    if hasattre,"reason":
        print e.reason
except urllib2.URLError, e:
    if hasattre,"code":
        print e.code
    if hasattre,"reason":
        print e.reason

就会得到一个URLError:

URLError:
[Errno 32] Broken pipe

3.请问如何在传入request对象时同样得到一个403 HTTRError的返回?
https://docs.python.org/2/lib...中提到了HTTPError是“This is useful when handling exotic HTTP errors, such as requests for authentication.”

如果上传文件,需要用MultipartParam包一下:

datagen, headers = multipart_encode[MultipartParam"file",openstlPath,"rb", MultipartParam"id", self._profile_id]

关于MultipartParam:

Represents a single parameter in a multipart/form-data request

栏目列表

广告位

澳门银河官网