回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一个脚本,我想读取RSS提要中的条目,并将JSON格式的各个条目存储到CouchDB数据库中。在</p>
<p>我代码中有趣的部分如下所示:</p>
<pre><code>Feed = namedtuple('Feed', ['name', 'url'])
couch = couchdb.Server(COUCH_HOST)
couch.resource.credentials = (COUCH_USER, COUCH_PASS)
db = couch['raw_entries']
for feed in map(Feed._make, csv.reader(open("feeds.csv", "rb"))):
d = feedparser.parse(feed.url)
for item in d.entries:
db.save(item)
</code></pre>
<p>当我尝试运行该代码时,我从<code>db.save(item)</code>中得到以下错误:</p>
^{pr2}$
<p>好的,所以我做了一些调试。。。在</p>
<pre><code>for feed in map(Feed._make, csv.reader(open("feeds.csv", "rb"))):
d = feedparser.parse(feed.url)
for item in d.entries:
print(type(item))
</code></pre>
<p>结果是<code><class 'feedparser.FeedParserDict'></code>--ahh,所以feedparser使用它自己的dict类型。。。那么,如果我尝试显式地将其转换为<code>dict</code>怎么办?在</p>
<pre><code>for feed in map(Feed._make, csv.reader(open("feeds.csv", "rb"))):
d = feedparser.parse(feed.url)
for item in d.entries:
db.save(dict(item))
Traceback (most recent call last):
File "./feedchomper.py", line 32, in <module>
db.save(dict(item))
File "/home/dealpref/lib/python2.7/couchdb/client.py", line 407, in save
_, _, data = func(body=doc, **options)
File "/home/dealpref/lib/python2.7/couchdb/http.py", line 399, in post_json
status, headers, data = self.post(*a, **k)
File "/home/dealpref/lib/python2.7/couchdb/http.py", line 381, in post
**params)
File "/home/dealpref/lib/python2.7/couchdb/http.py", line 419, in _request
credentials=self.credentials)
File "/home/dealpref/lib/python2.7/couchdb/http.py", line 239, in request
resp = _try_request_with_retries(iter(self.retry_delays))
File "/home/dealpref/lib/python2.7/couchdb/http.py", line 196, in _try_request_with_retries
return _try_request()
File "/home/dealpref/lib/python2.7/couchdb/http.py", line 222, in _try_request
chunk = body.read(CHUNK_SIZE)
AttributeError: 'dict' object has no attribute 'read'
</code></pre>
<p>什么?这是没有道理的,因为下面的方法很好,而且类型仍然是<code>dict</code>:</p>
<pre><code>some_dict = dict({'foo': 'bar'})
print(type(some_dict))
db.save(some_dict)
</code></pre>
<p>我错过了什么?在</p>