ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Tornado-REST - 快速创建你的网络APIs

2020-07-08 20:36:23  阅读:301  来源: 互联网

标签:customer name APIs Tornado self REST API address id


目录

学习这篇文章之前,你需要:

  • 清楚RESTful风格的含义(了解即可,Demo会带你切身体验)
  • 明白Tornado是什么(对,不需要开发经验)

学习完本文后,你可以

  • 使用Tornado框架,快速构建REST-APIs
  • 实现一个CRUD(Create, Read, Update and Delete)操作流程

1. PyRestful库

github

一个基于Tornado框架、用于实现RESTful风格的API接口的Python组件。实际上,它主要提供了

  • @get
  • @post
  • @put
  • @delete

四个装饰器,用于定义一个method()的REST类型。

这里是一个简单的Demo,告诉你它是什么(关注@get即可)。

import tornado.ioloop
import pyrestful.rest

from pyrestful import mediatypes
from pyrestful.rest import get

class EchoService(pyrestful.rest.RestHandler):
     @get(_path="/echo/{name}", _produces=mediatypes.APPLICATION_JSON)
     def sayHello(self, name):
          return {"Hello":name}

if __name__ == '__main__':
     try:
          print("Start the echo service")
          app = pyrestful.rest.RestService([EchoService])
          app.listen(8080)
          tornado.ioloop.IOLoop.instance().start()
     except KeyboardInterrupt:
          print("\nStop the echo service")

2. 安装

两种安装方式

pip install pyrestful

或者

pip install -U git+https://github.com/rancavil/tornado-rest.git

3. 使用: a demo for CRUD

这里以官方的Demo作为演示。

目标:设计一个Http服务端,用于学生信息的记录。需要提供 增、删、改、查 四大功能。

预定义两个类:

  • class Customer : 学生对象
  • CustomerDataBase : 数据库接口

定义一个Http的Handler,继承自 pyrestful.rest.RestHandler :

class CustomerResource(pyrestful.rest.RestHandler):
    def initialize(self, database):
        self.database = database

3.1. Creating a new Customer

POST it is equivalent to INSERT.

使用post方法,传入一个新的学生信息。服务器接受到学生信息后存入数据库。

API接口的描述:

POST: http://myserver.domain.com:8080/customer

POST /customer HTTP/1.1
Host: myserver.domain.com

params:
* name_customer=Rodrigo
* address_customer=Santiago

服务端API代码

@post(_path="/customer", _types=[str,str], _produces=mediatypes.APPLICATION_JSON)
def createCustomer(self, name_customer, address_customer):
    id_customer = self.database.insert(name_customer, address_customer)
    response = {"created_customer_id": id_customer}
    return response

测试:

  • 使用 PostWoman 测试API

  • 使用 httplib 发起请求

    import http.client as httplib
    import urllib.parse as urllib
    
    params  = urllib.urlencode({'name_customer':name_customer,'address_customer':address_customer})
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    conn    = httplib.HTTPConnection("localhost:8080")
    
    conn.request('POST','/customer',params,headers)
    
    resp = conn.getresponse()
    data = resp.read()
    if resp.status == 200:
        json_data = json.loads(data.decode('utf-8'))
        print(json_data)
    else:
        print(data)
    

3.2. Read a Customer

GET it is equivalent to SELECT (READ).

使用get方法,获取数据库中一个学生信息。

API接口的描述:

GET: http://myserver.domain.com:8080/customer/{id}

GET /customer/1 HTTP/1.1

服务端API代码

@get(_path="/customer/{id_customer}", _types=[int], _produces=mediatypes.APPLICATION_JSON)
def getCustomer(self, id_customer):
    customer = self.database.find(id_customer)

    response = {
        'id_customer'     : customer.getId_Customer(),
        'name_customer'   : customer.getName_Customer(),
        'address_customer': customer.getAddress_Customer()
    }
    return response

3.3. Update a Customer

PUT it is equivalent to UPDATE.

API接口的描述:

PUT: http://myserver.domain.com:8080/customer/{id}

PUT /customer/1 HTTP/1.1
Host: myserver.domain.com

params:
* name_customer=Rodrigo
* address_customer=Santiago

服务端API代码

@put(_path="/customer/{id_customer}", _types=[int,str,str], _produces=mediatypes.APPLICATION_JSON)
def updateCustomer(self, id_customer, name_customer, address_customer):
    updated = self.database.update(id_customer,name_customer,address_customer)
    response = {
        "updated_customer_id": id_customer,
        "success":updated
    }
    return response

3.4. Delete a Customer

API接口的描述:

DELETE: http://myserver.domain.com:8080/customer/{id}

DELETE /customer/1 HTTP/1.1

服务端API代码

@delete(_path="/customer/{id_customer}", _types=[int], _produces=mediatypes.APPLICATION_JSON)
def deleteCustomer(self,id_customer):
    deleted = self.database.delete(id_customer)
    response = {
        "delete_customer_id": id_customer,
        "success":deleted
    }
    return response

标签:customer,name,APIs,Tornado,self,REST,API,address,id
来源: https://www.cnblogs.com/brt2/p/13269081.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有