IDLE中的URLLIB2调用和Django之间的区别?

时间:2010-05-06 02:07:25

标签: python django

在本地安装的django apache 2.2

中运行时,以下代码段按预期工作
 fx = urllib2.Request(f);
 fx.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.36 Safari/525.19');
 url_opened = urllib2.urlopen(fx);

然而,当我在同一台机器上将该代码输入IDLE时,我收到以下错误:

    url_opened = urllib2.urlopen(fx);
  File "C:\Python25\lib\urllib2.py", line 124, in urlopen
    return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 387, in open
    response = meth(req, response)
  File "C:\Python25\lib\urllib2.py", line 498, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python25\lib\urllib2.py", line 425, in error
    return self._call_chain(*args)
  File "C:\Python25\lib\urllib2.py", line 360, in _call_chain
    result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 506, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 407: Proxy Authentication Required

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

urlliburllib2我认为如果没有以编程方式设置代理,请查看代理的环境变量。也许在IDLE中没有正确设置代理环境变量?

将以下IDLE的输出与Django程序进行比较:

import os, pprint
for k in os.environ:
    if 'proxy' in k.lower(): # look for proxy environment variables
        print k, os.environ[k]

编辑:引用http://docs.python.org/library/urllib2.html#urllib2.ProxyHandler

Cause requests to go through a proxy. If proxies is given, it must be a 
dictionary mapping protocol names to URLs of proxies. The default is to read the 
list of proxies from the environment variables. If no proxy environment 
variables are set, in a Windows environment, proxy settings are obtained from 
the Internet Settings section and in a Mac OS X environment, proxy 
information is retrieved from the OS X System Configuration Framework.

To disable autodetected proxy pass an empty dictionary.

也许Django创建了ProxyHandler?尝试在IDLE中调用urllib2.ProxyHandler()

答案 1 :(得分:0)

也许Django版本已经使用代理所需的凭据准备了urllib2,而IDLE版本却没有?