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 hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        print e.reason
except urllib2.URLError, e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"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": open(stlPath,"rb"), "id": self._profile_id})
request = urllib2.Request(cloud_slice_url, datagen, headers)
try:
    response = urllib2.urlopen(request, timeout=1000)
except urllib2.HTTPError, e:
    print "HTTPError:"
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        print e.reason
except urllib2.URLError, e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"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.”

阅读 3.9k
1 个回答

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

datagen, headers = multipart_encode([MultipartParam("file",open(stlPath,"rb")), MultipartParam("id", self._profile_id)])

关于MultipartParam:

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题