我正在尝试使用pyramid-SQLAlchemy使用csv填充模型?

时间:2015-01-07 09:57:33

标签: python csv sqlalchemy pyramid flask-sqlalchemy

1.Am尝试使用sqlalchemy从表单填充模型表但我不断收到错误

2.当我在插入表格之前尝试取消数据会话时,我收到此错误 TypeError:**之后的DeclarativeMeta对象参数必须是映射,而不是列表

这是我的代码

def d(domain_file, request):
    if request.method == 'POST':  
        dbsession = DBSession()
        song_file = request.POST['csv'].file

        file = open(song_file, "r")
        csv_file = csv.reader( song_file,  delimiter=",", quotechar='"')

    for row in csv_file:
#data type conversion from (csv)string before inserting to table
        for key, value in row.items():
            #value.insert(row)
            print key, value

            song = Song(**rows)
            dbsession.add(song)
        return HTTPFound(Location=request.route_url('d'))

    return {"project":"beatstore"}

形式

form action="${request.route_url('d')}" method="POST" class="form-horizontal" >





            <div class="form-group">
                              <label class="col-lg-2 control-label">CSV File</label>
                              <div class="col-lg-10">
                                <input name="csv" id="mp3" type="file" accept=".csv" required class="form-control" placeholder="Upload CSV File" />             
                              </div>
                            </div>


            <div id="selectedFiles"></div>

                                <hr />
                            <div class="form-group">
                              <div class="col-lg-offset-2 col-lg-9">
                                <button type="submit" class="btn btn-primary">Submit</button>
                              </div>
                            </div>

             </form>

错误堆栈

File "/usr/lib/python2.7/dist-packages/pyramid/config/views.py", line 347, 
in rendered_view
    result = view(context, request)
  File "/home/elagu/Dropbox/pyramid_sites/beatstore/beatstore/views.py", 
  line 931, in d
    for key, value in row.items():
AttributeError: 'list' object has no attribute 'items'

1 个答案:

答案 0 :(得分:1)

行是一个列表。 您可以从中创建一个dict,例如:

header = ['name', 'author', 'year']
for row in csv_file:
    song_params = dict(zip(header, row))
    song = Song(**song_params)