这是一个很简单的博客系列,太长了似乎也不合适。
最后的代码可以见https://github.com/phodal/falcon-wordpress
我们还要做的就是建一个RESTful Server,有了前面的基础剩下的事情已经很简单了。
在我们的server.py
大概有下面的内容:
import falcon
from gevent import monkey
from gevent.wsgi import WSGIServer
from api.resources import PostsResource, AllPostsResource, CommentsResource, PostsCommentsResource
def main():
monkey.patch_thread()
api = falcon.API()
api.add_route('/posts/{post_id}', PostsResource())
api.add_route('/posts/{post_id}/comments', PostsCommentsResource())
api.add_route('/comment/{comment_id}', CommentsResource())
api.add_route('/all/posts', AllPostsResource())
server = WSGIServer(('0.0.0.0', 8000), api)
server.serve_forever()
gevent在这里的目的就是为了和gunicorn一起使用,方便部署。
简单地看一下依照ID取posts
class PostsResource():
def __init__(self):
pass
@staticmethod
def on_get(req, resp, post_id):
post = WpPosts.get(WpPosts.id == post_id)
user = WpUsers.get(WpUsers.id == post.post_author)
resp.status = falcon.HTTP_200
resp.body = json.dumps({"post_content": post.post_content,
"author": user.display_name})
过程似乎就是这么简单,因为构建一个RESTful Services不是一件很麻烦的事,当你已经选好框架、语言、数据库的时候。
Run
gunicorn server:app -k gevent
围观我的Github Idea墙, 也许,你会遇到心仪的项目