将变量转换为类变量(不知道该命名什么)
使用
- Flask
- Flask-sqlalchemy
- Sqlalchemy
- Jquery
- Datatables(jquery 插件)
- Jeditable(jquery 插件)
考虑这个用户类(直接来自flask-sqlalchemy 文档):
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
数据表发出 ajax 请求并填充表。然后每个 td 都可以使用 jeditable 进行编辑。一旦 td 被修改,jeditable 就会向 localhost/modify 发出一个 POST 请求,其中包含:
- 行 id(与用户类中的相同 id)
- 新的修改值
- 被更改的表的列(为了论证,让我们假设有三列 id/username/email) (int)
现在,我希望在处理 localhost/modify 的函数中获取行 id,创建一个用户对象并查询数据库以获取该特定的行,查看需要修改哪些属性,使用新值修改它并提交到数据库。这是我到目前为止得到的:
@app.route('/modify', methods=['GET', 'POST'])
def modify()
if request.method == 'POST' :
user = user.query.get(form.row_id)
if form.column_id == int(0):
user.id = form.value
elif form.column_id == int(1):
user.username = form.value
elif form.column_id == int(2):
user.email = form.value
else:
pass
db.session.commit()
return 'ok'
这样,是的,它确实有效,但必须有一个更漂亮的方法。这个看起来不太...pythonic
Mihai
Using
- Flask
- Flask-sqlalchemy
- Sqlalchemy
- Jquery
- Datatables (jquery plugin)
- Jeditable (jquery plugin)
Consider this user class ( straight out of flask-sqlalchemy docs):
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
The datatables makes an ajax request and populates the table. Each td then is made editable in place with jeditable. As soon as a td is modified, jeditable makes a POST request to localhost/modify containing:
- The row id(the same id from the user class)
- The new modified value
- The column of the table that was altered ( for the sake of argument let's assume that there are three columns id/username/email) (int)
Now, i'd like that in the function that handles localhost/modify i take the row id, make a user object and query the db for that specific row, see what property needs to be modified, modify it with the new value and commit to the db. Here's what i got so far:
@app.route('/modify', methods=['GET', 'POST'])
def modify()
if request.method == 'POST' :
user = user.query.get(form.row_id)
if form.column_id == int(0):
user.id = form.value
elif form.column_id == int(1):
user.username = form.value
elif form.column_id == int(2):
user.email = form.value
else:
pass
db.session.commit()
return 'ok'
This way, yes it does work but theremust be amore beautiful approach. This one doesn't seem very...pythonic
Mihai
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用列 ID 到属性名称的映射。
Use a map of column ID to attribute name.