Inserting data from multipledict into multiple rows using sqlalchemy
Assuming I have a table with the following columns:
id, title, description
I have a form with multiple input fields with the same names. E.g.:
<input type='text' name='title' value = 'A title' />
<input type='text' name='title' value = 'Another title' /> etc...
I get the following multidict from the POST request.
([('title', 'A title'), ('description', 'A description'),
('title', 'Another title'), ('description', 'Another description'),
('title', 'One more title'), ('description', 'One more description')])
My question is, from the data above how would I seperate each row of data from the mul开发者_StackOverflowtidict above and do an 'INSERT INTO' using SQLAlchemy, so data is inserted into multiple rows in the table.
Thanks.
Following (self-contained working sample) code should give you the idea:
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True,)
metadata = MetaData()
mytable = Table('mytable', metadata,
Column('id', Integer, primary_key=True),
Column('title', String(50)),
Column('description', String(50)),
)
class MyObject(object):
# 1. define keywork based constructor (or do this in the part 2.)
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
mapper(MyObject, mytable)
metadata.create_all(engine)
session = sessionmaker(bind=engine, autoflush=False)()
input = ([('title', 'A title'), ('description', 'A description'),
('title', 'Another title'), ('description', 'Another description'),
('title', 'One more title'), ('description', 'One more description')])
# 2. add data to the session, then commit
while input:
values = dict((input.pop(0), input.pop(0)))
obj = MyObject(**values)
session.add(obj)
session.commit()
I use multidict.getall()
and zip
to achieve the same in my code:
...
input = ([('title', 'A title'), ('description', 'A description'),
('title', 'Another title'), ('description', 'Another description'),
('title', 'One more title'), ('description', 'One more description')])
titles = input.getall('title')
descriptions = input.getall('description')
for title, description in zip(titles, descriptions):
obj = MyObject(title, description)
session.add(obj)
...
It seems a bit more clear but I don't know about other advantages/disadvantages.
精彩评论