๐ Welcome to my profile!
โ If you have any questions or suggestions for me, write to me in Telegram.
โ๏ธ t.me/dotX12 | @dotX12
๐ช A simple pydantic to Form FastAPI model converter.
License: MIT License
Trying to install on ec2 server.
here my ec2 details
Virtualization: amazon
Operating System: Amazon Linux 2
CPE OS Name: cpe:2.3:o:amazon:amazon_linux:2
Kernel: Linux 5.10.162-141.675.amzn2.x86_64
Architecture: x86-64
python version: Python 3.7.16
pip version: pip 23.3.2
Hi! great to see this useful tool!
Cross posting from FastAPI discussions ๐
I just tried it, but unfortunately it doesn't work with pydantic v2.
It crashes because it can't find pydantic.fields.ModelField
, that is removed in facor of a cls.model_fields
, which is a dict[str, FieldInfo]
.
Obviously there will be other error, but I couldn't find the time to investigate it further.
Hi,
With an model like this:
class PostContractBodySchema(BaseModel):
config_id: str = Field(
...,
max_length=25,
title="Config ID",
description="The ID of the config used by this notification channel.",
example="ckasokq6g0000yvxuigfa2agy",
)
channel: Literal["whatsapp"] = Field(
...,
# max_length=25,
title="Channel",
description="Channel used by this notification.",
example="whatsapp",
)
channel_category: Literal["DIRECT_MESSAGE"] = Field(
...,
title="Category",
description="Communication channel category.",
example="DIRECT_MESSAGE",
)
language: Literal["pt_BR", "en"] = Field(
...,
# max_length=5,
title="Language",
description="language of this channel notification.",
example="pt_BR",
)
template_type: Literal["TRANSACTIONAL", "MARKETING", "OTP",] = Field(
...,
title="Template Type",
description="Your template should fall under one of these categories. This will be used by some providers to approve your template.",
example="MARKETING",
)
tags: str = Field(
...,
max_length=64,
title="Tags",
description="Tags of this template.",
example="PROPOSAL SEND",
)
config: Dict[str, Any] = Field(
...,
title="Configuration",
description="""Notification extra configuration, like buttons and images in Whatsapp templates.""",
example={
"header": "Importante",
"footer": "Clique no botรฃo para continuar a conversa.",
"buttons": [{"type": "QUICK_REPLY", "text": "Sim"}],
},
)
I got this exceptions:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/local/lib/python3.9/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
target(sockets=sockets)
File "/usr/local/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
return asyncio.run(self.serve(sockets=sockets))
File "/usr/local/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "uvloop/loop.pyx", line 1501, in uvloop.loop.Loop.run_until_complete
File "/usr/local/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
config.load()
File "/usr/local/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
self.loaded_app = import_from_string(self.app)
File "/usr/local/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/app/./app/main.py", line 34, in <module>
from app.api.api import api_router
File "/app/./app/api/api.py", line 11, in <module>
from app.api.api_v1.endpoints.notification_channel.endpoint import notification_channel_router
File "/app/./app/api/api_v1/endpoints/notification_channel/endpoint.py", line 343, in <module>
payload: PostContractBodySchema = FormDepends(PostContractBodySchema),
File "/usr/local/lib/python3.9/site-packages/pyfa_converter/depends.py", line 42, in __new__
return super().generate(model=model_type, _type=cls._TYPE)
File "/usr/local/lib/python3.9/site-packages/pyfa_converter/depends.py", line 26, in generate
obj = PydanticConverter.reformat_model_signature(model_cls=model, _type=_type)
File "/usr/local/lib/python3.9/site-packages/pyfa_converter/main.py", line 105, in reformat_model_signature
new_params = PydanticConverterUtils.override_signature_parameters(
File "/usr/local/lib/python3.9/site-packages/pyfa_converter/main.py", line 50, in override_signature_parameters
return [
File "/usr/local/lib/python3.9/site-packages/pyfa_converter/main.py", line 54, in <listcomp>
default=param_maker(field),
File "/usr/local/lib/python3.9/site-packages/pyfa_converter/main.py", line 94, in make_form_parameter
if issubclass(field.type_, BaseModel):
File "/usr/local/lib/python3.9/abc.py", line 123, in __subclasscheck__
return _abc_subclasscheck(cls, subclass)
TypeError: issubclass() arg 1 must be a class
If I remove the fields of type Literal and Dict[str, Any] pyfa works fine.
Any idea on how to solve this problem ?
Thanks
Using the
from pyfa_converter import FormDepends
and get the error
TypeError: unsupported operand type(s) for |: 'ModelMetaclass' and 'type'
python: 3.9
The default values of Field
get ignored.
class TestModel(BaseModel):
test_field: str | None = Field(default="Some default value", description="Description...")
Is the only option to add an validator like this:
@root_validator
def set_default_values(cls, values):
values["test_field"] = (
"Some default value"
if values.get("test_field") is None
else values["test_field"]
)
return values
Or is there another way for the default values to work?
python-multipart has released v0.0.6 but the dependency of this repo is ^0.0.5, which might cause some dependency conflict with newer packages.
On:
python: 3.10 and 3.11
pyfa-converter: 1.0.3.0 (and master
, which shows as 1.0.1.0)
pydantic: 1.10.2
If you add a Field
constraint, pydantic raises a ValueError:
For example, for the class in this repo, if you change it to (adding a gt
constraint of 10
:
class PostContractSmallDoubleBodySchema(BaseModel):
id: Optional[int] = Field(None, description="gwa", gt=10)
title: Optional[str] = Field(None)
data: Optional[List[int]]
pydantic raises the following exception
ImportError while loading conftest '/home/ben/repos/pyfa-converter/tests/conftest.py'.
tests/conftest.py:6: in <module>
from examples.main import app
examples/main.py:47: in <module>
@app.post("/test")
.venv/lib/python3.11/site-packages/fastapi/routing.py:630: in decorator
self.add_api_route(
.venv/lib/python3.11/site-packages/fastapi/routing.py:569: in add_api_route
route = route_class(
.venv/lib/python3.11/site-packages/fastapi/routing.py:438: in __init__
self.dependant = get_dependant(path=self.path_format, call=self.endpoint)
.venv/lib/python3.11/site-packages/fastapi/dependencies/utils.py:292: in get_dependant
sub_dependant = get_param_sub_dependant(
.venv/lib/python3.11/site-packages/fastapi/dependencies/utils.py:122: in get_param_sub_dependant
return get_sub_dependant(
.venv/lib/python3.11/site-packages/fastapi/dependencies/utils.py:158: in get_sub_dependant
sub_dependant = get_dependant(
.venv/lib/python3.11/site-packages/fastapi/dependencies/utils.py:299: in get_dependant
param_field = get_param_field(
.venv/lib/python3.11/site-packages/fastapi/dependencies/utils.py:388: in get_param_field
annotation = get_annotation_from_field_info(annotation, field_info, param_name)
pydantic/schema.py:1011: in pydantic.schema.get_annotation_from_field_info
???
E ValueError: On field "id" the following field constraints are set but not enforced: gt.
E For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints
I spent some time investigating and I'm still not sure why this is happening
Hi,
First, thank you for sharing this library, it works great!
I was wondering if there's a way to make the form data optional. I'd like to have an endpoint that would work without body and with a form.
I tried using a union with the model and None
but it's not working. Example code:
from fastapi import FastAPI, Form
from pydantic import BaseModel, validator, ValidationError
from pyfa_converter import FormDepends
from starlette.responses import JSONResponse
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
app = FastAPI()
class MyRequest(BaseModel):
a: str = Form(default=None)
b: str = Form(default=None)
@validator('a')
def a_must_contain_space(cls, v):
if not v:
return v
if ' ' not in v:
raise ValueError('must contain a space')
return v.title()
@app.exception_handler(ValidationError)
def exception_handler(_request, exc: ValidationError):
return JSONResponse(status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()})
@app.post("/test")
async def test(request: MyRequest | None = FormDepends(MyRequest)):
if request is None:
return "Empty form data"
return "Has form data"
request
is always not None
, no matter the request. Is there a way to achieve what I intend?
In addition, is there a way to mark the request body in the docs as multipart/form-data
?:
Thanks.
Hi! The code in this repo seems super useful for us working with pydantic + fastapi, but we can't use it without a LICENSE
. Could you add LICENSE
file to the repo? MIT is a permissive one if you don't have an opinion otherwise
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.