datamodel-code-generator
datamodel-code-generator copied to clipboard
Q: Is it possible to add custom code to python generated definitions?
Hi, I would like to add endpoint name to Python generated scripts, the endpoint name should be probably in some variable/constant. What I mean in definitions language:
openapi: "3.0.0"
info: ...
paths:
my_endpoint_name:
$ref: "#/components/schemas/MyEndpointName"
components:
schemas:
MyEndpointName:
type: object
properties:
asdf:
type: string
Which I would like to be generated to something like this
class MyEndpointName(BaseModel):
asdf: Optional[str] = None
MY_ENDPOINT_NAME_INFO = EndpointInfo("my_endpoint_name", ...)
Is it possible or are you interested in such feature? Thanks for answer.
@adaamz
You can use --custom-template-dir
option.
The original template is here https://github.com/koxudaxi/datamodel-code-generator/blob/master/datamodel_code_generator/model/template/pydantic/BaseModel.jinja2
Thanks for answer. If I understand it correctly this is template for class and not for whole python file (with many definitions in it), am I right? Some documentation with examples would be really appreciated 😁
@koxudaxi Is it possible?
@adaamz I just understood your thought...
If I understand it correctly this is template for class and not for whole python file (with many definitions in it), am I right?
Yes, This template is a part of the python file. And, This code is building a python file. https://github.com/koxudaxi/datamodel-code-generator/blob/bdc186f232c56602d256dc69dc9b718245675509/datamodel_code_generator/parser/base.py#L628-L648
If your additional code is simple (only paths name) then you should add lines in the generated code by external commands or another module. Because, this code generator can generate models, but you want to create other content.
Also, you can override this method to parse operation
.
after parse, you can generate additional content.
However, I guess it's a little difficult.
https://github.com/koxudaxi/datamodel-code-generator/blob/master/datamodel_code_generator/parser/openapi.py#L328
Some documentation with examples would be really appreciated
Exactly!! I want to update the documents. But, I don't have the time.
Is it possible to add extra metadata in currently and have it be injected into the Field as the "extra"
https://github.com/samuelcolvin/pydantic/blob/8846ec4685e749b93907081450f592060eeb99b1/pydantic/fields.py#L126
Would be great to have additional custom metadata