Created
June 12, 2020 07:56
-
-
Save kharandziuk/08de1d24845b05dfaa6acfbfda3cd28e to your computer and use it in GitHub Desktop.
a scaffold for a django command to handle the file with test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| import csv | |
| import sys | |
| from datetime import datetime | |
| from django.utils.timezone import make_aware | |
| from django.core.management.base import BaseCommand | |
| from metrics import models | |
| class Command(BaseCommand): | |
| def add_arguments(self, parser): | |
| parser.add_argument("file", | |
| nargs='?', | |
| type=argparse.FileType('r'), | |
| default=sys.stdin | |
| ) | |
| def handle(self, *args, **options): | |
| input_file = options["file"] | |
| reader = csv.DictReader(input_file) | |
| for row in reader: | |
| dt = datetime.fromisoformat(row['timestamp']) | |
| row['timestamp'] = make_aware(dt) | |
| models.Metric.objects.create(**row) | |
| def test_can_upload(): | |
| f = io.StringIO( | |
| """id,timestamp,temperature,duration | |
| 96234,2019-07-09 11:31:10.548198,1551.4133321786408,0 days 00:34:56.389283463""" | |
| ) | |
| management.call_command('load_metrics_csv', file=f) | |
| assert models.Metric.objects.count() == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment