简体   繁体   English

sanic-如何指定所需的JSON?

[英]sanic - How to specify required JSON?

I would like to specify the required JSON for a controller get / post methods in order for it to show in SwaggerUI. 我想为控制器的get / post方法指定所需的JSON,以便使其在SwaggerUI中显示。

For example, I want request.json to look like this: 例如,我希望request.json看起来像这样:

{
  'key1': <int>,
  'key2': <string>
}

I initialize SwaggerUI like this: 我这样初始化SwaggerUI:

from sanic_openapi import swagger_blueprint, openapi_blueprint

app = Sanic(__name__)

# Set up SwaggerUI
app.blueprint(openapi_blueprint)
app.blueprint(swagger_blueprint)

How can I make both keys show up in parameters ? 如何使两个键都显示在parameters 在此处输入图片说明

There is sanic_openapi.doc.consumes decorator for decorating view functions to document their input. sanic_openapi.doc.consumes装饰器,用于装饰视图函数以记录其输入。 This naming of the decorator function follows from the OpenAPI specification . 装饰器函数的命名遵循OpenAPI规范

Here is one way to apply it: 这是一种应用方法:

@app.post('/recording_test')
@doc.summary('Tests a recording')
@doc.consumes({'key1': str, 'key2': int}, location='body')
async def create_recording_test(request):
    ...

You can model your input using a class. 您可以使用类对输入进行建模。

class RecordingTest:
    key1 = str
    key2 = int

Use the modeled input above in the following manner 通过以下方式使用上面的建模输入

@app.post('/recording_test')
@doc.summary('Tests a recording')
@doc.consumes(RecordingTest, location='body')
async def create_recording_test(request):
    ...

You did not see this params in swagger because your get method is on class. 由于您的get方法位于类中,因此您不会大张旗鼓地看到这些参数。 Sanic-openapi and Sanic-swagger does not support class based views yet. Sanic-openapi和Sanic-swagger还不支持基于类的视图。 :( :(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM