Skip to content

Commit 170baa1

Browse files
committed
Fix cli
1 parent e0a6143 commit 170baa1

File tree

10 files changed

+101
-359
lines changed

10 files changed

+101
-359
lines changed

docs/source/guides/cli.rst

Lines changed: 11 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ To use the CLI features, install Flask InputFilter with the ``cli`` extra::
1212

1313
This installs the following additional dependencies:
1414

15-
- ``click>=8.0`` - Command-line interface framework
16-
- ``jinja2>=3.0`` - Template engine for code generation
17-
- ``jsonschema>=4.0`` - JSON Schema validation library
15+
- ``click`` - Command-line interface framework
16+
- ``jinja2`` - Template engine for code generation
17+
- ``jsonschema`` - JSON Schema validation library
1818

1919
Quick Start
2020
-----------
@@ -55,12 +55,12 @@ Given this JSON Schema (``user_schema.json``):
5555
},
5656
"age": {
5757
"type": "integer",
58+
"required": "false",
5859
"description": "User's age",
5960
"minimum": 18,
6061
"maximum": 120
6162
}
6263
},
63-
"required": ["name", "email"],
6464
"additionalProperties": false
6565
}
6666
@@ -79,8 +79,7 @@ The CLI generates this Python code:
7979
8080
8181
class UserInputFilter(InputFilter):
82-
"""User
83-
User registration data"""
82+
"""User registration data"""
8483
8584
# User's full name
8685
name = field(required=True, filters=[StringTrimFilter()], validators=[IsStringValidator(), LengthValidator(min_length=2, max_length=100)])
@@ -96,7 +95,7 @@ The CLI generates this Python code:
9695
Command Reference
9796
-----------------
9897

99-
generate
98+
generate:inputfilter
10099
~~~~~~~~
101100

102101
Generate InputFilter classes from JSON Schema files.
@@ -105,7 +104,7 @@ Generate InputFilter classes from JSON Schema files.
105104

106105
.. code-block:: bash
107106
108-
fif generate [OPTIONS]
107+
fif generate:inputfilter [OPTIONS]
109108
110109
**Required Options:**
111110

@@ -120,27 +119,9 @@ Generate InputFilter classes from JSON Schema files.
120119
``--out PATH``
121120
Output file path. Use ``-`` for stdout (default)
122121

123-
``--base-class NAME``
124-
Base class name (default: ``InputFilter``)
125-
126-
``--base-module MODULE``
127-
Module to import base class from (default: ``flask_inputfilter``)
128-
129-
``--field-import MODULE``
130-
Module to import the ``field`` function from
131-
132-
``--field-name NAME``
133-
Name of the field builder function (default: ``field``)
134-
135122
``--strict``
136123
Fail if schema properties cannot be mapped to validators
137124

138-
``--docstring/--no-docstring``
139-
Include schema title and description as class docstring (default: enabled)
140-
141-
``--template PATH``
142-
Path to custom Jinja2 template file
143-
144125
**Examples:**
145126

146127
Basic usage::
@@ -155,10 +136,6 @@ Use strict validation::
155136

156137
fif generate --schema user.json --class UserInputFilter --strict
157138

158-
Custom base class::
159-
160-
fif generate --schema user.json --class UserInputFilter --base-class CustomFilter --base-module myapp.base
161-
162139
help
163140
~~~~
164141

@@ -195,7 +172,6 @@ Help for specific command::
195172
- **Practical examples**: Shows common usage patterns
196173
- **Command discovery**: Lists all available commands with brief descriptions
197174
- **Error handling**: Provides helpful feedback for unknown commands
198-
- **Multiple access methods**: Works alongside standard ``--help`` flags
199175

200176
The help system is designed to be both comprehensive for new users and quick for experienced users who need specific command details.
201177

