Tornado构建RESTful应用

RESTful

  • Representational State Transfer:表中状态转移
  • 资源(Resources),表现层(Representation),状态转化(State Transfer)

RESTful风格

  • Resources(资源):使用URI指向的一个实体
  • Representation(表现层):资源的表现形式,比如图片、HTML文本等
  • State Transfer(转态转化):GET、POST、PUT、DELETE HTTP动词来操作资源

常用HTTP动词

  • RESTful解释
    • GET/POST/PUT/DELETE分别用来 获取/新建/更新/删除 资源
    • 幂等性:GET/PUT/DELETE是幂等操作(无论操作多少次都是获得同样的数据,幂等的可以放心的多次请求,非幂等就要注意)
    • 幂等指的是无论一次还是多次操作具有一样的副作用

Tornado RESTful Api示例

HTTP方法 URL 动作
GET http://[hostname]/api/users 检索用户列表
GET http://[hostname]/api/users/[user_id] 检索单个用户
POST http://[hostname]/api/users 创建新用户
PUT http://[hostname]/api/users/[user_id] 更新用户信息
DELETE http://[hostname]/api/users/[user_id] 删除用户

简单实现

  • 使用Tornado实现Restful Api
    • Tornado适合构建RESTful微服务
    • 实现UserModel
    • 实现UserListRequesthandler和UserRequestHandler

相关代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# models/user.py
class UserModel(object):
users = {
1: {'name': 'zhang', 'age': 10},
2: {'name': 'wang', 'age': 12},
3: {'name': 'li', 'age': 14},
4: {'name': 'zhao', 'age': 11},
}

@classmethod
def get(cls, user_id):
return cls.users[user_id]

@classmethod
def get_all(cls):
return list(cls.users.values())

@classmethod
def create(cls, name ,age):
user_dict = {'name': name, 'age': age}
max_id = max(cls.users.keys()) + 1
cls.users[max_id] = user_dict

@classmethod
def update(cls, user_id, age):
cls.users[user_id]['age'] = age

@classmethod
def delete(cls, user_id):
if user_id in cls.users:
return cls.users.pop(user_id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# handlers/user.py
import tornado.web
from tornado.escape import json_encode
from models.user import UserModel

class UserListHandler(tornado.web.RequestHandler):
def get(self):
users = UserModel.get_all()
self.write(json_encode(users))

def post(self):
name = self.get_argument('name')
age = self.get_argument('age')
UserModel.create(name, age)
resp = {'status': True, 'msg': 'create success'}
self.write(json_encode(resp))

class UserHandler(tornado.web.RequestHandler):
def get(self, user_id):
try:
user = UserModel.get(int(user_id))
except KeyError:
return self.set_status(404)
self.write(json_encode(user))

def put(self, user_id):
age = self.get_argument('age')
UserModel.update(int(user_id), age)
resp = {'status': True, 'msg': 'update success'}
self.write(json_encode(resp))

def delete(self, user_id):
UserModel.delete(int(user_id))
resp = {'status': True, 'msg': 'delete success'}
self.write(json_encode(resp))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# app.py
import tornado.web
from handlers import user as user_handlers

HANDLERS = [
(r"/api/users", user_handlers.UserListHandler),
(r"/api/users/(\d+)", user_handlers.UserHandler)
]

def run():
app = tornado.web.Application(
HANDLERS,
debug=True,
)
http_server = tornado.httpserver.HTTPServer(app)
port = 8888
http_server.listen(port)
print('Server start on port {}'.format(port))
tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
run()
-------------本文结束感谢您的阅读-------------
原创技术分享,感谢您的支持。