python3 和 python2 系列的用法

2014-11-23 14:02:06 +08:00
 p8p8
'''python3 下面这样写没有问题'''

db = momoko.Pool(dsn='dbname=%s user=%s' % (config.db.database, config.db.user), size=2)

@tornado.gen.coroutine
def execute(self, query, *args):
result = yield momoko.Op(self.db.execute, query, args, cursor_factory=psycopg2.extras.DictCursor)
return result


python2 下面会提示 python version < 3.3 do not allow 'return' .....

所以我把


@tornado.gen.coroutine
def execute(self, query, *args):
result = yield momoko.Op(self.db.execute, query, args, cursor_factory=psycopg2.extras.DictCursor)
return result


return result 直接去掉,写了一个 self.finish()


然后另外一个地方直接这样调用

@gen.coroutine
def get(self):
query = 'INSERT INTO public.user (name, password) VALUES (%s, %s);'
try:
yield self.execute(query,'sss','333')
except (psycopg2.Warning, psycopg2.Error) as error:
self.write(str(error))
self.finish()


这样会有问题么??
4072 次点击
所在节点    Python
7 条回复
ryd994
2014-11-23 14:20:39 +08:00
return()吧
ryd994
2014-11-23 14:22:13 +08:00
我错了,没事了
p8p8
2014-11-23 14:22:39 +08:00
@ryd994 return()吧 ??

result = yield momoko.Op(self.db.execute, query, args, cursor_factory=psycopg2.extras.DictCursor)
return result

这里改成

result = yield momoko.Op(self.db.execute, query, args, cursor_factory=psycopg2.extras.DictCursor)
return()

这样吗?

我怎么感觉你的回答好虚啊。。。不过还是谢谢你。
p8p8
2014-11-23 14:23:06 +08:00
@ryd994 哈哈哈,没事,大家一起学习进步!
iceout
2014-11-23 14:28:27 +08:00
http://tornado.readthedocs.org/en/branch3.2/gen.html#decorators
文档中写了。。。

Coroutines may “return” by raising the special exception Return(value).In Python 3.3+, it is also possible for the function to simply use the return value statement (prior to Python 3.3 generators were not allowed to also return values).
p8p8
2014-11-23 14:52:17 +08:00
@iceout 嗯,然后呢?2系列中应该怎么用呢?
iceout
2014-11-23 19:00:10 +08:00
@p8p8 第一句。。raise exception

文档中的例子:

@gen.coroutine
def fetch_json(url):
response = yield AsyncHTTPClient().fetch(url)
raise gen.Return(json_decode(response.body))

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

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

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

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

© 2021 V2EX