datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Simple Use Case with CSV

Open nfarrar opened this issue 3 years ago • 1 comments

I'm attempting to use the library as a module, but having a difficult time figuring out the correct inputs for generate from the documentation. Command line usage is a no brainer:

# Note: test_data.csv is currently just the data from simple.csv in the tests
# % datamodel-codegen --input test_data.csv --input-file-type csv --output test_model.py 
# generated by datamodel-codegen:
#   filename:  test_data.csv
#   timestamp: 2021-04-30T20:18:11+00:00

from __future__ import annotations

from pydantic import BaseModel, Field


class Model(BaseModel):
    id: str
    name: str
    tel: str
    zip_code: str = Field(..., alias='zip code')

... but when trying to include this in my own code (based on this example: https://koxudaxi.github.io/datamodel-code-generator/using_as_module/) ... I'm trying to figure out the most straight forward way. I don't need a temp directory or even to write it out to disk ATM.

This is what I'm currently doing:

from pathlib import Path
from tempfile import TemporaryDirectory
from datamodel_code_generator import InputFileType, generate

with TemporaryDirectory() as temporary_directory_name:
    temporary_directory = Path(temporary_directory_name)
    output = Path(temporary_directory / 'model.py')
    generate(
        Path("test_data.csv"),
        input_file_type=InputFileType.CSV,
        input_filename="test_data.csv",
        output=output,
    )
    model: str = output.read_text()

print(model)

... it works, but seems super wonky. Amidoingitrite?

nfarrar avatar Apr 30 '21 20:04 nfarrar

@nfarrar

... it works, but seems super wonky. Amidoingitrite?

Yes. currently, It's right. But, We need a way to create easy. :thinking:

I have an idea that generate() will return results as str or dict. What did you think about it?

results = generate(
        Path("test_data.csv"),
        input_file_type=InputFileType.CSV,
        input_filename="test_data.csv",
    )
if isinstance(results, str):
  ## For a single file
  print(results) 
else:
  ## For modules
  for file_name, body:
      print(file_name)
      print(body)
      

koxudaxi avatar May 01 '21 15:05 koxudaxi