[新手开源] 使用 Tornado 搭建 RESTful 接口服务

2016-01-21 01:18:01 +08:00
 nekocode

作为一个「人生苦短,我用 Python 」的程序员,最近毅然决然地决定使用 Tornado 搭建一个社交应用的服务后端。现在在开发途中积累了很多不错的东西,打算分享给有这方面需求的人。

我在开发该社交应用(图片问答社区)中,使用了以下一些工具:
Tornado , MongoDB , Redis , Qiniu , MQTT

说实话, MongoDB 真的挺适合储存社交数据的,不过 Tornado 下真的缺乏一款好用的 MongoDB 的 ORM 框架, Motor Engine 还缺乏很多功能。不知道有没有大牛能够推荐一下。

另外就是目前在实现用户 Feeds 时有些停顿,目前仍在研究如何处理会好一些,也希望有经验的大牛能提供下好的意见。

去掉大部分的业务逻辑的壳,需要的拿去,也欢迎 Star , PR :
TornaREST . Github

11141 次点击
所在节点    Python
32 条回复
zhuf
2016-01-22 11:22:08 +08:00
mongoengine 啊
nekocode
2016-01-22 11:32:06 +08:00
@latyas 实现起来太麻烦了。

@phithon https://motor.readthedocs.org/en/latest/index.html

@zhuf mongoengine 不是非阻塞的。 motorengine 是 mongoengine 针对 tornado 的 port 版本。
neoblackcap
2016-01-22 12:10:54 +08:00
@phithon 要不就是多线程 /多进程池,要不就是消息队列。再来就是 microservice ,然后用 AsyncHttpClient 调用。

PS :毕竟数据库操作都是 IO 密集型,因此用多线程也是可以的。
fhefh
2016-01-22 14:43:24 +08:00
学习了 mark
SaberSalv
2016-01-22 15:41:11 +08:00
为什么都喜欢绑定? 比如我不想用 MongoDB 怎么办?
nekocode
2016-01-22 15:58:02 +08:00
@SaberSalv 很抱歉,我并没有把它做成可拆卸的,想使用 MySQL 的话必须自己修改代码(推荐使用 torndb )。我写它的出发点在于创建一个提供社交接口的高性能的后端,所以在栈选择上比较极端。
phithon
2016-01-22 17:50:41 +08:00
@nekocode
这个并不是 orm 呀。。。我写的一个项目就是用的 motor https://github.com/phith0n/Minos
nekocode
2016-01-22 18:21:40 +08:00
@phithon
需要 ORM 的话可以看看这个: https://github.com/heynemann/motorengine
我在代码里面就是使用它的,具体可以查阅我的 Github Repo
phithon
2016-01-22 18:43:53 +08:00
@nekocode 已关注~
anson008
2016-01-23 11:17:00 +08:00
https://github.com/PyMySQL/Tornado-MySQL
我目前一个 websocket 项目中用的 tornado+异步 mysql db 读写
希望和大家多多交流
latyas
2016-01-25 13:08:27 +08:00
@nekocode 不麻烦

from concurrent.futures import ThreadPoolExecutor

tpool = ThreadPoolExecutor()

asyncio 的话 await asyncio.wrap_future(tpool.submit(target, *args, **kwargs)) 即可,
tornado 也有用 concurrent 库的接口。
withrock
2016-02-01 19:24:27 +08:00
@gen.coroutine
13 def get_all_gallerys():
14 gallery_path = "/mnt/F/Picture"
15 gallerys = []
16 for item in os.listdir(gallery_path):
17 if not os.path.isdir(item):
18 continue
19 gallery = dict(
20 name = item,
21 path = os.path.join(gallery_path, item)
22 )
23 gallerys.append(gallery)
24 raise gen.Return(gallerys)
25
26 class GalleryHandler(BaseHandler):
27 def data_received(self, chunk):
28 pass
29
30 @tornado.web.asynchronous
31 @gen.coroutine
32 def get(self):
33 ret = yield get_all_gallerys()
34 print ret
35 self.write_json(ret)


@nekocode
请问这样调用,想在这个 handle 里返回一个目录下的所有文件夹,但是返回的消息却是
{"msg": "success.", "code": 200, "data": []}
后台没有打印报错信息
只是: 304 GET /api/photo/gallerys (::1)
请问这样该怎么办呢?

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

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

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

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

© 2021 V2EX