aist-python-pydantic-json-schema-form
v1.0.1
Published
Dynamic React form generator from Python Pydantic model_json_schema() output
Downloads
97
Maintainers
Readme
aist-python-pydantic-json-schema-form
Python Pydantic model_json_schema() 출력을 기반으로 동적 React 폼을 생성하는 라이브러리
설치
# 로컬 패키지 링크
cd /Users/mskim07-macbook/Workspace/aist/aist-python-pydantic-json-schema-form
npm install
npm run build
npm link
# AI Studio Front에서 사용
cd /Users/mskim07-macbook/Workspace/aist/api-studio-front
npm link aist-python-pydantic-json-schema-form기본 사용법
import { JsonSchemaForm } from 'aist-python-pydantic-json-schema-form';
// Pydantic model_json_schema() 결과
const schema = {
type: 'object',
title: 'User',
properties: {
name: { type: 'string', title: 'Name' },
email: { type: 'string', format: 'email', title: 'Email' },
age: { type: 'integer', title: 'Age', minimum: 0 },
},
required: ['name', 'email'],
};
function MyForm() {
const handleSubmit = (data) => {
console.log('Form data:', data);
};
return (
<JsonSchemaForm
schema={schema}
onSubmit={handleSubmit}
onChange={(data) => console.log('Changed:', data)}
/>
);
}Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| schema | PydanticJsonSchema | required | Pydantic model_json_schema() 결과 |
| onSubmit | (data: FormValues) => void | - | 제출 핸들러 |
| onChange | (data: FormValues) => void | - | 실시간 변경 핸들러 |
| defaultValues | FormValues | - | 초기값 |
| disabled | boolean | false | 전체 비활성화 |
| readOnly | boolean | false | 읽기 전용 |
| showSubmitButton | boolean | true | 제출 버튼 표시 |
| submitButtonText | string | 'Submit' | 버튼 텍스트 |
| className | string | - | 폼 컨테이너 클래스 |
| classNames | ClassNames | - | 개별 요소 클래스 커스터마이징 |
지원 JSON Schema 기능
| 기능 | Pydantic 예시 | 지원 |
|------|--------------|------|
| 기본 타입 | str, int, float, bool | ✅ |
| Optional | Optional[str] → anyOf: [{type: string}, {type: null}] | ✅ |
| Enum | Literal["A", "B"] → enum: ["A", "B"] | ✅ |
| 중첩 모델 | Address → $ref: "#/$defs/Address" | ✅ |
| 배열 | List[str] → type: array, items: {type: string} | ✅ |
| 객체 배열 | List[Item] → items: {$ref: "#/$defs/Item"} | ✅ |
| Discriminated Union | Union[TypeA, TypeB] with discriminator | ✅ |
| 기본값 | Field(default="value") | ✅ |
| 설명 | Field(description="...") | ✅ |
| 검증 | minLength, maximum, pattern | ✅ |
| 포맷 | email, date, date-time, uuid, uri | ✅ |
스타일링
Tailwind CSS 클래스를 사용합니다. classNames prop으로 커스터마이징 가능합니다:
<JsonSchemaForm
schema={schema}
onSubmit={handleSubmit}
classNames={{
form: 'max-w-lg mx-auto',
input: 'border-gray-400',
label: 'text-gray-800 font-semibold',
submitButton: 'bg-green-600 hover:bg-green-700',
error: 'text-red-700',
arrayContainer: 'bg-gray-100 p-4 rounded',
objectContainer: 'border-l-4 border-blue-500 pl-4',
}}
/>고급 사용
Custom Hook 사용
import { useJsonSchemaForm, FormContext, FormField } from 'aist-python-pydantic-json-schema-form';
function CustomForm({ schema }) {
const { contextValue, handleSubmit, values } = useJsonSchemaForm({
schema,
onChange: (data) => console.log(data),
});
return (
<FormContext.Provider value={contextValue}>
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
{/* 커스텀 레이아웃 */}
<div className="grid grid-cols-2 gap-4">
<FormField name="firstName" path="firstName" schema={schema.properties.firstName} />
<FormField name="lastName" path="lastName" schema={schema.properties.lastName} />
</div>
<button type="submit">Submit</button>
</form>
</FormContext.Provider>
);
}유틸리티 함수
import {
resolveRef,
generateDefaultValue,
validateForm,
parsePath,
setValueAtPath,
} from 'aist-python-pydantic-json-schema-form';
// $ref 해석
const resolvedSchema = resolveRef('#/$defs/Address', rootSchema);
// 기본값 생성
const defaultValue = generateDefaultValue(schema, rootSchema);
// 폼 검증
const errors = validateForm(values, schema);
// 경로 기반 값 설정
const newValues = setValueAtPath(values, 'address.city', 'Seoul');예제: Pydantic 모델
from pydantic import BaseModel, Field
from typing import Optional, List, Literal
from datetime import date
class Address(BaseModel):
street: str
city: str
country: str = "Korea"
class User(BaseModel):
name: str = Field(description="사용자 이름")
email: str = Field(format="email")
age: Optional[int] = Field(default=None, ge=0)
role: Literal["admin", "user", "guest"] = "user"
address: Address
tags: List[str] = []
birth_date: Optional[date] = None
# JSON Schema 생성
schema = User.model_json_schema()위 Pydantic 모델의 model_json_schema() 출력으로 자동으로 폼이 생성됩니다.
개발
# 의존성 설치
npm install
# 개발 모드
npm run dev
# 빌드
npm run build
# 린트
npm run lintLicense
MIT
