sanic-org / sanic-openapi Goto Github PK
View Code? Open in Web Editor NEWEasily document your Sanic API with a UI
Home Page: https://sanic-openapi.readthedocs.io/
License: MIT License
Easily document your Sanic API with a UI
Home Page: https://sanic-openapi.readthedocs.io/
License: MIT License
I have a static route as follows
app.static('/robots.txt', './static/robots.txt')
It gets documented with swagger and there is no way to set @doc.exclude(True) for it.
If I create an endpoint of "/", it appears in the swagger UI once as expected, i.e.;
blueprint = Blueprint('Authentication')
@blueprint.get("/")
@doc.summary('Get a list of all users')
@doc.produces(Status)
async def get_users(request, user):
return json({'success': True})
If however the endpoint is anything other than "/" , or if I include a prefix in the blue print definition, then I end up getting TWO entries in my swagger UI, i.e;
blueprint = Blueprint('Authentication', '/auth')
@blueprint.get("/")
@doc.summary('Get a list of all users')
@doc.produces(Status)
async def get_users(request, user):
return json({'success': True})
Both swagger entries work, but one is listed with a trailing "/" on the URL, and the other is listed without. Is there something I need to do to suppress the additional entry?
Note; it's ONLY "GET" operations that are subject to this issue, post, put, and delete only appear once as one would expect ...
@doc.summary("This is my view's getter")
async def get(self, _):
return response.json({'foo': []})
Does not include the summary.
this is my create_app method:
from sanic import Sanic
from sanic_openapi import swagger_blueprint, openapi_blueprint
def create_app():
app = Sanic(__name__)
app.blueprint(openapi_blueprint)
app.blueprint(swagger_blueprint)
from .api import v1
app.blueprint(v1)
return app
/swagger page can't load the resources. It tries to get them from: http://localhost:8000/css/typography.css
but actually they are at
http://localhost:8000/swagger/css/typography.css
Am I doing something wrong?
Hello ! , thank for all your job
unfortunately your last big version do not work with sanic 18.12.0
I have theses Exceptions :
ERROR:sanic.root:Exception occurred while handling uri: 'http://localhost:8000/swagger-ui.css'
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/sanic/app.py", line 736, in handle_request
handler, args, kwargs, uri = self.router.get(request)
File "/usr/local/lib/python3.6/site-packages/sanic/router.py", line 396, in get
return self._get(request.path, request.method, "")
File "/usr/local/lib/python3.6/site-packages/sanic/router.py", line 458, in _get
raise NotFound("Requested URL {} not found".format(url))
sanic.exceptions.NotFound: Requested URL /swagger-ui.css not found
[2019-04-02 13:53:19 +0000] - (sanic.access)[INFO][10.102.52.1:40210]: GET http://localhost:8000/swagger-ui.css 404 46
INFO:sanic.access:
[2019-04-02 13:53:19 +0000] [1] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/swagger-ui-bundle.js'
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/sanic/app.py", line 736, in handle_request
handler, args, kwargs, uri = self.router.get(request)
File "/usr/local/lib/python3.6/site-packages/sanic/router.py", line 396, in get
return self._get(request.path, request.method, "")
File "/usr/local/lib/python3.6/site-packages/sanic/router.py", line 458, in _get
ERROR:sanic.root:Exception occurred while handling uri: 'http://localhost:8000/swagger-ui-bundle.js'
Should I rollback to 0.4.0 ?
thank you again
Hi.
Any chance to include the securityDefinitions section?
Also, is there a way to define the parameters, defining if they are from URL query part, form, body, etc?
@app.route('/index_post/', methods=['POST'])
@doc.route(summary='Returns an indexed post',
description='does the index thing',
consumes={"user": str},
consumes_content_type='application/json')
async def tester(request):
if not request.json:
return response.HTTPResponse(status=400)
return response.json({'user': request.json.get('user')})
This doesn't allow the server to start, something with how the consumes argument is assigned.
here is error log
$ pip install sanic-openapi
Collecting sanic-openapi
Using cached sanic-openapi-0.1.5.tar.gz
Requirement already satisfied (use --upgrade to upgrade): sanic>=0.3.0 in ./venv/lib/python3.5/site-packages (from sanic-openapi)
Requirement already satisfied (use --upgrade to upgrade): uvloop>=0.5.3 in ./venv/lib/python3.5/site-packages (from sanic>=0.3.0->sanic-openapi)
Requirement already satisfied (use --upgrade to upgrade): httptools>=0.0.9 in ./venv/lib/python3.5/site-packages (from sanic>=0.3.0->sanic-openapi)
Requirement already satisfied (use --upgrade to upgrade): ujson>=1.35 in ./venv/lib/python3.5/site-packages (from sanic>=0.3.0->sanic-openapi)
Requirement already satisfied (use --upgrade to upgrade): aiofiles>=0.3.0 in ./venv/lib/python3.5/site-packages (from sanic>=0.3.0->sanic-openapi)
Installing collected packages: sanic-openapi
Running setup.py install for sanic-openapi ... error
Complete output from command $PROJECT_PATH/venv/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/private/var/folders/g8/9ff4t0k52rvdfrh8vgg7kjq40000gn/T/pip-build-wupv41gv/sanic-openapi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/g8/9ff4t0k52rvdfrh8vgg7kjq40000gn/T/pip-hipmbyu3-record/install-record.txt --single-version-externally-managed --compile --install-headers $PROJECT_PATH/venv/include/site/python3.5/sanic-openapi:
running install
running build
running build_py
creating build
creating build/lib
creating build/lib/sanic_openapi
copying sanic_openapi/__init__.py -> build/lib/sanic_openapi
copying sanic_openapi/doc.py -> build/lib/sanic_openapi
copying sanic_openapi/openapi.py -> build/lib/sanic_openapi
copying sanic_openapi/swagger.py -> build/lib/sanic_openapi
creating build/lib/sanic_openapi/ui
error: can't copy 'sanic_openapi/ui/css': doesn't exist or not a regular file
----------------------------------------
Command "$PROJECT_PATH/venv/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/private/var/folders/g8/9ff4t0k52rvdfrh8vgg7kjq40000gn/T/pip-build-wupv41gv/sanic-openapi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/g8/9ff4t0k52rvdfrh8vgg7kjq40000gn/T/pip-hipmbyu3-record/install-record.txt --single-version-externally-managed --compile --install-headers $PROJECT_PATH/venv/include/site/python3.5/sanic-openapi" failed with error code 1 in /private/var/folders/g8/9ff4t0k52rvdfrh8vgg7kjq40000gn/T/pip-build-wupv41gv/sanic-openapi/
code:
@app.route("/new_moment/<uid:int>",methods=["POST"])
@doc.consumes({
"type":int,
"res_json":str,
"words":str,
"location":str
})
def test():
download the "spec.json" file and find the method parameters description:
"post":{"parameters":[{"format":"int64","in":"path","required":true,"type":"integer","name":"uid"},{"in":"body","name":"body","properties":{"res_json":{"type":"string"},"location":{"type":"string"},"words":{"type":"string"},"type":{"format":"int64","type":"integer"}},"type":"object"}]
so . firstly I want to konw the parameters format is correct ? secondly I want to konw where I can find the "spec.json" datas standard description . thanks.
By setting global configuration option strict_slashes
to True I would expect to swagger documentation no to have duplicate entries that differentiate only in trailing slash. Example:
app = sanic.Sanic(strict_slashes=True)
test_blueprint = sanic.Blueprint("test")
# no strict_slashes here
@test_blueprint.route("/test", methods=["GET"])
def test(request):
return "Hello world"
app.blueprint(swagger_blueprint)
app.blueprint(test_blueprint)
I'd assume using doc.produces({...})
would have something show up in the UI but nothing is showing up.
Hi.
Tried a couple of things and @doc.consumes & @doc.produces isn't working.
Could it be related to using sanic's blueprints?
Will try and have a look myself if I have some time.
CG
I'm on version 0.4.0 and my swagger UI doesn't seem to show a body textarea where I can modify the body when trying out an API endpoint.
You can resproduces this (hopefully) by copying the /user
endpoint from the readme file:
@app.post("/user")
@doc.summary("Creates a user")
@doc.consumes({"user": { "name": str }}, location="body")
async def create_user(request):
...
When you click "Try it out" on the /user
endpoint on the Swagger UI, you can't modify the body. Because of this, you can't even execute the call if you make the input a required field.
Even though document calls are only done in a blueprint, say a blue print with url prefix /bp/, swagger goes ahead and documents everything including routes in the root.
Is there a way to register or restrict the documenting for only the blueprint prefix?
@DirkGuijt #58 using relative link has caused a small side effect.
testing using (latest) swagger 3.18.3 seems to work using "./" prefix as suggested in issue above. So quick fix is to upgrade from 3.9.2 I guess
How does one specify description for headers? For example in:
@blueprint.post("/comment", strict_slashes=True)
@doc.summary("GitHub comment parser")
@doc.description("Handle GitHub comment events")
@doc.consumes({'X-Hub-Signature': str}, location='header', required=True)
@authorized(os.environ.get('GITHUB_S2S_SECRET', None))
async def githubCommentHandler(request):
return json({'msg': 'processed'})
l fond the default response is 200.now l want set more response. so, l wish
from sanic_openapi import doc
@doc.response(204,'the is new response)
The latest release contains at least one show-stopping bug (#50), and contains other errors. Meanwhile, there are 12 pull requests which have been sitting unmerged (and likely not even reviewed) for months.
It seems that @Typhon66 can no longer maintain this project. Is it possible to add another maintainer to the project and at least merge all the working PRs? I cannot dedicate a significant amount of time to this, but I would be willing to at least merge the PRs.
If @Typhon66 and @channelcat are not active, and cannot add another maintainer, the repository should probably be forked.
There should be a way to configure custom (not 200) status code in response like in flask-restplus:
from flask_restplus import Namespace
ns = Namespace('Wallet')
...
@ns.response(201, 'Wallet created')
...
@ns.response(404, 'Wallet not found')
something like:
@doc.response(404, 'Wallet not found')
This project looks in need of some assistance. There are several open PRs with some greatly needed fixes. Willing to assist as needed.
Hi, can someone tell me whether there is an easy way of documenting path parameters, it seems to be eluding me if it's there .. for example;
@warc_blueprint.get('/open/<file_name:string>', strict_slashes=True)
@doc.summary('Open a connection to a file')
async def open_get(request, file_name) ...
Essentially I'm looking to be able to associate a description with "file_name" so I can display it on the Swagger UI next to the name/type .. (?) Maybe something like this;
@doc.parameter('file_name', 'The name of the file to open')
Is there a way to override the swagger-ui CSS?
Is it possible to exclude some urls from the docs?
Hi,
We plan to document our API with sanic-openapi
, I'm currently implementing some tooling for it. We tried to reuse some consumed/produced model definitions in the doc of multiple API endpoints, but it turns out reusing the same class wrapped in different doc.Object
instances is not supported by the framework, even if object_name
is different in every case.
Would it be possible to register Object
instances in definitions
with self.object_name
instead of self.cls
? I've tested it locally and it seems to work.
Here is my workaround code:
class Object(doc.Object):
def __init__(self, cls, *args, object_name=None, **kwargs):
super().__init__(cls, *args, object_name=object_name, **kwargs)
doc.definitions[self.object_name] = doc.definitions[self.cls]
del doc.definitions[self.cls]
PS.: Thanks for your efforts!
Like
Schematics might be the closest one.
Now I need to duplicate of record definitions.
Is it somehow possible to document the required query strings (note: not URL path params) and their types for GET requests? This line https://github.com/channelcat/sanic-openapi/blob/8a7b77f0fbda15061a8132c8a5c163f6ea82afcb/sanic_openapi/openapi.py#L103 suggests that @doc.consumes can only be used for HTTP verbs other than GET and DELETE.
I don't really know the nature of how pypi handles authorization, but is it really a good idea to have the password made public here?
Hi.
The following code
class OABuilding:
floors = [OAFloor]
# lat_lon = [doc.String()]
state = doc.String("State")
street = doc.String("Street")
building_id = doc.String("Building ID")
city = doc.String("City")
province = doc.String("Province")
zipcode = doc.String("Zipcode")
phone = doc.String("Phone")
notes = doc.String("Notes")
name = doc.String("Building Name")
class OABuildingsResponse:
data = doc.List(OABuilding, description="All buildings")
raises this error:
Traceback (most recent call last):
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic/sanic.py", line 355, in run
serve(**server_settings)
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic/server.py", line 305, in serve
trigger_events(before_start, loop)
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic/server.py", line 262, in trigger_events
result = event(loop)
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/openapi.py", line 99, in build_spec
"schema": serialize_schema(route_spec.produces) if route_spec.produces else None
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/doc.py", line 155, in serialize_schema
return Object(schema).serialize()
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/doc.py", line 107, in init
definitions[self.cls] = (self, self.definition)
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/doc.py", line 115, in definition
for key, schema in self.cls.dict.items()
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/doc.py", line 116, in
if not key.startswith("_")
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/doc.py", line 162, in serialize_schema
return schema.serialize()
File "/opt/venv36/spy-rest/lib/python3.6/site-packages/sanic_openapi/doc.py", line 86, in serialize
if len(self.items) > 1:
TypeError: object of type 'type' has no len()
If I use it with
class OABuildingsResponse:
data = [OABuilding]
It works
#21 is closed, but its fix only half-works:
@doc.route(exclude=True)
do not appear in the swagger UI, but,/openapi/spec.json
My expectation is that an "excluded" route would not appear in either the openapi/spec.json
or the swagger UI.
i have to set operation with views.
class RouteSpec(object):
consumes = None
consumes_content_type = None
produces = None
produces_content_type = None
summary = None
description = None
operation = None
blueprint = None
tags = None
exclude = None
response = None
--------
endpoint = remove_nulls({
'operationId': route_spec.operation or route.name,
'summary': route_spec.summary,
'description': route_spec.description,
'consumes': consumes_content_types,
'produces': produces_content_types,
'tags': route_spec.tags or None,
'parameters': route_parameters,
'responses': responses
})
'operationId': route_spec.operation or route.name,
And see that operationId in swagger.json
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "FUND SLB SVC API",
"description": "FUND SLB SVC API",
"termsOfService": "",
"contact": {
"email": null
},
"license": {
"name": null,
"url": null
}
},
"schemes": ["http"],
"securityDefinitions": {
"authToken": {
"type": "apiKey",
"in": "header",
"name": "Authorization",
"description": "Paste your auth token and do not forget to add \"Bearer \" in front of it"
},
"OAuth2": {
"type": "oauth2",
"flow": "application",
"tokenUrl": "https://your.authserver.ext/v1/token",
"scopes": {
"some_scope": "Grants access to this API"
}
}
},
"security": [{
"authToken": []
}],
"definitions": {},
"tags": [{
"name": "NginxCluster"
}],
"paths": {
"/fund-slb-svc/api/v1/NginxCluster/": {
"get": {
"operationId": "NginxCluster.Cluster List",
"summary": "nginx\u96c6\u7fa4\u5217\u8868",
"description": "nginx\u96c6\u7fa4\u5217\u8868",
"consumes": ["application/json"],
"produces": ["application/json"],
"tags": ["NginxCluster"],
"parameters": [{
"type": "string",
"required": false,
"in": "query",
"name": "installation_path"
}, {
"type": "string",
"required": false,
"in": "query",
"name": "type"
}, {
"type": "string",
"required": false,
"in": "query",
"name": "version"
}, {
"type": "string",
"required": false,
"in": "query",
"name": "name"
}, {
"type": "integer",
"format": "int64",
"required": false,
"in": "query",
"name": "id"
}],
"responses": {
"200": {
"schema": {
"type": "object",
"properties": {
"msg": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int64"
},
"data": {
"type": "object",
"properties": {}
}
}
},
"description": "Success"
}
}
},
"post": {
"operationId": "NginxCluster.Cluster List",
"summary": "\u65b0\u589enginx\u96c6\u7fa4",
"description": "\u65b0\u589enginx\u96c6\u7fa4",
"consumes": ["application/json"],
"produces": ["application/json"],
"tags": ["NginxCluster"],
"parameters": [{
"schema": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"type": {
"type": "string"
},
"installation_path": {
"type": "string"
}
}
},
"name": "body",
"required": false,
"in": "body"
}],
"responses": {
"200": {
"schema": {
"type": "object",
"properties": {
"msg": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int64"
},
"data": {
"type": "object",
"properties": {}
}
}
},
"description": "Success"
}
}
}
},
"/fund-slb-svc/api/v1/NginxCluster/{id}": {
"get": {
"operationId": "NginxCluster.NginxClusterGetOneController",
"summary": "\u901a\u8fc7ID\u83b7\u53d6nginx\u96c6\u7fa4\u4fe1\u606f",
"consumes": ["application/json"],
"produces": ["application/json"],
"tags": ["NginxCluster"],
"parameters": [{
"type": "integer",
"format": "int64",
"required": true,
"in": "path",
"name": "id"
}, {
"type": "integer",
"format": "int64",
"required": false,
"in": "path",
"name": "id"
}],
"responses": {
"200": {
"schema": {
"type": "object",
"properties": {
"msg": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int64"
},
"data": {
"type": "object",
"properties": {}
}
}
},
"description": "Success"
}
}
},
"put": {
"operationId": "NginxCluster.NginxClusterGetOneController",
"summary": "\u901a\u8fc7ID\u66f4\u65b0nginx\u96c6\u7fa4\u4fe1\u606f",
"consumes": ["application/json"],
"produces": ["application/json"],
"tags": ["NginxCluster"],
"parameters": [{
"type": "integer",
"format": "int64",
"required": true,
"in": "path",
"name": "id"
}, {
"type": "integer",
"format": "int64",
"required": false,
"in": "path",
"name": "id"
}],
"responses": {
"200": {
"schema": {
"type": "object",
"properties": {
"msg": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int64"
},
"data": {
"type": "object",
"properties": {}
}
}
},
"description": "Success"
}
}
},
"delete": {
"operationId": "NginxCluster.NginxClusterGetOneController",
"summary": "\u901a\u8fc7ID\u5220\u9664nginx\u96c6\u7fa4\u4fe1\u606f",
"consumes": ["application/json"],
"produces": ["application/json"],
"tags": ["NginxCluster"],
"parameters": [{
"type": "integer",
"format": "int64",
"required": true,
"in": "path",
"name": "id"
}, {
"type": "integer",
"format": "int64",
"required": false,
"in": "path",
"name": "id"
}],
"responses": {
"200": {
"schema": {
"type": "object",
"properties": {
"msg": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int64"
},
"data": {
"type": "object",
"properties": {}
}
}
},
"description": "Success"
}
}
}
}
}
}
models
class ModelsDemo:
id = int
name = str
version = str
type = str
installation_path = str
views
blueprint = Blueprint('demo', '/demo')
@blueprint.get("/", strict_slashes=True)
@doc.summary("demo")
@doc.consumes(ModelsDemo, location="body")
async def ModelsDemoViews(request, *args, **kwargs):
"""
List
"""
pass
errors
[2019-04-22 16:35:44 +0800] [44224] [ERROR] Exception occurred while handling uri: 'http://127.0.0.1:8080/swagger/swagger.json'
Traceback (most recent call last):
File "E:\code\alter_svc\websocket-svc\lib\site-packages\sanic\app.py", line 915, in handle_request
response = handler(request, *args, **kwargs)
File "E:\local_git\fund-slb-svc\sanic_openapi\swagger.py", line 208, in spec
return json(_spec)
File "E:\code\alter_svc\websocket-svc\lib\site-packages\sanic\response.py", line 220, in json
dumps(body, **kwargs),
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
python version 3.7
sanic version 19.3.1
sanic-openapi version 0.5.1
The new release 0.5.1 is not yet on pypi ( and the 0.5.0 is broken )
https://pypi.org/project/sanic-openapi
Do you know how to update it ? @ahopkins
@dataset_svc.get('/datasets', strict_slashes=True)
@doc.summary('list all datasets')
@doc.produces([{"name": str, "id": str, "type": str}])
async def list_datasets(request):
dataset_class = get_dataset_class('CSV')
try:
datasets = dataset_class.list_datasets()
return response.json(datasets, status=200)
except Exception:
return response.json({}, status=500)
there is nothing produced, what could be the reason?
I use sanic-openapi and sanic-jwt
How to set @doc.consumes
and @doc.produces
for below API's of sanic-jwt
POST/auth/
GET/auth/me/
GET/auth/verify/
Hi.
Is there a way to emulate the behaviour of this ref attribute $ref: "#/definitions/Response" (in BuildingsResponse)?
I need a way to add all the fields of Response inside other responses
Response:
required:
- application
- version
- api_version
- contact
- status
properties:
application:
type: string
version:
type: string
api_version:
type: string
contact:
type: string
status:
type: integer
BuildingsResponse:
type: object
allOf:
- $ref: "#/definitions/Response"
- type: object
properties:
data:
type: array
items:
$ref: "#/definitions/Building"
metadata:
type: object
properties:
building_id:
type: integer
/swagger
endpoint causes index.html to look for the assets at /<file_name>
instead of /swagger/<file_name
. /swagger/
works because it generates the correct url.
If you register the two blueprints with a prefix as follows:
app.blueprint(openapi_blueprint, url_prefix='/api/openapi')
app.blueprint(swagger_blueprint, url_prefix='/api/swagger')
swagger ends up not working at /api/swagger because it looks for the specs.json file at /specs.json instead of /api/specs.json
I believe it is because of this code at the bottom of sanic_openapi/openapi.py
@blueprint.route('/spec.json')
def spec(request):
return json(_spec)
Should it not take the blueprint prefix into consideration?
There are several pointers in swagger-ui.js
and swagger-ui-bundle.js
to https://online.swagger.io/validator
. These pointers cause the swagger UI to freeze.
Would it be possible to document "offline deployment" instructions, or even provide a configuration for whether or not the UI should try to access resources on external domains?
I am glab to see the latest update to version 0.5.0.
I am hitting this issue after upgrade from 0.4.0 to 0.5.0.
File "/Users/gtao/Code/Projects/Personal/dataplay3/server/.venv/lib/python3.6/site-packages/sanic_openapi/swagger.py", line 146, in build_spec
"schema": serialize_schema(route_spec.produces.field) if route_spec.produces else None,
AttributeError: 'list' object has no attribute 'field'
seems it is complaining about the list in produces.
I am using something like this:
@doc.route( summary='list all datasets', produces=[{"name": str, "id": str, "type": str, "description": str}], )
is that a problem?
----- can be closed ----
Hello there,
I am not sure if support for this already exists. As far as i looked, i couldn't find.
in 0.4.0.
dict = {'name': {'type': 'string', 'description': 'id name', 'required': True, 'in': 'formData'}, 'abbr': {'type': 'string', 'description': 'name addr ', 'required': True, 'in': 'formData'}}
@doc.consumes(dict)
only name argument, not addr argument.
but in 0.3.0 is suceess !
so.l found bug.
in openapi.py
for consumer in route_spec.consumes:
print(consumer.field)
spec = serialize_schema(consumer.field)
# print(spec)
if 'properties' in spec:
for name, prop_spec in spec['properties'].items():
route_param = {
**prop_spec,
'required': consumer.required,
'in': consumer.location,
'name': name
}
else:
route_param = {
**spec,
'required': consumer.required,
'in': consumer.location,
'name': consumer.field.name if hasattr(consumer.field, 'name') else 'body'
}
if '$ref' in route_param:
route_param["schema"] = {'$ref': route_param['$ref']}
del route_param['$ref']
route_parameters.append(route_param) # There is only one record
so. if is that:
for consumer in route_spec.consumes:
print(consumer.field)
spec = serialize_schema(consumer.field)
# print(spec)
if 'properties' in spec:
for name, prop_spec in spec['properties'].items():
route_param = {
**prop_spec,
'required': consumer.required,
'in': consumer.location,
'name': name
}
route_parameters.append(route_param) # add revord
else:
route_param = {
**spec,
'required': consumer.required,
'in': consumer.location,
'name': consumer.field.name if hasattr(consumer.field, 'name') else 'body'
}
route_parameters.append(route_param) # add revord
if '$ref' in route_param:
route_param["schema"] = {'$ref': route_param['$ref']}
del route_param['$ref']
route_parameters.append(route_param) # inside
so. it is be worker .
@blueprint.get("/", strict_slashes=True)
@doc.consumes({ "user": { "name": str, "id": int }, "user1": { "name": str, "id": int }}, location="query", content_type='application/json')
just last one parameter is active.
python version 3.7
sanic 19.3.1
sanic-openapi 0.5.1
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.