Skip to content
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

New Feature: Add Token #11

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
*.tar.gz
*.pyc
*.csv
*.sqlite
*.sqlite

env.sh
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,19 @@ $ pip install git+git://github.com/NuCivic/[email protected]#egg=pydkan
[true]
```
Check the examples folder, there are snippets for pretty much everything you can do with this library.

## New Feature: TOKEN

Now it is possible to use a token instead of a user+password combination.
In order to do that, you need to omit the password argument, and the user
argument will be understood as a token.

_Everything else works the same_

```python
>>> from dkan.client import DatasetAPI
>>> token = '123456789'
>>> uri = "http://docker:32770"
>>> api = DatasetAPI(uri, token)
...
```
31 changes: 23 additions & 8 deletions dkan/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,29 +34,38 @@ class DatasetAPI:
>>> user, password = ('admin', 'admin')
>>> api = DatasetAPI(uri, user, password)
"""
def __init__(self, dkan, user, password, debug=False):
def __init__(self, dkan, user, password=None, debug=False):
'''
If the password is None (no password provided), we assume the 'user'
argument is the token
'''
self.dkan = dkan
self.headers = {
'Accept': 'application/json',
}
self.cookies = {}
self.token = {}
self.debug = debug
self.login(user, password)


if password is None: # Assume Token
self.token = {
'services_token': user
}
else:
self.login(user, password)

def build_uri(self, path):
return os.path.join(self.dkan, path).replace('\\', '/')

def login(self, user, password):
"""Authenticates against the dkan site.

This method should not be called from user code. It authenticates
against the DKAN site in two steps. 1) it posts the user and password
to api/dataset/user/login and retrieves a cookie 2) it sets the acquired
cookie and posts against services/sessions/token to retrieve a token
that's going to be sent as a header for every request this client
builds.


:param user: Drupal user
:param password: Drupal Password
"""
Expand All @@ -80,7 +89,7 @@ def login(self, user, password):
message = 'pydkan client can\'t login.(%s %s)' % (login.status_code, login.content)
raise LoginError(message)

def node(self, action='index', **kwargs):
def node(self, action='index', params=None, **kwargs):
"""Interface to the node endpoint.

This method builds requests against the api/dataset/node endpoint. It is
Expand Down Expand Up @@ -118,14 +127,20 @@ def node(self, action='index', **kwargs):
'create': self.post,
'delete': self.delete
}

if params is None:
params = self.token
else:
params.update(self.token)

if not action in action_map.keys():
raise ValueError('action parameter should be one of the following: %s' % ', '.join(action_map.keys()))
if action not in ['index', 'retrieve']:
kwargs['headers'] = self.headers.copy()
kwargs['headers']['Content-Type'] = 'application/json'
if 'data' in kwargs.keys():
kwargs['data'] = json.dumps(kwargs['data'])
return action_map[action](uri, **kwargs)
return action_map[action](uri, params=params, **kwargs)

def get(self, uri, **kwargs):
return self.request(uri, 'GET', **kwargs)
Expand Down Expand Up @@ -172,7 +187,7 @@ def attach_file_to_node(self, file, node_id, field, update=0):
files = {
'files[1]': open(file, 'rb'),
}
return self.post(uri, headers=headers, data=data, files=files)
return self.post(uri, headers=headers, data=data, files=files, params=self.token)

@classmethod
def pretty_print_request(cls, req):
Expand Down
6 changes: 4 additions & 2 deletions examples/attach_file_to_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
uri = os.environ.get('DKAN_URI', False)
user = os.environ.get('DKAN_USER', 'admin')
password = os.environ.get('DKAN_PASSWORD', 'admin')
token = os.environ.get('TOKEN')

if uri:
api = DatasetAPI(uri, user, password, True)
# api = DatasetAPI(uri, user, password, True)
api = DatasetAPI(uri, token)
payload = {'parameters[type]': 'resource'}
nodes = api.node(params=payload).json()
resource = nodes[0]
Expand All @@ -21,4 +23,4 @@
resource = api.node('retrieve', node_id=resource['nid'])
print resource.json()['field_upload']
else:
print 'Please Set the dkan URL as an ENVIRONMENT variable'
print 'Please Set the dkan URL as an ENVIRONMENT variable'
7 changes: 5 additions & 2 deletions examples/create_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
uri = os.environ.get('DKAN_URI', False)
user = os.environ.get('DKAN_USER', 'admin')
password = os.environ.get('DKAN_PASSWORD', 'admin')
token = os.environ.get('TOKEN')

print uri, token

if uri:
api = DatasetAPI(uri, user, password, True)
api = DatasetAPI(uri, token)
data = {
'title': 'Test Dataset',
'type': 'dataset'
Expand All @@ -16,4 +19,4 @@
print dataset.status_code
print dataset.text
else:
print 'Please Set the dkan URL as an ENVIRONMENT variable'
print 'Please Set the dkan URL as an ENVIRONMENT variable'
6 changes: 4 additions & 2 deletions examples/delete_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
uri = os.environ.get('DKAN_URI', False)
user = os.environ.get('DKAN_USER', 'admin')
password = os.environ.get('DKAN_PASSWORD', 'admin')
token = os.environ.get('TOKEN')

if uri:
api = DatasetAPI(uri, user, password, True)
# api = DatasetAPI(uri, user, password, True)
api = DatasetAPI(uri, token)
data = {
'title': 'Test Dataset',
'type': 'dataset'
Expand All @@ -20,4 +22,4 @@
print op.status_code
print op.text
else:
print 'Please Set the dkan URL as an ENVIRONMENT variable'
print 'Please Set the dkan URL as an ENVIRONMENT variable'
8 changes: 5 additions & 3 deletions examples/full_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
uri = os.environ.get('DKAN_URI', False)
user = os.environ.get('DKAN_USER', 'admin')
password = os.environ.get('DKAN_PASSWORD', 'admin')
token = os.environ.get('TOKEN')

if uri:
api = DatasetAPI(uri, user, password, True)
# api = DatasetAPI(uri, user, password, True)
api = DatasetAPI(uri, token)
# Create dataset
print 'CREATE DATASET'
data = {
Expand All @@ -26,7 +28,7 @@
'und': {
'target_id': dataset_nid,
},

},
}
r = api.node('create', data=data)
Expand Down Expand Up @@ -55,4 +57,4 @@
r = api.node('retrieve', node_id=resource_nid)
print 'Response: %s\n\n' % r.text
else:
print 'Please Set the dkan URL as an ENVIRONMENT variable'
print 'Please Set the dkan URL as an ENVIRONMENT variable'
6 changes: 4 additions & 2 deletions examples/list_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
uri = os.environ.get('DKAN_URI', False)
user = os.environ.get('DKAN_USER', 'admin')
password = os.environ.get('DKAN_PASSWORD', 'admin')
token = os.environ.get('TOKEN')

if uri:
# Make the api authenticate properly
api = DatasetAPI(uri, user, password, True)
# api = DatasetAPI(uri, user, password, True)
api = DatasetAPI(uri, token)

# List datasets
params = {
Expand All @@ -18,4 +20,4 @@

print r.json()
else:
print 'Please Set the dkan URL as an ENVIRONMENT variable'
print 'Please Set the dkan URL as an ENVIRONMENT variable'
6 changes: 4 additions & 2 deletions examples/update_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
uri = os.environ.get('DKAN_URI', False)
user = os.environ.get('DKAN_USER', 'admin')
password = os.environ.get('DKAN_PASSWORD', 'admin')
token = os.environ.get('TOKEN')

if uri:
api = DatasetAPI(uri, user, password, True)
# api = DatasetAPI(uri, user, password, True)
api = DatasetAPI(uri, token)
data = {
'title': 'Test Dataset',
'type': 'dataset'
Expand All @@ -23,4 +25,4 @@
print r.status_code
print r.text
else:
print 'Please Set the dkan URL as an ENVIRONMENT variable'
print 'Please Set the dkan URL as an ENVIRONMENT variable'
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

setup(
name='pydkan',
version='0.1',
version='0.1.1',
author=u'NuCivic',
author_email='[email protected]',
license='BSD licence, see LICENCE.txt',
Expand All @@ -18,4 +18,4 @@
zip_safe=False,
entry_points = {},
install_requires=required,
)
)