如何在烧瓶中重新加载python模块? [英] How to reload python module in flask?

查看:47
本文介绍了如何在烧瓶中重新加载python模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 mapping.py 的文件,该文件具有一个字典 methodMapping .在我的Web应用程序中,键值对被添加到methodMapping字典中.将其附加到 mapping.py 后,将调用 reload(mapping),然后重新加载文件(我通过在文件顶部打印出一条消息进行检查),但是当我尝试访问键值对时,会出现 KeyError .

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.

原始mapping.py文件:

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 ....

添加键值后,mapping.py如下所示:

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

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

但是,当我尝试从flaskServer.py访问 methodMapping ['key2'] 时,会出现 KeyError 异常.重新启动服务器时,它可以找到 methodMapping ['key2'] .

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'].

注意:我已经检查了这个链接尝试过 app.run(debug = True,port = 8000),但这对我的应用程序是不可能的,因为我使用的是带有Tensorflow后端的keras,并且设置debug = True会将其加载两次并导致到 ValueError:张量张量(...)不在图形中错误

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.

推荐答案

问题是导入映射的方式.如果要重新加载(映射)工作,则需要使用导入映射,而不是从映射导入... .

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. ;)

这篇关于如何在烧瓶中重新加载python模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