下面的實驗主要來自[1][2],但是對實驗2的代碼進行了修改,修改過程參考了[3]
#---------------------------------------------------實驗1-------------------------------------------------------------------
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
class HelloHandler(RequestHandler):
def get(self):
self.write({'message': 'hello world'})
def make_app():
urls = [("/", HelloHandler)]
return Application(urls, debug=True)
if __name__ == '__main__':
app = make_app()
app.listen(3000)
IOLoop.instance().start()
python test1.py
**************************************************************
GET請求測試:
GET請求結果:
#---------------------------------------------------實驗2-----------------獲取post請求中的json數據--------------------------------------------------
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
import json
items = ['csdn']
class TodoItems(RequestHandler):
def get(self):
self.write({'items': items})
class TodoItem(RequestHandler):
def post(self):
# items.append(self.request.body)
print("-----------------進入post----------------")
print(self.request)
print("--------------self.write之前------------------")
jsonbyte = self.request.body
jsonstr = jsonbyte.decode('utf8') #解碼,二進制轉爲字符串
print('Json字符串:', jsonstr)
jsonobj = json.loads(jsonstr) #將字符串轉爲json對象
# self.write({'message': self.request.body})
self.write(jsonobj)
def make_app():
urls = [
("/", TodoItems),
("/api/item/", TodoItem)
]
return Application(urls, debug=True)
if __name__ == '__main__':
app = make_app()
app.listen(3000)
IOLoop.instance().start()
python test2.py
**************************************************************
GET請求測試:
瀏覽器打開:
http://127.0.0.1:3000/
GET請求結果:
**************************************************************
POST請求測試:
curl -H "Content-Type: application/json" -X POST -d '{"user_id": "123", "coin":100, "success":1, "msg":"OK!" }' "http://127.0.0.1:3000/api/item/"
POST請求結果:
{"user_id": "123", "coin": 100, "success": 1, "msg": "OK!"}
#----------------------------------------實驗3-----------------------------curl發送delete請求---------------------------------------------------------
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
import json
items = []
class TodoItems(RequestHandler):
def get(self):
self.write({'items': items})
class TodoItem(RequestHandler):
def post(self, _):
items.append(json.loads(self.request.body))
self.write({'message': 'new item added'})
def delete(self, id):
global items
new_items = [item for item in items if item['id'] is not int(id)]
items = new_items
self.write({'message': 'Item with id %s was deleted' % id})
def make_app():
urls = [
("/", TodoItems),
(r"/api/item/([^/]+)?", TodoItem)
]
return Application(urls, debug=True)
if __name__ == '__main__':
app = make_app()
app.listen(3000)
IOLoop.instance().start()
python test3.py
***********************************************
GET請求測試:
GET請求測試結果:
***********************************************
POST請求測試:
curl -H "Content-Type: application/json" -X POST -d '{"user_id": "123", "coin":100, "success":1, "msg":"OK!" }' "http://127.0.0.1:3000/api/item/342"
POST請求測試結果:
{"message": "new item added"}
***********************************************
DELETE請求測試:
curl -v -X DELETE 127.0.0.1:3000/api/item/342
DELETE請求測試結果:
{"message": "Item with id 342 was deleted"}
#---------------------------------------------------------結束--------------------------------------------------------------------------
Reference:
[1]How to build a REST API in Python with Tornado (part 1)