[英]GAE Datastore: put into a field using a string as the field reference python
我正在從網絡來源讀取CSV文件,並希望將其存儲在我的GAE數據存儲區中。 CSV數據帶有標題行,只需進行一點操作即可匹配我的數據存儲區中的字段(例如,用下划線替換CSV文件中的空格以匹配數據存儲區)。 我只想遍歷CSV文件每一行中的字段,然后將它們放入數據存儲區。
我的問題是如何使用字符串引用數據存儲區中的字段並將其值設置為另一個字符串?
from google.appengine.ext import db
from urllib import urlopen
from csv import DictReader
class Table(db.Model):
field_one = db.StringProperty() # equivalent to 'field one' column in CSV data
field_two = db.StringProperty() # equivalent to 'field two' column in CSV data
def store_csv_data(url):
# Request the url with the csv data
f = urlopen(url)
csv_dict = DictReader(f, delimiter=',', quotechar='"')
for line in csv_dict:
# Do some processing on the data (not shown here)
row = Table()
for field in line:
db_field = field.replace(' ','_') # Make the csv field match the db field
db_value = line[field] # The value I want to store in the datastore
row.db_field = db_value # THIS IS WHERE THE CODE FAILS
row.put()
這實際上不會產生任何錯誤,只是在數據存儲區中創建了一堆空行。
setattr(row, db_field, db_value)
我猜你的問題在這條線上:
db_value = line[field]
應該:
db_value = field[0]
您將不得不用字段列號替換零,因此繼續上面的示例:
class Table(db.Model):
field_one = db.StringProperty()
field_two = db.StringProperty()
field_one為0,field_2為1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.