Creating a CKAN Dataset Using the CKAN API and Python Query Library

I am using CKAN version 2.2 and trying to automate the creation of a dataset and resource loading. It seems I cannot create a dataset using the python query library. I get a 400 error code. The code:

import requests, json

dataset_dict = {
    'name': 'testdataset',
    'notes': 'A long description of my dataset',
}

d_url = 'https://mywebsite.ca/api/action/package_create'
auth = {'Authorization': 'myKeyHere'}
f = [('upload', file('PathToMyFile'))]

r = requests.post(d_url, data=dataset_dict, headers=auth)

Oddly, I can create a new resource and upload the file using the python query library. The code is based on this documentation. The code:

import requests, json

res_dict = {
    'package_id':'testpackage',
    'name': 'testresource',
    'description': 'A long description of my resource!',
    'format':'CSV'
}

res_url = 'https://mywebsite.ca/api/action/resource_create'
auth = {'Authorization': 'myKey'}
f = [('upload', file('pathToMyFile'))]

r = requests.post(res_url, data=res_dict, headers=auth, files=f)

I can also create a dataset using the method in the CKAN documentation using the python built-in libraries. Documentation: CKAN 2.2

the code:

#!/usr/bin/env python
import urllib2
import urllib
import json
import pprint

# Put the details of the dataset we're going to create into a dict.
dataset_dict = {
    'name': 'test1',
    'notes': 'A long description of my dataset',
}

# Use the json module to dump the dictionary to a string for posting.
data_string = urllib.quote(json.dumps(dataset_dict))

# We'll use the package_create function to create a new dataset.
request = urllib2.Request('https://myserver.ca/api/action/package_create')

# Creating a dataset requires an authorization header.
request.add_header('Authorization', 'myKey')

# Make the HTTP request.
response = urllib2.urlopen(request, data_string)
assert response.code == 200

# Use the json module to load CKAN response into a dictionary.
response_dict = json.loads(response.read())
assert response_dict['success'] is True

# package_create returns the created package as its result.
created_package = response_dict['result']
pprint.pprint(created_package)

, . package_create resource_create , , . CKAN. - ?

.

+4
2

. . , , . JSON-, multipart/form-data, CKAN, .

, JSON, - . CKAN URL (application/x-www-form-urlencoded). - , , POST. , URL.

, , urllib, :

head['Content-Type'] = 'application/x-www-form-urlencoded'
in_dict = urllib.quote(json.dumps(in_dict))
r = requests.post(url, data=in_dict, headers=head)

.

+4

, , JSON.

( , ):

API CKAN, JSON- HTTP- POST URL- API CKAN.

urllib :

data_string = urllib.quote(json.dumps(dataset_dict))

( ), requests - dict JSON. - :

r = requests.post(d_url, data=json.dumps(dataset_dict), headers=auth)
+3

Source: https://habr.com/ru/post/1547658/


All Articles