【发布时间】:2012-04-24 19:40:46
【问题描述】:
我在我的应用程序的一种方法中使用 Python 的 requests 库。该方法的主体如下所示:
def handle_remote_file(url, **kwargs):
response = requests.get(url, ...)
buff = StringIO.StringIO()
buff.write(response.content)
...
return True
我想为该方法编写一些单元测试,但是,我想做的是传递一个虚假的本地 url,例如:
class RemoteTest(TestCase):
def setUp(self):
self.url = 'file:///tmp/dummy.txt'
def test_handle_remote_file(self):
self.assertTrue(handle_remote_file(self.url))
当我使用本地 url 调用 requests.get 时,我得到了下面的 KeyError 异常:
requests.get('file:///tmp/dummy.txt')
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/packages/urllib3/poolmanager.pyc in connection_from_host(self, host, port, scheme)
76
77 # Make a fresh ConnectionPool of the desired type
78 pool_cls = pool_classes_by_scheme[scheme]
79 pool = pool_cls(host, port, **self.connection_pool_kw)
80
KeyError: 'file'
问题是如何将本地 url 传递给 requests.get?
PS:上面的例子是我自己编的。它可能包含许多错误。
【问题讨论】:
-
可以使用本地纯python web服务器吗?
-
为什么不直接使用
html = open("/tmp/dummy.txt, 'r').read()?
标签: python http python-requests local-files