<p>我找到了一种方法,将该结构序列化为JSON,然后返回到我传递给CouchDB的Python dict,然后CouchDB会将其重新序列化回JSON以保存(是的,很奇怪,不好用,但它可以工作吗?)在</p>
<p>我必须为转储执行自定义序列化程序方法,因为<code>time_struct</code>的<code>repr</code>不能是{<cd3>}'d</p>
<p>来源:<a href="http://diveintopython3.org/serializing.html" rel="nofollow">http://diveintopython3.org/serializing.html</a></p>
<p>代码:</p>
<pre><code>#!/usr/bin/env python2.7
from collections import namedtuple
import csv
import json
import time
import feedparser
import couchdb
def to_json(python_object):
if isinstance(python_object, time.struct_time):
return {'__class__': 'time.asctime',
'__value__': time.asctime(python_object)}
raise TypeError(repr(python_object) + ' is not JSON serializable')
Feed = namedtuple('Feed', ['name', 'url'])
COUCH_HOST = 'http://mycouch.com'
COUCH_USER = 'user'
COUCH_PASS = 'pass'
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:
j = json.dumps(item, default=to_json)
db.save(json.loads(j))
</code></pre>