pyswagger

作者: 12plus12 | 来源:发表于2018-12-11 18:02 被阅读0次

    原文github地址

    初始化

    使用pyswagger的第一步是创建一个pyswagger.App对象。需要提供资源文件的路径。例如,petstore的App可以这样初始化:

    from pyswagger import App
    
    # 使用 App.create
    app = App.create('http://petstore.swagger.io/v2/swagger.json')
    

    或者用本地文件初始化

    该路径可以是URI或绝对路径。例如,路径/home/workspace/local/ swagger.json可以像这样传递:

    from pyswagger import App
    
    # file URI
    app = App.create('file:///home/workspace/local/swagger.json')
    # with hostname
    app = App.create('file://localhost/home/workspace/local/swagger.json')
    # absolute path
    app = App.create('/home/workspace/local/swagger.json')
    # without the file name, because 'swagger.json' is a predefined name(不知道在哪儿预定义?)
    app = App.create('/home/workspace/local')
    

    发起请求

    发起请求涉及三个部分:

    • 获取operation对象
    • operation对象传参,它将返回(Request, Response)
    • 将此对(Request, Response)提供给您选择的client implementation实现(注:client implementation我不知道怎么确切的翻译,所以用了原文,我的理解就是实例对象)

    访问operation对象
    有许多方法可以访问operation对象。例如,如果要访问petstore中的“getUserByName”:

    from pyswagger import App
    
    app = App.create('http://petstore.swagger.io/v2/swagger.json')
    
    # 1.通过tags和operationId
    op = app.op['getUserByName']         # 如果operationId是唯一的
    op = app.op['user', 'getUserByName'] # tag + operationId
    
    # 2.通过JSON Pointer, Swagger中的每个对象都可以通过它的JSON Pointer来引用。
    # 操作“getUserByName”的JSON Pointer为“#/paths/~1user~1{username}/get”,
    # pyswagger提供了一种简单的方法来处理JSON Pointer
    from pyswagger import utils
    # 检查petstore中“getUserByName”操作的位置
    op = app.resolve(utils.jp_compose(['#', 'paths', '/user/{username}', 'get']))
    
    # 也可以分步来写
    username_api = app.resolve(utils.jp_compose(['#', 'paths', '/user/{username}']))
    op = username_api.resolve('get')
    # 'get'中没有特殊字符,可以用获取属性的方式来获取
    op = username_api.get
    

    传参
    这个步骤涉及到将python中的原语转换为Swagger中的原语,请参阅这里的Swagger原语列表。

    # 这是一个包含了所有种类的原语的伪操作
    op = app.op['FakeApi']
    
    req_and_resp = op(
      # integer, long, 
      Id=1,
      # float, double
      speed=27.3,
      # string
      name='Tom',
      # byte
      raw=b'fffffffffff',
      # byte, in string, would be encoded to 'utf-8'
      raw_s='jdkjldkjlsdfs',
      # boolean
      like_suki=True,
      # date, datetime, in timestamp
      next_date_1=0.0,
      # date, in datetime.date
      next_date_2=datetime.date.today(),
      # datetime, in datetime.datetime
      next_date_3=datetime.datetime.now(),
      # date, in string ISO8601
      next_date_4='2007-04-05',
      # datetime, in string ISO8601
      next_date_5='2007-04-05T12:30:00-02:00',
      # array of integer
      list_of_ids=[1, 2, 3, 4, 5],
      # an object
      user=dict(id=1, username='Tom'),
      # list of objects
      users=[
        dict(id=1, username='Tom'),
        dict(id=2, username='Mary')
      ]
    )
    

    给client传递返回的结果
    调用Operation时返回的值是一对(Request, Response),只需将其传递给clientrequest函数即可。下面是“getUserByName”的完整示例:

    from pyswagger import App
    from pyswagger.contrib.client.requests import Client
    
    app = App.create('/path/to/your/resource/file/swagger.json')
    client = Client()
    
    # make the request
    response = client.request(
      app.op['getUserByName']( # access the Operation
        username='Tom'         # provide the parameter
      ))
    

    使用响应(需重翻)

    每个client implementationrequest方法的返回值是pyswagger.io.Response对象。您需要通过请求的接口访问它的结果(注意:此示例要求在环境中装好 requests库)

    from pyswagger import App
    from pyswagger.contrib.client.requests import Client
    
    app = App.create('/path/to/your/resource/file/swagger.json')
    client = Client()
    
    # making a request
    resp = client.request(app.op['getUserByName'](username='Tom'))
    
    # Status
    assert resp.status == 200
    
    # Data
    # it should return a data accord with '#/definitions/User' Schema object
    assert resp.data.id == 1
    assert resp.data.username == 'Tom'
    # Raw
    assert resp.raw == '{"id": 1, "username": "Tom"}'
    
    # To disable parsing of body parameter, and handle 'raw' on your own.
    resp.raw_body_only = True
    assert resp.data == None
    
    # Header
    # header is a dict, its values are lists of values,
    # because keys in HTTP header allow duplication.
    #
    # when the input header is:
    # A: 1,
    # A: 2,
    # B, 1
    assert sorted(resp.header['A']) == [1, 2]
    assert resp.header['B'] == [1]
    

    测试本地服务器(待重翻)

    作为后端开发人员,您需要在交付之前测试API。我们提供了一种在客户端发出请求之前修补url的简单方法。(注意:此示例要求在环境中装好 requests库)

    from pyswagger import App
    from pyswagger.contrib.client.request import Client
    
    # create a App with a local resource file
    app = App.create('/path/to/your/resource/file/swagger.json')
    # init the client
    client = Client()
    
    # try to making a request
    client.request(
      app.op['getUserByName'](username='Tom'),
      opt=dict(
        url_netloc='localhost:8001' # patch the url of petstore to localhost:8001
      ))
    

    相关文章

      网友评论

          本文标题:pyswagger

          本文链接:https://www.haomeiwen.com/subject/dpkdhqtx.html