|
1 | | -from datetime import datetime |
2 | | -import html |
3 | 1 | from os.path import join |
4 | | -from io import BytesIO |
5 | 2 | import csv |
| 3 | +from operator import itemgetter |
6 | 4 |
|
7 | 5 | import requests |
8 | | -import openpyxl |
9 | 6 |
|
10 | | -def to_date(date_str): |
11 | | - return datetime.strptime(date_str, '%d %B %Y').date() |
| 7 | +url = 'https://api.hpc.tools/v2/public/plan' |
| 8 | +headers = ['Plan name', 'Plan code', 'Plan type', 'Plan year', 'Start date', 'End date'] |
12 | 9 |
|
13 | | -# via https://fts.unocha.org/plan-code-list-iati |
14 | | -url = 'https://fts.unocha.org/download/initiate/views_executable/xlsx?uri=/plan-code-list-iati&query%5Buri%5D=/plan-code-list-iati&query%5Bview_id%5D=plan_code_list_for_iati&query%5Bview_display%5D=page&query%5B_wrapper_format%5D=drupal_modal&view_id=plan_code_list_for_iati&view_display=page' |
15 | 10 | r = requests.get(url) |
16 | | -download_id = r.json()[0].get('download_id') |
17 | | - |
18 | | -r = requests.get(f'https://fts.unocha.org/download/{download_id}/download') |
19 | | -wb = openpyxl.load_workbook(BytesIO(r.content)) |
20 | | -sheet = wb['Export data'] |
21 | | -rows = [ |
22 | | - [ |
23 | | - html.unescape(str(cell.value)) if cell.value is not None else None |
24 | | - for cell in row |
25 | | - ] for row in sheet.rows] |
26 | | - |
27 | | -# bin the first 2 rows |
28 | | -rows = rows[2:] |
29 | | - |
30 | | -# pop the header row |
31 | | -headers = rows.pop(0) |
32 | | - |
33 | | -# standardise headers |
34 | | -headers = [h[0] + h[1:].lower() for h in headers] |
35 | | - |
36 | | -# zip it up |
37 | | -rows = [dict(zip(headers, row)) for row in rows] |
| 11 | +data = r.json() |
| 12 | +rows = [] |
38 | 13 |
|
39 | 14 | # fix the dates |
40 | | -for row in rows: |
41 | | - row['Start date'] = to_date(row['Start date']) |
42 | | - row['End date'] = to_date(row['End date']) |
| 15 | +for item in data['data']: |
| 16 | + rows.append({ |
| 17 | + 'Plan name': item['planVersion']['name'], |
| 18 | + 'Plan code': item['planVersion']['code'], |
| 19 | + 'Plan type': ",".join([it['name'] for it in item['categories'] if it['group'] == 'planType']), |
| 20 | + 'Plan year': ",".join([it['year'] for it in item['years']]), |
| 21 | + 'Start date': item['planVersion']['startDate'], |
| 22 | + 'End date': item['planVersion']['endDate'], |
| 23 | + }) |
| 24 | + |
| 25 | + |
| 26 | +rows.sort(key=itemgetter('Plan name')) |
| 27 | +rows.sort(key=itemgetter('Plan year'), reverse=True) |
43 | 28 |
|
44 | 29 | with open(join('output', 'humanitarian-plan.csv'), 'w') as f: |
45 | 30 | writer = csv.DictWriter(f, fieldnames=headers) |
|
0 commit comments