CamelCase Conversion
Source module: fastapi_restful.camelcase
¶
The fastapi_restful.camelcase
module contains functions for converting camelCase
or CamelCase
strings to snake_case
, and vice versa:
from fastapi_restful.camelcase import camel2snake, snake2camel
assert snake2camel("some_field_name", start_lower=False) == "SomeFieldName"
assert snake2camel("some_field_name", start_lower=True) == "someFieldName"
assert camel2snake("someFieldName") == "some_field_name"
assert camel2snake("SomeFieldName") == "some_field_name"
These functions are used by APIModel to ensure snake_case
can be used in your python code,
and camelCase
attributes in external JSON
.
But they can also come in handy in other places – for example, you could use them to ensure tables
declared using SQLAlchemy’s declarative API are named using snake_case
:
from sqlalchemy.orm import declarative_base, declared_attr
from fastapi_restful.camelcase import camel2snake
class CustomBase:
@declared_attr
def __tablename__(cls) -> str:
return camel2snake(cls.__name__)
Base = declarative_base(cls=CustomBase)
If you were to create a class MyUser(Base):
using Base
defined above,
the resulting database table would be named my_user
.