finish() called twice

2015-06-17 17:18:49 +08:00
 wolegequ
抱歉,标题略含糊.

有两个返回json接口
http://example.com/api/user/uid
http://example.com/api/user/uid/fun

本打算如此实现 handles
(r'/api/user/(.*)', user.fun1),
(r'/api/user/(.*)/fun2', user.fun2 ),

搞了半天,发现 user.fun1 根本不会调用 ......

于是乎改为这样

(r'/api/user/(.*)', user.funs ),


class funs(BaseController):

@tornado.web.asynchronous
def get(self, params):

if 'fun' in params:
self.fun2
else:
self.fun1

惊奇的发现 it works !!!(虽然很山寨...)

重点来了 !!!!

客户端两个接口先后几乎同时请求

self.fun1 self.fun2最后都会调用 self.finish(),

于是乎出现了 finish() called twice - - !

后来看到有说法@tornado.web.asynchronous 是不可以self.finish()的

于是乎改为self.fun1 self.fun2最后都调用 self.write(),

没有 finish() called twice了,但是有一个接口一直没数据返回(单独请求任意一个都正常!)

醉了醉了....
5322 次点击
所在节点    Tornado
13 条回复
yangtukun1412
2015-06-17 17:55:32 +08:00
文档里并没有说加了 asynchronous 装饰器的方法不能使用 self.finish(),相反的,加了装饰器后是需要显式调用 finish 方法才会完成请求的。

所以问题还是要看你的 fun1 和 fun2 里面到底做了什么...
wolegequ
2015-06-17 18:03:54 +08:00
@yangtukun1412 fun1 和 fun2 都调用http接口取得数据, 处理完毕再返回给客户端
ltttx
2015-06-17 18:10:19 +08:00
问题在于你的url配置问题,前者的正则匹配太宽泛了
wolegequ
2015-06-17 18:16:46 +08:00
@aiden0xz 此类该如何配置呀,求指点...
wolegequ
2015-06-17 21:50:22 +08:00
wolegequ
2015-06-17 21:53:41 +08:00
@aiden0xz 换行直接回复了....

历史原因导致的....

http://example.com/api/user/uid
http://example.com/api/user/uid/fun
http://example.com/api/user/uid/a
http://example.com/api/user/uid/b

有此类的接口,路由设置貌似没效果
tigerstudent
2015-06-17 23:09:27 +08:00
“客户端两个接口先后几乎同时请求

self.fun1 self.fun2最后都会调用 self.finish(),

于是乎出现了 finish() called twice - - ! ”
按你前面的描述,if else分开的self.fun1 self.fun2怎么会两个都执行?
wolegequ
2015-06-18 01:11:06 +08:00
msg7086
2015-06-18 07:37:44 +08:00
为什么要用(.*)?用([0-9]+)不行吗?
tigerstudent
2015-06-18 08:38:40 +08:00
@wolegequ 两个请求之间不会有冲突!你想歪了!
ltttx
2015-06-18 08:55:16 +08:00
@wolegequ 参考 @msg7086
janxin
2015-06-18 09:15:23 +08:00
url匹配的话,应该是正则写的太松了,导致的匹配问题,一般[0-9a-zA-z]应该能满足需求。
self.finish应该是需要调用的吧,如果是render或者redirect,应该已经调用过self.finish了,不需要显示调用。self.write需要显示调用self.finish。不过我倒是一般用@tornado.gen.corountine
wolegequ
2015-06-19 01:54:43 +08:00
问题已解决, 多谢各位

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/199311

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX