guokr / swagger-py-codegen Goto Github PK
View Code? Open in Web Editor NEWa Python web framework generator supports Flask, Tornado, Falcon, Sanic
a Python web framework generator supports Flask, Tornado, Falcon, Sanic
Hi,
I just managed to generate a Tornado app after solving the previous problem at #103. Trying to start the Tornado app resulted in the following error whose Traceback shows that the generated validators.py
module is importing a dependency that was not added to the requirements.txt
file, werkzeug that is.
Traceback (most recent call last):
File "/Users/ahmad/Projects/Work/swagger_code_gen/example-app/demo/core/__init__.py", line 25, in load_tornado_settings
mods.append(importlib.import_module('%s.routes' % module))
File "/Users/ahmad/.pyenv/versions/3.6.3/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/ahmad/Projects/Work/swagger_code_gen/example-app/demo/demo_api_v1/routes.py", line 11, in <module>
from .api.events import Events
File "/Users/ahmad/Projects/Work/swagger_code_gen/example-app/demo/demo_api_v1/api/__init__.py", line 6, in <module>
from ..validators import request_validate, response_filter
File "/Users/ahmad/Projects/Work/swagger_code_gen/example-app/demo/demo_api_v1/validators.py", line 12, in <module>
from werkzeug.datastructures import MultiDict
ModuleNotFoundError: No module named 'werkzeug'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "demo/__init__.py", line 11, in <module>
config = load_tornado_settings(*modules)
File "/Users/ahmad/Projects/Work/swagger_code_gen/example-app/demo/core/__init__.py", line 29, in load_tornado_settings
module))
ImportError: Could not import routers 'demo_api_v1' (Is it on sys.path?)
In a service spec I defined a query string parameter as integer like:
[...]
parameters:
- name: offset
in: query
required: false
type: integer
[...]
When I pass an invalid value like abc
for the offset parameter, the validating code gets a ValueError
which is not handled:
Traceback (most recent call last):
File "/home/.../controller.py", line 115, in __call__
self._validate_request()
File "/home/.../controller.py", line 248, in _validate_request
wrapped_callable()
File "/home/.../api_v1/validators.py", line 94, in wrapper
result, errors = validator.validate(value)
File "/home/.../api_v1/validators.py", line 72, in validate
value = self.type_convert(value)
File "/home/.../api_v1/validators.py", line 68, in type_convert
result[k] = fun(values)
File "/home/.../api_v1/validators.py", line 49, in <lambda>
'integer': lambda v: int(v[0]),
ValueError: invalid literal for int() with base 10: 'abc'
Maybe we need a bit more code for the integer
and float
types in convert_funs
which checks for ValueError
and treat such an error as an invalid value.
Using: swagger-py-codegen==0.2.3
maximum, minimum, maxLength, minLength .. etc.
tornado
jsonschema
six
werkzeug
If has 100 path,there will be 100 files in the api directory. Such as api.yml in the home directory.
It's too stupid and crazy
such as, I have a swagger definition file (api.yaml),
can we convert it to json using this tool?
Seems like refs are not working properly
https://pypi.python.org/pypi/json-spec
The above package seems to do the majority of what validators and parser does. Instead of continuing to maintain these two, consider moving to the above package for robustness.
3.12 doesnt like Python 3.7
flask那边,是因为Blueprint类的第二个参数是import name,但是sanic里的Blueprint的第二个参数直接是url_prefix,所以建议做一下处理
Other codegen tools support circular references. See swagger-api/swagger-codegen#728.
I this this issue with the following yml:
Node:
description: Generic node.
type: object
properties:
type:
description: Type or label of the node.
type: string
properties:
description: Node specific dictionary of key/value pairs.
type: object
additionalProperties:
type: string
relationships:
descriptions: Relationships this node has with other nodes.
type: array
items:
$ref: '#/definitions/Relationship'
Relationship:
description: Relationship that one node has with another.
type: object
properties:
type:
description: Type of relationship between nodes.
type: string
properties:
description: Relationship specific dictionary of key/value pairs.
type: object
additionalProperties:
type: string
node:
$ref: '#/definitions/Node'
Exception:
Traceback (most recent call last):
File "/usr/local/bin/swagger_py_codegen", line 11, in <module>
sys.exit(generate())
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/swagger_py_codegen/command.py", line 77, in generate
swagger = Swagger(data)
File "/usr/local/lib/python2.7/site-packages/swagger_py_codegen/parser.py", line 29, in __init__
self._references_sort()
File "/usr/local/lib/python2.7/site-packages/swagger_py_codegen/parser.py", line 67, in _references_sort
raise ValueError(msg)
ValueError: $ref circular references found!
Hi experts,
I want to use this project to display my api and test it whit my swagger definition file.
now I can display it well but can not run it.
when I click the button "Try it out". it seems there is no request from this ui to my rest api server.
so could any give some guidance for this project and the key point is where is the read execution of the request? is the code is in swagger-ui.js or method.py or other place?
Thanks a lot.
Hi there:)
Looks like a super cool project you got here. With OpenAPI 3 released on used out there in the wild, I was wondering if you are planning to support that anytime soon :)?
I run the command "python init.py". the server can start at port 5000, but in web browser, page not found ,there is the output in the page:
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
and I found in the debug console, there is the following message:
[03/Jan/2016 21:38:54] "GET / HTTP/1.1" 404 -
what's wrong with my environment?
Environment:
Python 2.7.13 (default, May 10 2017, 20:04:28)
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux2
Example failure:
# swagger_py_codegen -s petStore.json example-app
................................Traceback (most recent call last):
File "/opt/virtualenvs/engineering/bin/swagger_py_codegen", line 11, in <module>
sys.exit(generate())
...
File "/opt/virtualenvs/engineering/lib/python2.7/site-packages/swagger_py_codegen/parser.py", line 11, in schema_var_name
return ''.join(map(str.capitalize, path))
TypeError: descriptor 'capitalize' requires a 'str' object but received a 'unicode'
The (ugly) fix I found is rewriting this function in parser.py:
def schema_var_name(path):
#ALF
class_ = path[0].__class__
return class_.join(class_(''),map(class_.capitalize, path))
#return ''.join(map(str.capitalize, path))
Right now, this project can only generate Flask code.
How about we add support for additional frameworks, specifically for Falcon?
It would only require creating a FalconGenerator class (in falcon.py module) and appropriate templates, most of which would be fairly similar.
Is this something you'd consider merging in?
def _normalize_default(schema, data):
if data is None:
return schema.get('default')
else:
return data
Need sorted based on alphabet order, or the other in the spec. Currently it is out of order, so hard to navigate when number of operations grow.
$ref都被替换了,应保留
Given two files,
testing.yml
swagger: '2.0'
info:
version: "0.1.1"
title: test Application
paths:
/account:
get:
responses:
'200':
description: the status of an account
schema:
properties:
account:
$ref: '#/definitions/Account'
definitions:
$ref: 'testdef.yml'
and testdef.yml:
Account:
type: object
required:
- emailAddress
properties:
emailAddress:
type: string
installationInformation:
$ref: '#/InstallationInformation'
InstallationInformation:
description: A collection of information that describes an instance of the application and what device it is running on.
properties:
OSType:
type: string
description:
Android or Apple or other
They validate ok:
schemas$ swagger validate testing.yml
testing.yml is valid
but swagger_py_codegen stumbles on $refs:
$ swagger_py_codegen --swagger-doc schemas/testing.yml -p api app --ui --spec
Traceback (most recent call last):
File "/home/d/venv/tm/bin/swagger_py_codegen", line 11, in <module>
sys.exit(generate())
File "/home/d/venv/tm/local/lib/python2.7/site-packages/click/core.py", line 700, in __call__
return self.main(*args, **kwargs)
File "/home/d/venv/tm/local/lib/python2.7/site-packages/click/core.py", line 680, in main
rv = self.invoke(ctx)
File "/home/d/venv/tm/local/lib/python2.7/site-packages/click/core.py", line 873, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/d/venv/tm/local/lib/python2.7/site-packages/click/core.py", line 508, in invoke
return callback(*args, **kwargs)
File "/home/d/venv/tm/local/lib/python2.7/site-packages/swagger_py_codegen/command.py", line 77, in generate
swagger = Swagger(data)
File "/home/d/venv/tm/local/lib/python2.7/site-packages/swagger_py_codegen/parser.py", line 29, in __init__
self._references_sort()
File "/home/d/venv/tm/local/lib/python2.7/site-packages/swagger_py_codegen/parser.py", line 67, in _references_sort
raise ValueError(msg)
ValueError: $ref circular references found!
I pull the swagger_py_codegen and run it in python3 like the following:
Pip install swagger_py_codegen
Swagger_py_codegen
There is the following error message:
Traceback (most recent call last):
File "/scratch/lozou/MyProject/Python/py34env/bin/swagger_py_codegen", line 11, in
sys.exit(generate())
File "/scratch/lozou/MyProject/Python/py34env/lib/python3.4/site-packages/click/core.py", line 716, in call
return self.main(_args, *_kwargs)
File "/scratch/lozou/MyProject/Python/py34env/lib/python3.4/site-packages/click/core.py", line 675, in main
_verify_python3_env()
File "/scratch/lozou/MyProject/Python/py34env/lib/python3.4/site-packages/click/_unicodefun.py", line 69, in _verify_python3_env
if locale.lower().endswith(('.utf-8', '.utf8')):
TypeError: 'str' does not support the buffer interface
(
And if I run it in python2.6, it also failed:
Traceback (most recent call last):
File "/scratch/lozou/MyProject/Python/py26env/bin/swagger_py_codegen", line 7, in
from swagger_py_codegen import generate
File "/scratch/lozou/MyProject/Python/py26env/lib/python2.6/site-packages/swagger_py_codegen/init.py", line 1, in
from .command import generate
File "/scratch/lozou/MyProject/Python/py26env/lib/python2.6/site-packages/swagger_py_codegen/command.py", line 12, in
from .flask import FlaskGenerator
File "/scratch/lozou/MyProject/Python/py26env/lib/python2.6/site-packages/swagger_py_codegen/flask.py", line 134
locations = {_location(loc): val for loc, val in v.iteritems()}
^
SyntaxError: invalid syntax
any configuration and package needed?
hi Rejown,
if convenient, could you please tell your IM account?such as , QQ or wechat?
I have some questions about this porject.
I'm stduing the swagger now.
👍
Background
I am generating a Flask server from a Swagger document with multiple schema definitions. I am generating the server code at build time, and committing it in source control.
Actual Outcome
Between two builds with no changes in my swagger.yaml, the file schemas.py
moves a Definitions...
entry between two different lines in the file; it is either the first Definitions
entry, or the third. This is seen in the diff:
$ git diff
-DefinitionsWeirdType = {'type': 'object', 'blah': 'blah'} # Hops from here..
DefinitionsOkType = {'type': 'object', 'blah': 'blah'}
DefinitionsFineType = {'type': 'object', 'blah': 'blah'}
+DefinitionsWeirdType = {'type': 'object', 'blah': 'blah'} # To here
Expected Outcome
The file should not change between two builds. The Definitions
variables should be sorted in a deterministic manner.
Versions
Python 3.6.5
swagger-py-codegen==0.3.2
swagger: "2.0"
Additional Details
I can work around this for now by only running my swagger-py-codegen
task if changes are detected in my swagger.yaml
.
Hi,
I am trying to generate a web application from a swagger specification and I get the following error, I have already validated my swagger specification on the Online Swagger Editor.
$ swagger_py_codegen -s swagger.yaml example-app -p demo --ui --spec
......................................generate example-app/demo/static/swagger-ui
Traceback (most recent call last):
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/bin/swagger_py_codegen", line 11, in <module>
load_entry_point('swagger-py-codegen==0.2.9', 'console_scripts', 'swagger_py_codegen')()
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/swagger_py_codegen/command.py", line 121, in generate
for code in generator.generate():
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/swagger_py_codegen/base.py", line 44, in generate
for code in g:
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/swagger_py_codegen/base.py", line 47, in generate
for code in self._process():
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/swagger_py_codegen/jsonschema.py", line 109, in _process
yield Schema(build_data(self.swagger))
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/swagger_py_codegen/jsonschema.py", line 71, in build_data
validator = dict(_parameters_to_schemas(path_param + method_param))
File "/Users/ahmad/Projects/Work/swagger_code_gen/venv/lib/python3.6/site-packages/swagger_py_codegen/jsonschema.py", line 28, in _parameters_to_schemas
yield location, param['schema']
KeyError: 'schema'
The error occurs on both Python2.7 and Python3.6.
Any ideas why this happens and how can I resolve it?
Take for example this (part of) swagger file:
swagger: '2.0'
info:
version: '1.0'
title: API
description: API.securityDefinitions:
Auth-email:
description: |
User-Email
type: apiKey
in: header
name: Auth-email
Auth-IP:
description: |
If login request is not sent from the same IP session is created for, you should send it.
type: apiKey
in: header
name: Auth-IP
JWT:
description: |
For accessing the API a valid JWT
type: apiKey
name: Authorization
in: header# default JWT security
security: [ { JWT: [] }]paths:
/login:
get:
summary: login
security:
- Auth-email
Auth-IP/query
get:
summary: query
Both requests have security configurations and neither is enforced/checked.
I think it should be.
Any objections that I'll do it?
The YAML in question
Person:
required:
- name
- children
properties:
name:
type: string
children:
type: array
items:
$ref: '#/definitions/Person'
I believe my issue is similar to #62
Trying to generate code from a model definition such as above will result in the following error:
ValueError: $ref circular references found!
Full yaml:
swagger: '2.0'
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
host: petstore.swagger.io
basePath: "/v1"
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
"/persons":
get:
summary: List all persons
operationId: listPersons
tags:
- persons
responses:
'200':
description: An paged array of persons
schema:
"$ref": "#/definitions/Person"
default:
description: unexpected error
schema:
"$ref": "#/definitions/Error"
post:
summary: Add a person
operationId: addPerson
tags:
- persons
parameters:
- in: body
name: body
required: true
schema:
"$ref": "#/definitions/Person"
responses:
'201':
description: person was created
schema:
"$ref": "#/definitions/Person"
default:
description: unexpected error
schema:
"$ref": "#/definitions/Error"
definitions:
Person:
required:
- name
- children
properties:
name:
type: string
children:
type: array
items:
"$ref": "#/definitions/Person"
Error:
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
However, if I run the same yaml through swagger-codegen, valid Python code is generated.
修复_normalize方法中,非必需子schema元素且该子schema中存在必需属性的问题。
The Swagger UI included is pretty outdated. One way to fix it is to update the files with the latest dist from the swagger-ui project. Another is to make UI a submodule.
Thoughts?
it seems in the code ,the type "query" and "body" are supported, but "path" is not supported.
if I set the type of a parameter to "path", when we run it ,the parameter is not added into the url of request.
is it sure?
I have a yml file. there is a definition for the host like the following:
host: api.server.domain
When I run the command swagger-py-codegen. there is a json file is created in the folder "static/v1", whose name is "swagger.json".
but I found the host definition is lost.
and when run the test "Try it out", the request is sent to my flask server "localhost/v1/Method".
can I add the host in the swagger.json directly? my purpose is the request should be sent to the real restful api host.
Is that meaning that the restful api server and the ui server should be the same?
I want to re-write the curl command and execute it to access the Restful API Host to get/post request and then analyze the response to get some information (Header and Body).
Sorry for that I don't know where is the realization code for it.
I found there is the following points in swagger-ui.js:
31919: var curlCommand = this.model.asCurl(this.map);
I know it is the point for making the curl command but I know where is executing for this command , and where is the callback for analyzing the response and then overwrite the response form in the web page.
I think it should be that run the asCurl function first and get the whole curl command and then run the post method.
but when I debug the trace , I found the sequence is reversed.
I write a swagger definition file and generate the code with swager-py-codegen.
I found in the code there is a new file swagger.json. but in the file ,the content "host" is lost.
so when I click the button named "Try it out", there is no response.
And I don't know where is the real execution of the Request to my restful API.
could anyone give some guidance for this project.
Thanks a lot.
I wrote a restful web application that need token and authentication to access the api.
And I can get the token from login to the api http://api/authenticate and can get the cookie.
how do I set the cookie in the next call ? such as:
when User click the button named "try out", it will run the command:
curl -b cookie_file ...
need I define the requirement of cookie in the original definition files (swagger.json)?
I add a host to the json file and run the test by clicking "Try it out" in web page.
There is no response from the server ,but when I execute the curl command in the terminal in linux according to the item "curl" from the web page, it can print the response header and body in the ternimal.
so I think whether the curl command (requst) is not executed?
where is the tracelog for the request or swagger-ui test?
Hi there,
I think this project is really cool and it can use some aiohttp support. Aiohttp has some tooling in place that would help you define validation logic quite easily, for example:
Cheers!
consider following "Path(s)" yaml definition:
/token/:
get:
summary: Obtain token
parameters:
- name: username
in: header
required: true
type: string
- name: password
in: header
required: true
type: string
format: password
responses:
200:
description: OK
headers:
x-auth-token:
type: string
curl -X GET --header "Accept: application/json" --header "username: testuser" --header "password: xxx" "http://127.0.0.1:5000/v1/token/"
returns:
{
"errors": [
"'username' is a required property",
"'password' is a required property"
],
"message": "Unprocessable Entity"
}
https://github.com/guokr/swagger-py-codegen/blob/master/swagger_py_codegen/jsonschema.py#L174
这里的判断可否换成
import collections
if isinstance(data, collections.Iterable):
或者
if hasattr(data, '__iter__'):
这样我在model中定义一对多的关系的时候可以直接使用 lazy='dynamic'
example:
validator = Draft4Validator(schema)
value = []
schema = {'required': ['username'], 'properties': {'username': {'type': 'string', 'description': u'username'}}}
errors = list(e.message for e in validator.iter_errors(value))
errors 结果为 []
单是结果应该是 ["'username' is a required property"] 才对
这里 错误是因为 value 应该是一个 {}
Hello,
sorry for bothering you with this question, but I didn't find anything related to this topic.
My question is how to override generated API methods (located under example_app/$basePath/api/*)
My point is to have a central point (api.yaml file) from which the code is generated and to extend the generated code with own logic / glue.
In other words, I would like to use the generated code not only for the docs / UI but as a 'template' which can be extended by own code.
As far I've seen, the generated methods code ("../api/") is bound only at one "point" - that is routes.py.
Importing ../api/ or $basePath/routes imports the stuff from init file.
Thanks a lot,
Rgds,
Adrian
RT
I've been working on an SQLalchemy branch.
Do you want me to form a pull-request out of it?
Is any plan to realize the client for the apis?
like this
definitions:
Pet:
type: object
discriminator: petType
properties:
name:
type: string
petType:
type: string
required:
- name
- petType
Cat:
description: A representation of a cat
allOf:
- $ref: '#/definitions/Pet'
- type: object
properties:
huntingSkill:
type: string
description: The measured skill for hunting
default: lazy
enum:
- clueless
- lazy
- adventurous
- aggressive
required:
- huntingSkill
Dog:
description: A representation of a dog
allOf:
- $ref: '#/definitions/Pet'
- type: object
properties:
packSize:
type: integer
format: int32
description: the size of the pack the dog is from
default: 0
minimum: 0
required:
- packSize
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.