'Updation of shared global object - Prevent Racing

I'm creating an API server using Flask that responds to 2 types of requests - queries and updation. Internally, an object rec is used to carry out computations.

When rec is initialized, some data from a database is stored in it. All queries are resolved using this data. From time to time, the server receives an updation request, when the database has changed. After this, rec's internal data is brought up - to - date with the current data in database.

Here's some code that outlines the basic idea:

from flask import Flask
from utilities import Rec

app = Flask(__name__)

# Initialize rec
rec = Rec()

# ---- API Endpoints Definition ----
@app.route('/query1', methods=['GET'])
def solve_query_1():
    # Computation
    result = rec(1, 'a')
    return result


@app.route('/update_rec', methods=['POST'])
def update_rec():
    # rec updated here
    rec.update()
    return 'Done'


if __name__ == '__main__':
    app.run(debug=True)

Now, as rec may be updated depending on any external request, if /query1 route is used in some API call while rec is being updated (it takes time to update rec), racing might occur.

Using a reader - writer lock may solve the problem, but, while rec is being updated, new requests to /query1 will have to wait.

Is there some way in python to allow new requests for /query1 to be serviced using the old rec while a new instance of rec is made, then the old rec updated with the newer rec?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source