【发布时间】:2017-07-07 09:40:08
【问题描述】:
我有一个简单的 web.py 应用程序,它读取配置文件并提供给 URL 路径。但是我得到了两种奇怪的行为。一、对 Main 中的数据所做的更改不会反映在 GET 的结果中。二,Main 似乎运行了两次。
期望的行为是修改 Main 中的数据将导致方法看到修改后的数据,并且没有 main 重新运行。
问题:
- 这里真正发生的事情是,mydict 都没有被修改 得到。
- 为什么我的一些代码运行了两次。
- 实现所需行为的最简单途径(最重要)
- 所需行为的 Pythonic 路径(最不重要)
来自 pbuck(已接受的答案):3.)的答案是替换
app = web.application(urls, globals())
与:
app = web.application(urls, globals(), autoreload=False)
在 pythons Linux (CentOS 6 python 2.6.6) 和 MacBook (brew python 2.7.12) 上的行为相同
开始时我得到:
$ python ./foo.py 8080
Initializing mydict
Modifying mydict
http://0.0.0.0:8080/
查询时:
wget http://localhost:8080/node/first/foo
wget http://localhost:8080/node/second/bar
这会导致(注意第二个“初始化 mydict”):
Initializing mydict
firstClass.GET called with clobber foo
firstClass.GET somevalue is something static
127.0.0.1:52480 - - [17/Feb/2017 17:30:42] "HTTP/1.1 GET /node/first/foo" - 200 OK
secondClass.GET called with clobber bar
secondClass.GET somevalue is something static
127.0.0.1:52486 - - [17/Feb/2017 17:30:47] "HTTP/1.1 GET /node/second/bar" - 200 OK
代码:
#!/usr/bin/python
import web
urls = (
'/node/first/(.*)', 'firstClass',
'/node/second/(.*)', 'secondClass'
)
# Initialize web server, start it later at "app . run ()"
#app = web.application(urls, globals())
# Running web.application in Main or above does not change behavior
# Static Initialize mydict
print "Initializing mydict"
mydict = {}
mydict['somevalue'] = "something static"
class firstClass:
def GET(self, globarg):
print "firstClass.GET called with clobber %s" % globarg
print "firstClass.GET somevalue is %s" % mydict['somevalue']
return mydict['somevalue']
class secondClass:
def GET(self, globarg):
print "secondClass.GET called with clobber %s" % globarg
print "secondClass.GET somevalue is %s" % mydict['somevalue']
return mydict['somevalue']
if __name__ == '__main__':
app = web.application(urls, globals())
# read configuration files for initializations here
print "Modifying mydict"
mydict['somevalue'] = "something dynamic"
app.run()
【问题讨论】:
标签: python-2.7 web.py