[英]Looking for a better way to handle update request in python
I create a flask
application for my web server and one of the endpoint is to update contact
information. 我为我的Web服务器创建了一个
flask
应用程序,端点之一是更新contact
信息。 One contact has many attributes such as username
, email
, first_name
, last_name
etc. I declare below method to handle update request on the contact: 一个联系人具有许多属性,例如
username
, email
, first_name
, last_name
等。我声明以下方法来处理联系人的更新请求:
def update_contact_with_form(contact_id, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None):
session = Session()
try:
contact = session.query(DBContact).filter(DBContact.id == contact_id).one()
if username != None:
contact.username = username
if first_name != None:
contact.first_name = first_name
...
except Exception as error:
print(error)
finally:
session.close()
return abort(400, 'failed to update')
The above code works fine but what I don't like is to check each value against None
. 上面的代码工作正常,但是我不喜欢针对
None
检查每个值。 Is there a better way to update the instance without checking each attribute? 有没有更好的方法来更新实例而不检查每个属性?
How about this way? 这样呢
def update_contact_with_form(contact_id, **kwargs):
session = Session()
try:
contact = session.query(DBContact).filter(DBContact.id == contact_id).one()
for k, v in kwargs:
if v is not None:
contact.__setattr__(k, v)
except Exception as error:
print(error)
finally:
session.close()
return abort(400, 'failed to update')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.