0

I have a code that requires that when users type in their input, it is stored in a json file and accessed by some functions. Different users type in their input at different times, in this case the json file is accessed by multiple users as follows:

#post data
for item in mm:
    data['questions'].append({'name': item})
    with open('my_data_loop.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

#get it
posted = []
with open('my_data_loop.json') as json_file:
    data = json.load(json_file)
    for p in data['questions']:
        posted.append(p['name'])
        ...process the string

If I have more users concurrently accessing the file, will there be any issue of accessing wrong data at one point? e.g. user 'B' getting info from processed string for user 'A' How can I avoid this and allow one user's iteration to post and process the data to completion?

***I've not used json data extensively, just learning the ropes.

lobjc
  • 2,751
  • 5
  • 24
  • 30
  • Two problems here. 1) How do you know which data in the JSON file belongs to a particular user? 2) You'll need some kind of locking mechanism to ensure that you don't have more than 1 user concurrently updating the file. –  Nov 11 '21 at 07:19
  • What do you mean by `multiple users`? Do you have multiple users in your PC and they can run this code separately (or at the same time) and update the file? – MSH Nov 11 '21 at 07:21
  • A web app. Users logged in. Retrieves data from database after processing the user's string. – lobjc Nov 11 '21 at 07:25
  • @BrutusForcus, some kind of locking mechanism is what i'm trying to develop, but the way out to do it is what i'm asking. To know which data: The app has a login system. – lobjc Nov 11 '21 at 07:30
  • 1
    Is the file a must? Can you use any sort of `SQL`? See: https://softwareengineering.stackexchange.com/a/190483. The 10th says `Databases are concurrent; multiple users can use them at the same time without corrupting the data.` – MSH Nov 11 '21 at 07:32
  • This is discussed at length [here](https://stackoverflow.com/questions/489861/locking-a-file-in-python) –  Nov 11 '21 at 07:32
  • Thanks a lot for the help. I really appreciate. – lobjc Nov 11 '21 at 07:39

0 Answers0