0

To build a dynamic user update route on Flask, I have iterate over the user Flask SQLAlchemy object using the dunder __dict__:

parameters = ['name'] # Valid parameters after the Regex filter was applied

for parameter in parameters:
    user.__dict__[parameter] = request.form.get(parameter)

I have done this to avoid the usage of ifs. To ensure that only valid parameters are present in parameters, I have applied a Regex pattern that filters the valid parameters received in the request for the user route, and I have documented this aspect on the doc string.

I'm asking if iterate over a Flask SQLAlchemy object using __dict__ is it a bad practice because if I print the user.__dict__, I receive all parameters, even those that aren't on the Regex filter, i.g, password, date created, etc; and should never be updated by this route.

I have found another approach that uses get all columns in SQLAlchemy, but I think that at the end its similar to the approach that I'm using...

Obs: the implemented route can update specific attributes from user or all of them, using the same route

  • 2
    Yes it is; it does not work: https://stackoverflow.com/questions/17013965/sqlalchemy-commit-changes-to-object-modified-through-dict – Ilja Everilä Apr 18 '19 at 17:44
  • 1
    In general: direct access from outside the class to a special method or var enclosed by double underscores is never best practice. – Klaus D. Apr 18 '19 at 17:46
  • Awesome, thanks guys. I'm going try to use `setattr` indicate by @lIja. –  Apr 18 '19 at 17:47
  • 1
    Related as well: https://stackoverflow.com/questions/23272789/when-should-method-be-called-directly, in general it's better to use operators and available functions instead of magic methods and attributes. – Ilja Everilä Apr 18 '19 at 17:49

1 Answers1

0

I'd recommend looking into marshmallow-sqlalchemy to manage this sort of thing. I've found that there are very few use-cases where there is a problem, and __dict__ is the best solution.

Here's an example application using it: How do I produce nested JSON from database query with joins? Using Python / SQLAlchemy

Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55