@@ -297,88 +273,13 @@ Generated InputFilter classes work seamlessly with Flask routes:
297273
# Create user in database...
298274
return jsonify({'status': 'created'})
299275
300-
Advanced Usage
301-
--------------
302-
303-
Custom Templates
304-
~~~~~~~~~~~~~~~~
305-
306-
You can provide your own Jinja2 template for code generation:
307-
308-
.. code-block:: bash
309-
310-
fif generate --schema user.json --class UserFilter --template my_template.j2
311-
312-
The template receives these context variables:
313-
314-
- ``base_module``, ``base_class`` - Import information
315-
- ``class_name`` - Generated class name
316-
- ``schema_title``, ``schema_description`` - From JSON Schema
317-
- ``fields`` - List of field definitions with validators and filters
318-
- ``import_filters``, ``import_validators``, ``import_enums`` - Required imports
319-
- ``global_validators`` - Schema-level validators
320-
321-
CI/CD Integration
322-
~~~~~~~~~~~~~~~~~
323-
324-
The CLI is ideal for automated code generation in CI/CD pipelines:
325-
326-
.. code-block:: yaml
327-
328-
# GitHub Actions example
329-
- name: Generate InputFilter classes
330-
run: |
331-
for schema in schemas/*.json; do
332-
class_name=$(basename "$schema" .json | sed 's/.*/\u&/')InputFilter
333-
fif generate --schema "$schema" --class "$class_name" --out "src/filters/"
334-
done
335-
336-
Working with OpenAPI Specifications
337-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
338-
339-
While the CLI currently supports JSON Schema directly, you can extract schemas from OpenAPI specifications:
340-
341-
.. code-block:: bash
342-
343-
# Extract user schema from OpenAPI spec
344-
yq eval '.components.schemas.User' openapi.yaml > user_schema.json
345-
346-
# Generate InputFilter
347-
fif generate --schema user_schema.json --class UserInputFilter
348-
349-
Best Practices
350-
--------------
351-
352-
Schema Organization
353-
~~~~~~~~~~~~~~~~~~~
354-
355-
- Keep JSON schemas in a dedicated directory (e.g., ``schemas/``)
356-
- Use descriptive filenames that match your model names
357-
- Include meaningful ``title`` and ``description`` fields
358-
- Set ``additionalProperties: false`` for strict validation
359-
360-
Code Generation
361-
~~~~~~~~~~~~~~~
362-
363-
- Use consistent naming conventions for generated classes (e.g., ``ModelNameInputFilter``)
364-
- Generate filters into a dedicated module (e.g., ``filters/`` or ``validation/``)
365-
- Consider using ``--strict`` mode in CI/CD to catch schema issues early
366-
- Version control both schemas and generated code for traceability
367-
368-
Error Handling
369-
~~~~~~~~~~~~~~
370-
371-
- Use descriptive error messages in your schemas
372-
- Test generated validators with valid and invalid data
373-
- Consider custom error messages for business-specific validation rules
374-
375276
Troubleshooting
376277
---------------
377278

378279
Common Issues
379280
~~~~~~~~~~~~~
380281

381-
**"No such command 'generate'"**
282+
**"No such command 'generate:inputfilter'"**
382283

383284
Ensure you installed with the CLI extra::
384285

@@ -403,7 +304,7 @@ Getting Help
403304

404305
For command-specific help::
405306

406-
fif --help
407-
fif generate --help
307+
fif help
308+
fif help generate
408309

409-
For issues and feature requests, visit the `GitHub repository <https://github.com/LeanderCS/flask-inputfilter/issues>`_.
310+
For issues and feature requests, visit the `GitHub repository <https://github.com/LeanderCS/flask-inputfilter/issues>`_.

flask_inputfilter/cli/codegen/json_schema.py

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,28 +17,22 @@ class JsonSchemaCodegen:
1717
def validate_schema(schema: Dict[str, Any]) -> None:
1818
"""Validate the JSON schema using jsonschema library."""
1919
try:
20-
jsonschema.Draft202012Validator.check_schema(schema)
20+
jsonschema.Draft202012Validator.check_schema(schema) # was zur hölle ist Draft202012Validator nutzte da einen richtigen
2121
except jsonschema.SchemaError as e:
2222
raise ValueError(f"Invalid JSON Schema: {e}")
2323

2424
@staticmethod
2525
def build_context(
2626
schema: Dict[str, Any],
2727
class_name: str,
28-
base_class: str = "InputFilter",
29-
base_module: str = "flask_inputfilter",
30-
import_field_from: Union[str, None] = None,
31-
field_name: str = "field",
3228
strict: bool = False,
33-
docstring: bool = True,
3429
) -> Dict[str, Any]:
3530
"""Build template context from JSON schema."""
3631
mapper = TypeMapper()
3732

3833
if strict:
3934
JsonSchemaCodegen.validate_schema(schema)
4035

41-
required_fields = set(schema.get("required", []))
4236
properties: Dict[str, Any] = schema.get("properties", {})
4337

4438
if not properties and strict:
@@ -48,26 +42,19 @@ def build_context(
4842

4943
fields = []
5044
for name, spec in properties.items():
51-
field_def = mapper.map_field(name, spec, required_fields)
45+
field_def = mapper.map_field(name, spec)
5246
fields.append(field_def)
5347

54-
global_validators = mapper.get_global_validators(schema)
5548
imports = mapper.get_imports()
5649

5750
return {
58-
"base_module": base_module,
59-
"base_class": base_class,
6051
"class_name": class_name,
6152
"schema_title": schema.get("title", ""),
6253
"schema_description": schema.get("description", ""),
63-
"docstring": docstring,
64-
"import_field_from": import_field_from,
65-
"field_name": field_name,
6654
"import_filters": imports["filters"],
6755
"import_validators": imports["validators"],
6856
"import_enums": imports["enums"],
6957
"fields": fields,
70-
"global_validators": global_validators,
7158
}
7259

7360
@staticmethod

0 commit comments

Comments
 (0)