Python / Flask Service Level Excellence

I am a little new to Python (I come from the Java / C ++ background). I play with Flask for web development. My question is somewhat related to injection dependency and thread safety. In the word Java / Spring, you will have a controller that has a Service that injects a UserService into it. And when you say addUser endpoint, it will call userService.addUser (someData).

If I want to do the same in Python / Flask, it is best to have a UserService file with functions like addUser (), deleteUser (), etc., and just call them with UserService.addUser (), UserService. deleteUser () and is this thread safe? Or should I have a new instance of the user service at each endpoint?

+7
source share
1 answer

As with all thread-related issues, the question arises: "did you make it thread safe"?

If your user service looks like this:

# user_service.py from some.package import database def add_user(user_information=None): db = database.connect() db.insert(user_information) def update_user(user_information=None): db = database.connect() db.update(user_information["user_id"], user_information) def delete_user(user_id=None): db = database.connect() db.delete(user_id) 

Then, assuming even a remote, sensible implementation of some.package.database , it will be thread safe. If, on the other hand, you are doing something like this:

 # bad_user_service.py from some.package import database # Shared single connection # Probably *not* thread safe db = database.connect() def add_user(user_information=None): db.insert(user_information) # ... etc. ... 

Now, including db = database.connect() at the top of each of your maintenance methods, itโ€™s not very dry. You can avoid this problem by wrapping your connection work in a decorator (for example):

 def provide_db(func): @functools.wraps(func) def new_function(*args, **kwargs): db = database.connect() return func(db, *args, **kwargs) return new_function 

Then you can do this:

 # user_service.py from your.data.layer import provide_db @provide_db def add_user(db, user_information=None): db.insert(user_information) # ... etc. ... 
+14
source

All Articles