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
GP2-1398_comtrade_data_copy #838
Merged
Merged
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
6234ef9
GP2-1398_comtrade_data_copy
bobmeredith 4743fbf
flake
bobmeredith 20c5760
Merge branch 'develop' into GP2-1398_comtrade_data_copy
bobmeredith f171175
missing utils
bobmeredith 6c3f492
Merge branch 'GP2-1398_comtrade_data_copy' of github.com:uktrade/dire…
bobmeredith c7484f1
fix some tests
bobmeredith 91d52cc
fix tests
bobmeredith 2599009
Add mgmt tests
bobmeredith 0a630d0
more tests
bobmeredith 9e7da1d
Add more tests
bobmeredith 97c594c
Response to review comments
bobmeredith File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
121 changes: 121 additions & 0 deletions
121
dataservices/management/commands/import_comtrade_data.py
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
import csv | ||
|
||
from django.conf import settings | ||
from django.core.management import BaseCommand | ||
from django.db import connection | ||
|
||
from core.helpers import get_s3_file_stream | ||
from dataservices.models import ComtradeReport | ||
|
||
|
||
class Command(BaseCommand): | ||
help = 'Import Comtrade data' | ||
|
||
def add_arguments(self, parser): | ||
# Positional arguments | ||
parser.add_argument('filenames', nargs='*', type=str) | ||
|
||
parser.add_argument( | ||
'--wipe', | ||
action='store_true', | ||
help='Wipe table before loading', | ||
) | ||
parser.add_argument( | ||
'--raw', | ||
action='store_true', | ||
help='load raw data files', | ||
) | ||
|
||
parser.add_argument( | ||
'--test', | ||
action='store_true', | ||
help='limit rowcount to 1000 for testing', | ||
) | ||
|
||
def load_raw_files(self, filenames): | ||
# Loads a raw file as downloaded from comtrade on top of existing data in db | ||
|
||
for filename in filenames: | ||
self.stdout.write(self.style.SUCCESS(f'******** Loading: {filename}')) | ||
with open(filename, 'r', encoding='utf-8-sig') as f: | ||
written = 0 | ||
read = 0 | ||
file_reader = csv.DictReader(f) | ||
for row in file_reader: | ||
read = read + 1 | ||
if row.get('Is Leaf Code') == '1': | ||
reporter_iso3 = row.get('Reporter ISO') | ||
partner_iso3 = row.get('Partner ISO') | ||
flow = row.get('Trade Flow') | ||
uk_or_world = None | ||
country_iso3 = None | ||
if reporter_iso3 == 'GBR' and flow == 'Export': | ||
uk_or_world = reporter_iso3 | ||
country_iso3 = partner_iso3 | ||
if partner_iso3 == 'WLD' and flow == 'Import': | ||
uk_or_world = partner_iso3 | ||
country_iso3 = reporter_iso3 | ||
if country_iso3 and uk_or_world: | ||
written = written + 1 | ||
report = ComtradeReport( | ||
country_iso3=country_iso3, | ||
year=row.get('Year'), | ||
classification=row.get('Classification'), | ||
commodity_code=row.get('Commodity Code'), | ||
trade_value=float(row.get('Trade Value (US$)') or '0'), | ||
uk_or_world=uk_or_world, | ||
) | ||
report.save() | ||
if written % 100 == 0: | ||
print(f'{read} read, {written} written', end='\r', flush=True) | ||
self.stdout.write(self.style.SUCCESS(f'{read} read, {written} written')) | ||
|
||
def populate_db_from_s3(self, filename, test): | ||
# Read from S3, write into local DB, hook up country table | ||
cursor = connection.cursor() | ||
filestream = get_s3_file_stream(filename or settings.COMTRADE_DATA_FILE_NAME) | ||
file_reader = csv.DictReader(filestream.split()) | ||
self.stdout.write('********* Loading comtrade data') | ||
written = 0 | ||
for row in file_reader: | ||
cursor.execute( | ||
"INSERT INTO \ | ||
dataservices_comtradereport \ | ||
(id, year, classification, commodity_code, trade_value, uk_or_world, country_iso3 )\ | ||
VALUES\ | ||
(%s, %s, %s, %s, %s, %s, %s)", | ||
[ | ||
row.get('id'), | ||
row.get('year'), | ||
row.get('classification'), | ||
row.get('commodity_code'), | ||
row.get('trade_value'), | ||
row.get('uk_or_world'), | ||
row.get('country_iso3'), | ||
], | ||
) | ||
|
||
written = written + 1 | ||
if written % 1000 == 0: | ||
print(f' {written} rows written', end='\r', flush=True) | ||
if written >= 1000 and test: | ||
break | ||
self.stdout.write(self.style.SUCCESS(f'Loaded table - {written} rows written')) | ||
|
||
self.stdout.write('Linking countries') | ||
cursor.execute( | ||
"UPDATE dataservices_comtradereport as d \ | ||
set country_id=c.id \ | ||
from dataservices_country as c where d.country_iso3=c.iso3;" | ||
) | ||
|
||
def handle(self, *args, **options): | ||
filenames = options['filenames'] | ||
if options['wipe']: | ||
ComtradeReport.objects.all().delete() | ||
elif filenames and options['raw']: | ||
self.load_raw_files(filenames) | ||
else: | ||
self.populate_db_from_s3(filenames and filenames[0], test=options['test']) | ||
|
||
self.stdout.write(self.style.SUCCESS('All done, bye!')) |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# Generated by Django 2.2.13 on 2021-02-19 08:48 | ||
|
||
from django.db import migrations, models | ||
import django.db.models.deletion | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('dataservices', '0023_auto_20210204_1009'), | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='ComtradeReport', | ||
fields=[ | ||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||
('year', models.IntegerField(blank=True, null=True)), | ||
('classification', models.CharField(max_length=3)), | ||
('country_iso3', models.CharField(max_length=3)), | ||
('uk_or_world', models.CharField(max_length=3)), | ||
('commodity_code', models.CharField(max_length=6)), | ||
('trade_value', models.DecimalField(blank=True, decimal_places=0, max_digits=15, null=True)), | ||
('country', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='dataservices.Country', verbose_name='Countries')), | ||
], | ||
), | ||
migrations.AddIndex( | ||
model_name='comtradereport', | ||
index=models.Index(fields=['commodity_code', 'country', 'uk_or_world'], name='dataservice_commodi_c61be8_idx'), | ||
), | ||
] |
This file contains 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
look like a typo here
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the spot.