Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

One, foreword

The setattr() function can be used to set the properties of an object. It is a built-in function in Python. The setattr() function takes three parameters: object, object property name (represented as a string), and property value value, and returns no value.

Setattr () corresponds to getattr(). Similar to setattr, getattr() passes in an object and an object attribute to get the value of the attribute, but it is quite different from the method described in this article, so it will not be described later.

Basic use of setattr(

Setattr () lets you enter an object attribute as a string and modify the value of the attribute (or create an attribute for the object if the attribute does not exist) :

class Student:
    name = "aaa"
s = Student()
getattr(s, "name")   # "aaa"
setattr(s, "name"."bbb")
getattr(s, "name")   # "bbb"
Copy the code

The running results are as follows:

Setattr () and sqlAlchemy

Sqlalchemy is arguably the most commonly used ORM for Python backend development. In everyday life, we may encounter a situation where we are modifying information. A lot of information modification is simply a numerical overwriting, but if we need to use an independent interface for overwriting each attribute, it will undoubtedly increase the redundancy of the code, and setattr() can better solve this problem:

Now consider a Student class with multiple names:

class Student(Model) :
    __tablename__ = 'student'
    id = Column(Integer, primary_key=True)
    Chinese_name = Column(String(16))
    English_name = Column(String(16))
    Russian_name = Column(String(16))
Copy the code

Now, we need an interface to modify each of these names. This can be done as follows:

/v1/name/

/

Name_type indicates the name of the Student, including Chinese_name and English_name. Name indicates the name to be changed.

Then, a filter is applied to name_type:

if name_type not in ["Chinese_name"."English_name"."Russian_name"] :return 404
Copy the code

Then use setattr() to update the data:


student = Student.query.filter(Student.id= =id).first()
Filter the name if necessary
setattr(student, name_type, name)
Copy the code

Sqlachemy commits session if no error occurs:

try:
    student = Student.query.filter(Student.id= =id).first()
    Filter the name if necessary
    setattr(student, name_type, name)
except:
    An error occurs and the rollback operation is performed
    db.session.rollback()
    return 500
else:
    Save the update
    db.session.commit()
    return 200
Copy the code