-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.py
54 lines (45 loc) · 2.01 KB
/
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
import os
import urllib
import requests
import json
import pprint
import random
# Constants that have to be changed
AUTHORIZATION_CODE = '' or os.getenv('AUTHORIZATION_CODE')
CKAN_URL = '' or os.getenv('CKAN_URL')
# Put the details of the dataset we're going to create into a dict.
dataset_name = 'something_unique-' + str(random.randint(0, 10000)) # take care the name should be always unique
dataset_dict = {
'name': dataset_name,
'notes': 'Tra la la',
'owner_org': 'aadr',
}
# We'll use the package_create function to create a new dataset.
url = CKAN_URL + '/api/3/action/package_create'
# Creating a dataset requires an authorization header.
headers = {'Authorization': AUTHORIZATION_CODE,
'Content-Type': 'application/x-www-form-urlencoded'}
# Make the HTTP request.
response = requests.post(url,
data=urllib.quote(json.dumps(dataset_dict)), # here, we are converting the dictionary into
# '%7B%22notes%22%3A%20%22Tra%20la%20la%22%2C%20%22owner_org%22%3A%20%22aadr%22%2C%20%22name%22%3A%20%22something_unique-7625%22%7D'
headers=headers)
assert response.status_code == 200
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.content)
assert response_dict['success'] is True
# package_create returns the created package as its result.
created_package = response_dict['result']
pprint.pprint(created_package)
# upload the file resource
url = CKAN_URL + '/api/action/resource_create'
response = requests.post(url,
data={"package_id": dataset_name,
'url': ''}, # add this because validation will fail
headers={"X-CKAN-API-Key": AUTHORIZATION_CODE},
files=[('upload', file('test.txt'))])
# test everythin went well
assert response.status_code == 200
response_dict = json.loads(response.content)
pprint.pprint(response_dict['result'])