Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CsvTarget to enable processing of completed lines of csv files in chunks #96

Merged
merged 1 commit into from
Feb 3, 2024

Conversation

gabrielcedran
Copy link

@gabrielcedran gabrielcedran commented Feb 1, 2024

The CsvTarget enables developers to load csv files in chunks, process the lines applying their own logic as they are completed by the chunks (e.g saving the lines into a db, send to another api, save into a file, etc) and remove them from the memory to prevent memory overflow.

In our project, our use case consisted of processing huge csv files where business logic needed to be applied for each line and then eventually they should be converted into domain objects and saved into a database.

Adapted example of our use case in flask:

`

def post(self):
    parser = StreamingFormDataParser(headers=request.headers)
    
    file_ = CsvTarget()
    parser.register('file', file_)

    while True:
        chunk = request.stream.read(1024)
        if not chunk:
            break
        parser.data_received(chunk)
        completed_lines = file_.pop_lines() # memory freed for the next iteration
        process_entries(completed_lines)

    completed_lines = file_.pop_lines(include_partial_line=True) # not necessarily a csv file ends with a linebreak
    process_entries(completed_lines)
    return {"message": "CSV uploaded successfully"}, 200

`

Copy link
Owner

@siddhantgoel siddhantgoel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! I left some minor comments but overall it looks good.

streaming_form_data/targets.py Outdated Show resolved Hide resolved
streaming_form_data/targets.py Outdated Show resolved Hide resolved
tests/test_targets.py Outdated Show resolved Hide resolved
streaming_form_data/targets.py Outdated Show resolved Hide resolved
streaming_form_data/targets.py Outdated Show resolved Hide resolved
@siddhantgoel siddhantgoel merged commit 53e06b6 into siddhantgoel:main Feb 3, 2024
12 checks passed
@siddhantgoel
Copy link
Owner

Thanks for the PR! I just published v1.14.0 which includes this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants