Skip to content
This repository has been archived by the owner on Feb 23, 2022. It is now read-only.

Commit

Permalink
Merge pull request #355 from multinet-app/bad-csv
Browse files Browse the repository at this point in the history
Raise an exception when CSV reading fails
  • Loading branch information
waxlamp committed Mar 27, 2020
2 parents a79c6af + 6cc69bf commit d3a70b9
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions multinet/uploaders/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from dataclasses import dataclass

from multinet import db, util
from multinet.errors import AlreadyExists, ValidationFailed
from multinet.errors import AlreadyExists, FlaskTuple, ServerError, ValidationFailed
from multinet.util import decode_data
from multinet.validation import ValidationFailure, DuplicateKey, UnsupportedTable

Expand Down Expand Up @@ -49,6 +49,14 @@ class MissingBody(ValidationFailure):
"""Missing body in a CSV file."""


class CSVReadError(ServerError):
"""Exception for unprocessable CSV data."""

def flask_response(self) -> FlaskTuple:
"""Generate a 415 error for the read failure."""
return ("Could not read CSV data", "415 Unsupported Media Type")


def validate_csv(
rows: Sequence[MutableMapping], key_field: str = "_key", overwrite: bool = False
) -> None:
Expand Down Expand Up @@ -136,8 +144,11 @@ def upload(
# Read the request body into CSV format
body = decode_data(request.data)

# Type to a Dict rather than an OrderedDict
rows: List[Dict[str, str]] = list(csv.DictReader(StringIO(body)))
try:
# Type to a Dict rather than an OrderedDict
rows: List[Dict[str, str]] = list(csv.DictReader(StringIO(body)))
except csv.Error:
raise CSVReadError()

# Perform validation.
validate_csv(rows, key, overwrite)
Expand Down

0 comments on commit d3a70b9

Please sign in to comment.