CSV Repository
Contents
CSV Repository#
CSV (Comma-separated values file) repository is a data store in which each item represents a row in the given CSV file.
With dict:
from redbird.repos import CSVFileRepo
repo = CSVFileRepo(filename="my_repo.csv", fieldnames=['id', 'name', 'age'])
Warning
CSV files don’t maintain the data types. All field values are considered
str and empty values are considered None. It is adviced to use
Pydantic model (see below) instead if the type matters.
With Pydantic model:
from pydantic import BaseModel
from redbird.repos import CSVFileRepo
class MyItem(BaseModel):
id: str
name: str
age: int
repo = CSVFileRepo(filename="my_repo.csv", model=MyItem)
Usage#
Now you may use the repository the same way as any other repository. Please see:
Class#
- class redbird.repos.CSVFileRepo(*, model=<class 'dict'>, id_field=None, query_model=<class 'redbird.base.BasicQuery'>, errors_query='raise', field_access='infer', ordered=True, filename, fieldnames=None, kwds_csv={})#
CSV file repository
This repository has a CSV (comma-separated values) file as a data store. Each item represents a row in the file.
- Parameters
filename (path-like) – The repository file
fieldnames (list of str) – Names of the columns in the CSV file. If unspecified, model’s fields are used instead
model (Type) – Class of an item in the repository. Commonly dict or subclass of Pydantic BaseModel. By default dict
id_field (str, optional) – Attribute or key that identifies each item in the repository.
field_access ({'attr', 'key'}, optional) – How to access a field in an item. Either by attribute (‘attr’) or key (‘item’). By default guessed from the model.
query (Type, optional) – Query model of the repository.
errors_query ({'raise', 'warn', 'discard'}) – Whether to raise an exception, warn or discard the item in case of validation error in converting data to the item model from the repository. By default raise
kwds_csv (dict) – Keyword arguments used to create
csv.DictWriterandcsv.DictReader
Examples
repo = CSVFileRepo(filepath="path/to/repo", fieldnames=['id', 'name', 'age'])
- insert(item)#
Insert item to the repository
- Parameters
item (instance of model) – Item to insert to the repository
Examples
repo.insert(Item(id="a", color="red"))
- filter_by(**kwargs)#
Filter the repository
- Parameters
**kwargs (dict) – Query which is used to conduct furher operation.
Examples
repo.filter_by(color="red")
- update(item)#
Update item in the repository
- Parameters
item (instance of model) – Item to update in the repository
Examples
repo.update(Item(id="a", color="red"))
- delete(item)#
Delete item from the repository
- Parameters
item (instance of model) – Item to delete from the repository
Examples
repo.delete(Item(id="a", color="red"))