2016-12-21 50 views
1

我試圖更新CKAN的一個實例中的資源。我正在使用demo.ckan.org進行一些測試。使用python更新CKAN中的資源

我能夠使用curl創建和更新數據集的資源,但使用python我無法做到這一點。

我的起點是此鏈接: http://docs.ckan.org/en/latest/maintaining/filestore.html#filestore-api

這是代碼:

import requests 
requests.post('http://0.0.0.0:5000/api/action/resource_create', 
       data={"package_id":"my_dataset"}, 
       headers={"X-CKAN-API-Key": "21a47217-6d7b-49c5-88f9-72ebd5a4d4bb"}, 
       files=[('upload', file('/path/to/file/to/upload.csv'))]) 

我捲曲代碼工作正常,所以我試圖適應它:

curl -X POST http://demo.ckan.org/api/3/action/resource_update -d '{"id":"5b75fdf2-df9c-4a4f-bb28-d78ea7bc4e48", "url": "http://82.98.156.2/ckan_api/public_html/restaurantes.geojson", "name": "Better Restaurants", "format":"GEOJSON", "description":"Description of the resource"}' -H "Authorization: 97caad21-8632-4372-98fe-a24cdcaa90dc" 

這應該是python中的代碼:

resource_dict = { 
    'id': '5b75fdf2-df9c-4a4f-bb28-d78ea7bc4e48', 
    'name':'REstaurantes con PYTHON', 
    'url':'http://82.98.156.2/ckan_api/public_html/restaurantes.geojson', 
    'description':'Description in PYTHON' 
} 
resource_dict = urllib.quote(json.dumps(resource_dict)) 
requests.post('http://demo.ckan.org/api/3/action/resource_update', 
       data=resource_dict, 
       headers={"Authorization: 97caad21-8632-4372-98fe-a24cdcaa90dc"}) 

我發現這個老鏈接: Create CKAN dataset using CKAN API and Python Requests library

在結束其建議添加一些信息,但我可以想出去做。

任何建議???

回答

1

這似乎工作:

resource_dict = {'id': '5b75fdf2-df9c-4a4f-bb28-d78ea7bc4e48', 
       'name':'REstaurantes con PYTHON', 
       'url':'http://82.98.156.2/ckan_api/public_html/restaurantes.geojson', 
       'description':'Description in PYTHON'} 
requests.post('http://demo.ckan.org/api/3/action/resource_update', 
      json=resource_dict, 
      headers={"Authorization": "97caad21-8632-4372-98fe-a24cdcaa90dc"}) 

至少state_code200,我響應了"success": true

請注意,{"Authorization: 97caad21-8632-4372-98fe-a24cdcaa90dc"}在你的代碼的數據類型爲class 'set'headers應該得到的class 'dict'數據,如"Authorization": "97caad21-8632-4372-98fe-a24cdcaa90dc"}

+0

真棒!!,感謝安德森 – davisoski

2

不要蟒蛇,請求麻煩 - 這是最容易在Python中使用優秀的ckanapi庫。例如

import ckanapi 
ckan = ckanapi.RemoteCKAN('http://demo.ckan.org/', apikey='97caad21-8632-4372-98fe-a24cdcaa90dc', user_agent='ckanapi so test') 
resource_dict = { 
    'id': '5b75fdf2-df9c-4a4f-bb28-d78ea7bc4e48', 
    'package_id': 'cdcf576d-0b09-4df0-a506-61a7142d2b8f', 
    'name':'Restaurantes con PYTHON', 
    'url':'http://82.98.156.2/ckan_api/public_html/restaurantes.geojson', 
    'description':'Description in PYTHON', 
    'format':'GEOJSON' 
} 
ckan.action.resource_update(**resource_dict) 
+0

偉大的作品!,謝謝 – davisoski

+1

大,請使用贊成票,並選擇最佳答案即可。 –

+0

我正在計算查看哪個選項更快但兩者相同的時間 – davisoski