tornado的CURD操作

rest api 创建的时候(post),创建成功后把id返回给客户端,客户端就可以通过这个id进行其他操作了

注意post/get风格: 如果针对集合用post /ab/ 而不是 post/ab;如果针对具体实体 get /ab/id

http://technobeans.wordpress.com/2012/09/13/tornado-crud-web-services/

              Resources   HTTP Verbs    Implementation
http://localhost/blog/        POST Creates a blog
http://localhost/blog/id        GET Displays the blog
http://localhost/blog/id        PUT Updates the blog
http://localhost/blog/id      DELETE Deletes the blog
http://localhost/blogs/        GET Lists all the blogs
http://localhost/blogs/       DELETE Deletes all the blogs

下面代码注意handler的初始化函数和它的传参,把外面的connection传进去了,通过url映射的时候的第三个字典参数

# -*- coding: utf-8 -*-

import tornado.ioloop
import tornado.web
import urlparse
from datetime import datetime
from bson.json_util import dumps
 
import pymongo
from pymongo import Connection
 
class Home(tornado.web.RequestHandler):

    def initialize(self, connection):
        self.conn = connection
        self.db = self.conn['blogger']
 
        # Blog's Welcome entry
        timestamp = datetime.now()
        blog = {
                "_id": 1,
                "title": "Welcome blog!",
                "tags": ["hello world"],
                "category": ["welcome"],
                "timestamp": timestamp,
        }
        self.db.blogs.insert(blog)
 
class Blog(Home):

    def get(self, blogid):
        """查看某个blog"""
        blog = self.db.blogs.find_one({"_id":int(blogid)})
        self.set_header('Content-Type', 'application/json')
        self.write(dumps(blog))
        
    def post(self):
        """新建一个blog,***注意,返回给用户有文章id,之后用户可以通过这个id来get等"""
        timestamp = datetime.now()
        body = urlparse.parse_qs(self.request.body)
        for key in body:
                body[key] = body[key][0]
        # 这里要判断title在集合中是否存在,存在就定向到403,不存在就往下执行
        title = body['title']
        if self.db.blogs.find_one({"title":title}):
            raise tornado.web.HTTPError(403)
        # ***生成一个自增的_id
        _id = self.db.blogs.count() + 1
        blog = {
                "_id": _id,
                "title": body['title'],
                "tags": body['tags'],
                "category": body['category'],
                "timestamp": timestamp
        }
        self.db.blogs.insert(blog)
        location = "/blog/"+ str(_id)
        self.set_header('Content-Type', 'application/json')
        self.set_header('Location', location) # 跳转到location这个uri
        self.set_status(201)
        self.write(dumps(blog))
 
    def put(self, blogid):
        """更新(修改)某个blog"""
        _id = int(blogid)
        timestamp = datetime.now()
        body = urlparse.parse_qs(self.request.body)
        for key in body:
                body[key] = body[key][0]
        blog = {
                "title": body['title'],
                "tags": body['tags'],
                "category": body['category'],
                "timestamp": timestamp
        }
        self.db.blogs.update({"_id":_id}, {"$set":blog})
        self.set_header('Content-Type', 'application/json')
        self.write(dumps(blog))
 
    def delete(self,blogid):
        """删除某个blog"""
        _id = int(blogid)
        blog = {
                "title": None,
                "tags": [],
                "category": [],
                "timestamp": None,
        }
        self.db.blogs.remove({"_id":_id})
        self.set_header('Content-Type', 'application/json')
        self.write(dumps(blog))
 
class Blogs(Home):
    def get(self):
        blogs = str(list(self.db.blogs.find()))
        self.set_header('Content-Type', 'application/json')
        self.write(dumps(blogs))
 
    def delete(self):
        blogs = str(list(self.db.blogs.find()))
        self.set_header('Content-Type', 'application/json')
        self.db.blogs.drop()
        self.write(dumps(blogs))
 
application = tornado.web.Application([
    (r"/", Home),
    (r"/blog/([0-9]+)", Blog, dict(connection = Connection()) ), # 注意handler初始化函数传参方式,使用字典
    (r"/blog/", Blog, dict(connection =  Connection()) ),
    (r"/blogs/", Blogs, dict(connection =  Connection()) ),
],debug=True)
 
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

测试代码

import httplib2
from urllib import urlencode
import tornado.escape
import tornado.httpclient
 
http = httplib2.Http()
 
print "\nView welcome blog - GET"
headers, content = http.request("http://localhost:7777/blog/1", "GET")
print "Response:", tornado.escape.json_decode(content)
print "Headers:", headers
 
 
print "\nCreate new blog - POST"
tags = ['python', 'web']
category = ['www']
data = {'title':'Tornado Web Server', 'tags': tags, 'category':category}
body = urlencode(data)
headers, content = http.request("http://127.0.0.1:7777/blog/", "POST", body=body)
print "Response:", tornado.escape.json_decode(content)
print "Headers:", headers
 
print "\nView all blogs - GET"
headers, content = http.request("http://localhost:7777/blogs/", "GET")
print  "Response:", tornado.escape.json_decode(content)
print "Headers:", headers
 
print "\nUpdate blog - PUT"
title = "mongo"
tags = ['python', 'DB']
category = ['db']
data = {'title': title, 'tags': tags, 'category':category}
body = urlencode(data)
headers, content = http.request("http://127.0.0.1:7777/blog/2", "PUT", body=body)
print "Response:", tornado.escape.json_decode(content)
print "Headers:", headers
 
print "\nDeactivate blog - DELETE"
headers, content = http.request("http://127.0.0.1:7777/blog/2", "DELETE")
print "Response:", tornado.escape.json_decode(content)
print "Headers:", headers
 
print "\nView all blogs - GET"
headers, content = http.request("http://localhost:7777/blogs/", "GET")
print "Response:",tornado.escape.json_decode(content)
print "Headers:", headers
 
print "\nClear all blogs - DELETE"
http = httplib2.Http()
headers, content = http.request("http://127.0.0.1:7777/blogs/", "DELETE")
print "Response:", tornado.escape.json_decode(content)
print "Headers:", headers













你可能感兴趣的:(tornado的CURD操作)