2

I have a file called mapping.py which has a dictionary methodMapping. In my web application, a key-value pair is added to the methodMapping dictionary. After I appended it to mapping.py, reload(mapping) is called, and the file reloads (I checked by printing out a message on top of the file), but when I try to access the key-value pair, KeyError is raised.

original mapping.py file:

print('mapping.py loaded) methodMapping =  {} 
methodMapping['key1'] = 'value1'

here is how the key-value pair is appended to the file:

from mapping import methodMapping
@app.route('/append', methods=['POST'])
def append():

    key = request.form.get('key')
    value = request.form.get('value')

    value = value.encode('ascii', 'ignore')

    f = open('mapping.py', 'a')
    f.write('methodMapping["'+key+'"] = '+value)
    f.write("\n\n")
    f.close()

    reload(mapping)
    return ....

after a key-value is added, mapping.py looks like this:

print('mapping.py loaded') 
methodMapping =  {} 
methodMapping['key1'] = 'value1'
methodMapping['key2'] = 'value2'

however, when I try to access methodMapping['key2'] from flaskServer.py, KeyError exception is raised. When I restart the server, it is able to find methodMapping['key2'].

Note: I have already checked this link also tried app.run(debug=True, port=8000), but this is not possible for my application because I'm using keras with Tensorflow backend, and setting debug=True will load it twice and leads to a ValueError: Tensor tensor(...) is not part of the graph error

Any comment or suggestion is greatly appreciated. Thank you.

Community
  • 1
  • 1
matchifang
  • 5,190
  • 12
  • 47
  • 76
  • I found the solution: The problem was from the way I imported mapping. If I want `reload(mapping)` to work, I need to use `import mapping` instead of `from mapping import ...` – matchifang Mar 06 '17 at 02:35

1 Answers1

2

The problem is the way you imported mapping. If you want reload(mapping) to work, you need to use import mapping instead of from mapping import....

And if you find the answer, you should put it in an Answer instead of in a comment. ;)

pjz
  • 41,842
  • 6
  • 48
  • 60
  • Thank you for the comment - I'll check yours as the answer then :) Also, I have another problem which is after the reload(), I am unable to use pickle because, according to this http://stackoverflow.com/questions/1412787/picklingerror-cant-pickle-class-decimal-decimal-its-not-the-same-object it needs to be in the form `from mapping import...` for pickle to work. Do you perhaps know the answer to that? – matchifang Mar 06 '17 at 18:37
  • According to that answer you just have to import things the same way each time, not a particular way. – pjz Mar 07 '17 at 12:12