2017-07-18 64 views
1

我想用urllib处理HTTPError。 我的设置是使用Django 1.10的anaconda virtualenv中的python3。 当代码得到try,它不会进入except和Django崩溃我的页面告诉我有一个HTTP错误。urllib HTTPError没有在Python/Django中被捕获

下面是代码:

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 

try: 
    req = Request(api.lists.members.get(LIST_ID, client_email)) 
    response = urlopen(req) 
except HTTPError as e: 
    print('Error code: ', e.code) 
else: 
    print('everything is fine') 

TRACEBACK:

环境:

Request Method: POST 
Request URL: http://127.0.0.1:8000/homepage/ 

Django Version: 1.10 
Python Version: 3.6.1 
Installed Applications: 
['django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'website'] 
Installed Middleware: 
['django.middleware.security.SecurityMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware'] 



Traceback: 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 
    39.    response = get_response(request) 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 
    187.     response = self.process_exception_by_middleware(e, request) 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 
    185.     response = wrapped_callback(request, *callback_args, **callback_kwargs) 

File "/Users/plfiras/vinhood/vinhood-website/website/views.py" in homepage 
    52.    conn = http.client.HTTPConnection(api.lists.members.get(LIST_ID, client_email)) 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/mailchimp3/entities/listmembers.py" in get 
    116.   return self._mc_client._get(url=self._build_path(list_id, 'members', subscriber_hash), **queryparams) 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/mailchimp3/mailchimpclient.py" in wrapper 
    25.    return fn(self, *args, **kwargs) 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/mailchimp3/mailchimpclient.py" in _get 
    100.    r.raise_for_status() 

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/requests/models.py" in raise_for_status 
    928.    raise HTTPError(http_error_msg, response=self) 

Exception Type: HTTPError at /homepage/ 
Exception Value: 404 Client Error: Not Found for url: https://us13.api.mailchimp.com/3.0/lists/7bdb42e5c9/members/d071e758df3554f0fe89679212ef95e8 
+0

发布回溯 –

+0

@ArpitSolanki完成! –

+0

在我的系统上试过你的代码和它的工作状态非常好 –

回答

-1

出于某种原因,并没有追赶HTTPError。 通过用Exception替换HTTPError,它可以工作。

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 

try: 
    req = Request(api.lists.members.get(LIST_ID, client_email)) 
    response = urlopen(req) 
except Exception as e: 
    print('Error code: ', e.code) 
else: 
    print('everything is fine') 
1

您正在捕捉错误的异常。看看你回溯的最后一行:

File "/Users/plfiras/anaconda/lib/python3.6/site-packages/requests/models.py" in raise_for_status 
    928. raise HTTPError(http_error_msg, response=self) 

requests/models.py线31看一看,你会看到以下内容:

from .exceptions import (
HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, 
ContentDecodingError, ConnectionError, StreamConsumedError) 

正如你可以看到HTTPError被实际募集来自requests/exceptions.py。看看该文件的顶部,你会看到:

from urllib3.exceptions import HTTPError as BaseHTTPError 


class RequestException(IOError): 
    """There was an ambiguous exception that occurred while handling your 
    request. 
    """ 

    def __init__(self, *args, **kwargs): 
     """Initialize RequestException with `request` and `response` objects.""" 
     response = kwargs.pop('response', None) 
     self.response = response 
     self.request = kwargs.pop('request', None) 
     if (response is not None and not self.request and 
       hasattr(response, 'request')): 
      self.request = self.response.request 
     super(RequestException, self).__init__(*args, **kwargs) 


class HTTPError(RequestException): 
    """An HTTP error occurred.""" 

这表明HTTPError被导入为BaseHTTPError,并请求库已经实现了它自己的HTTPError不延伸urlib3.HTTPError 。

所以抓住你需要从请求模块导入HTTPError错误,不urlib,就像这样:

from requests.exceptions import HTTPError 

try: 
    req = Request(api.lists.members.get(LIST_ID, client_email)) 
    response = urlopen(req) 
except HTTPError as e: 
    print('Error code: ', e.code) 
else: 
    print('everything is fine')