forked from Esri/portalpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
portalpy.py
1739 lines (1386 loc) · 68.4 KB
/
portalpy.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" The portalpy module for working with the ArcGIS Online and Portal APIs."""
__version__ = '1.0'
import collections
import copy
import gzip
import httplib
import imghdr
import json
import logging
import mimetools
import mimetypes
import os
import re
import tempfile
import unicodedata
import urllib
import urllib2
import urlparse
from cStringIO import StringIO
_log = logging.getLogger(__name__)
class Portal(object):
""" An object representing a connection to a single portal (via URL).
Notes:
To instantiate a Portal object execute code like this:
PortalPy.Portal(portalUrl, user, password)
There are a few things you should know as you use the methods below.
Group IDs
Many of the group functions require a group id. This id is
different than the group's name or title. To determine
a group id, use the search_groups function using the title
to get the group id.
Time
Many of the methods return a time field. All time is
returned as millseconds since 1 January 1970. Python
expects time in seconds since 1 January 1970 so make sure
to divide times from PortalPy by 1000. See the example
a few lines down to see how to convert from PortalPy time
to Python time.
Example - converting time
import time
.
.
.
group = portalAdmin.get_group('67e1761068b7453693a0c68c92a62e2e')
pythontime = time.ctime(group['created']/1000)
Example - list users in group
portal = PortalPy.Portal(portalUrl, user, password)
resp = portal.get_group_members('67e1761068b7453693a0c68c92a62e2e')
for user in resp['users']:
print user
Example - create a group
portal= PortalPy.Portal(portalUrl, user, password)
group_id = portalAdmin.create_group('my group', 'test tag', 'a group to share travel maps')
Example - delete a user named amy and assign her content to bob
portal= PortalPy.Portal(portalUrl, user, password)
portal.delete_user('amy.user', True, 'bob.user')
"""
def __init__(self, url, username=None, password=None, key_file=None,
cert_file=None, expiration=60, referer=None, proxy_host=None,
proxy_port=None, connection=None, workdir=tempfile.gettempdir()):
""" The Portal constructor. Requires URL and optionally username/password."""
self.url = url
if url:
normalized_url = _normalize_url(self.url)
if not normalized_url[-1] == '/':
normalized_url += '/'
self.resturl = normalized_url + 'sharing/rest/'
self.hostname = _parse_hostname(url)
self.workdir = workdir
# Setup the instance members
self._basepostdata = { 'f': 'json' }
self._version = None
self._properties = None
self._logged_in_user = None
self._resources = None
self._languages = None
self._regions = None
self._is_pre_162 = False
self._is_pre_21 = False
# If a connection was passed in, use it, otherwise setup the
# connection (use all SSL until portal informs us otherwise)
if connection:
_log.debug('Using existing connection to: ' + \
_parse_hostname(connection.baseurl))
self.con = connection
if not connection:
_log.debug('Connecting to portal: ' + self.hostname)
self.con = _ArcGISConnection(self.resturl, username, password,
key_file, cert_file, expiration, True,
referer, proxy_host, proxy_port)
# Store the logged in user information. It's useful.
if self.is_logged_in():
self._logged_in_user = self.get_user(username)
self.get_version(True)
self.get_properties(True)
def add_group_users(self, user_names, group_id):
""" Adds users to the group specified.
Note:
This method will only work if the user for the
Portal object is either an administrator for the entire
Portal or the owner of the group.
Arguments
user_names required string, comma-separated users
group_id required string, specifying group id
Returns
A dictionary with a key of "not_added" which contains the users that were not
added to the group.
"""
if self._is_pre_21:
_log.warning('The auto_accept option is not supported in ' \
+ 'pre-2.0 portals')
return
user_names = _unpack(user_names, 'username')
postdata = self._postdata()
postdata['users'] = ','.join(user_names)
resp = self.con.post('community/groups/' + group_id + '/addUsers',
postdata)
return resp
def create_group_from_dict(self, group, thumbnail=None):
""" Creates a group and returns a group id if successful.
Note
Use create_group in most cases. This method is useful for taking a group
dict returned from another PortalPy call and copying it.
Arguments
group dict object
thumbnail url to image
Example
create_group({'title': 'Test', 'access':'public'})
"""
postdata = self._postdata()
postdata.update(_unicode_to_ascii(group))
# Build the files list (tuples)
files = []
if thumbnail:
if _is_http_url(thumbnail):
thumbnail = urllib.urlretrieve(thumbnail)[0]
file_ext = os.path.splitext(thumbnail)[1]
if not file_ext:
file_ext = imghdr.what(thumbnail)
if file_ext in ('gif', 'png', 'jpeg'):
new_thumbnail = thumbnail + '.' + file_ext
os.rename(thumbnail, new_thumbnail)
thumbnail = new_thumbnail
files.append(('thumbnail', thumbnail, os.path.basename(thumbnail)))
# Send the POST request, and return the id from the response
resp = self.con.post('community/createGroup', postdata, files)
if resp and resp.get('success'):
return resp['group']['id']
def create_group(self, title, tags, description=None,
snippet=None, access='public', thumbnail=None,
is_invitation_only=False, sort_field='avgRating',
sort_order='desc', is_view_only=False, ):
""" Creates a group and returns a group id if successful.
Arguments
title required string, name of the group
tags required string, comma-delimited list of tags
description optional string, describes group in detail
snippet optional string, <250 characters summarizes group
access optional string, can be private, public, or org
thumbnail optional string, URL to group image
isInvitationOnly optional boolean, defines whether users can join by request.
sort_field optional string, specifies how shared items with the group are sorted.
sort_order optional string, asc or desc for ascending or descending.
is_view_only optional boolean, defines whether the group is searchable
Returns
a string that is a group id.
"""
return self.create_group_from_dict({'title' : title, 'tags' : tags,
'snippet' : snippet, 'access' : access,
'sortField' : sort_field, 'sortOrder' : sort_order,
'isViewOnly' : is_view_only,
'isinvitationOnly' : is_invitation_only}, thumbnail)
def delete_group(self, group_id):
""" Deletes a group.
Arguments
group_id is a string containing the id for the group to be deleted.
Returns
a boolean indicating whether it was successful.
"""
resp = self.con.post('community/groups/' + group_id + '/delete',
self._postdata())
if resp:
return resp.get('success')
def delete_user(self, username, reassign_to=None):
""" Deletes a user from the portal, optionally deleting or reassigning groups and items.
Notes
You can not delete a user in Portal if that user owns groups or items. If you
specify someone in the reassign_to argument then items and groups will be
transferred to that user. If that argument is not set then the method
will fail if the user has items or groups that need to be reassigned.
Arguments
username required string, the name of the user
reassign_to optional string, new owner of items and groups
Returns
a boolean indicating whether the operation succeeded or failed.
"""
if reassign_to :
self.reassign_user(username, reassign_to)
resp = self.con.post('community/users/' + username + '/delete',self._postdata())
if resp:
return resp.get('success')
else:
return False
def generate_token(self, username, password, expiration=60):
""" Generates and returns a new token, but doesn't re-login.
Notes
This method is not needed when using the Portal class
to make calls into Portal. It's provided for the benefit
of making calls into Portal outside of the Portal class.
Portal uses a token-based authentication mechanism where
a user provides their credentials and a short-term token
is used for calls. Most calls made to the Portal REST API
require a token and this can be appended to those requests.
Arguments
username required string, name of the user
password required password, name of the user
expiration optional integer, number of minutes until the token expires
Returns
a string with the token
"""
return self.con.generate_token(username, password, expiration)
def get_group(self, group_id):
""" Returns group information for the specified group group_id.
Arguments
group_id : required string, indicating group.
Returns
a dictionary object with the group's information. The keys in
the dictionary object will often include:
title: the name of the group
isInvitationOnly: if set to true, users can't apply to join the group.
owner: the owner username of the group
description: explains the group
snippet: a short summary of the group
tags: user-defined tags that describe the group
phone: contact information for group.
thumbnail: File name relative to http://<community-url>/groups/<groupId>/info
created: When group created, ms since 1 Jan 1970
modified: When group last modified. ms since 1 Jan 1970
access: Can be private, org, or public.
userMembership: A dict with keys username and memberType.
memberType: provides the calling user's access (owner, admin, member, none).
"""
return self.con.post('community/groups/' + group_id, self._postdata())
def get_group_thumbnail(self, group_id):
""" Returns the bytes that make up the thumbnail for the specified group group_id.
Arguments
group_id: required string, specifies the group's thumbnail
Returns
bytes that representt he image.
Example
response = portal.get_group_thumbnail("67e1761068b7453693a0c68c92a62e2e")
f = open(filename, 'wb')
f.write(response)
"""
thumbnail_file = self.get_group(group_id).get('thumbnail')
if thumbnail_file:
thumbnail_url_path = 'community/groups/' + group_id + '/info/' + thumbnail_file
if thumbnail_url_path:
return self.con.get(thumbnail_url_path, try_json=False)
def get_group_members(self, group_id):
""" Returns members of the specified group.
Arguments
group_id: required string, specifies the group
Returns
a dictionary with keys: owner, admins, and users.
owner string value, the group's owner
admins list of strings, typically this is the same as the owner.
users list of strings, the members of the group
Example (to print users in a group)
response = portal.get_group_members("67e1761068b7453693a0c68c92a62e2e")
for user in response['users'] :
print user
"""
return self.con.post('community/groups/' + group_id + '/users',
self._postdata())
def get_org_users(self, max_users=1000):
""" Returns all users within the portal organization.
Arguments
max_users : optional int, the maximum number of users to return.
Returns
a list of dicts. Each dict has the following keys:
username : string
storageUsage: int
storageQuota: int
description: string
tags: list of strings
region: string
created: int, when account created, ms since 1 Jan 1970
modified: int, when account last modified, ms since 1 Jan 1970
email: string
culture: string
orgId: string
preferredView: string
groups: list of strings
role: string (org_user, org_publisher, org_admin)
fullName: string
thumbnail: string
idpUsername: string
Example (print all usernames in portal):
resp = portalAdmin.get_org_users()
for user in resp:
print user['username']
"""
# Execute the search and get back the results
count = 0
resp = self._org_users_page(1, min(max_users, 100))
resp_users = resp.get('users')
results = resp_users
count += int(resp['num'])
nextstart = int(resp['nextStart'])
while count < max_users and nextstart > 0:
resp = self._org_users_page(nextstart, min(max_users - count, 100))
resp_users = resp.get('users')
results.extend(resp_users)
count += int(resp['num'])
nextstart = int(resp['nextStart'])
return results
def get_properties(self, force=False):
""" Returns the portal properties (using cache unless force=True). """
# If we've never retrieved the properties before, or the caller is
# forcing a check of the server, then check the server
if not self._properties or force:
path = 'accounts/self' if self._is_pre_162 else 'portals/self'
resp = self.con.post(path, self._postdata(), ssl=True)
if resp:
self._properties = resp
self.con.all_ssl = self.is_all_ssl()
# Return a defensive copy
return copy.deepcopy(self._properties)
def get_user(self, username):
""" Returns the user information for the specified username.
Arguments
username required string, the username whose information you want.
Returns
None if the user is not found and returns a dictionary object if the user is found
the dictionary has the following keys:
access string
created time (int)
culture string, two-letter language code ('en')
description string
email string
fullName string
idpUsername string, name of the user in the enterprise system
groups list of dictionaries. For dictionary keys, see get_group doc.
modified time (int)
orgId string, the organization id
preferredView string, value is either Web, GIS, or null
region string, None or two letter country code
role string, value is either org_user, org_publisher, org_admin
storageUsage int
storageQuota int
tags list of strings
thumbnail string, name of file
username string, name of user
"""
return self.con.post('community/users/' + username, self._postdata())
def invite_group_users(self, user_names, group_id,
role='group_member', expiration=10080):
""" Invites users to a group.
Notes:
A user who is invited to a group will see a list of invitations
in the "Groups" tab of portal listing invitations. The user
can either accept or reject the invitation.
Requires
The user executing the command must be group owner
Arguments
user_names: a required string list of users to invite
group_id : required string, specifies the group you are inviting users to.
role: an optional string, either group_member or group_admin
expiration: an optional int, specifies how long the invitation is valid for in minutes.
Returns
a boolean that indicates whether the call succeeded.
"""
user_names = _unpack(user_names, 'username')
# Send out the invitations
postdata = self._postdata()
postdata['users'] = ','.join(user_names)
postdata['role'] = role
postdata['expiration'] = expiration
resp = self.con.post('community/groups/' + group_id + '/invite',
postdata)
if resp:
return resp.get('success')
def is_logged_in(self):
""" Returns true if logged into the portal. """
return self.con.is_logged_in()
def is_all_ssl(self):
""" Returns true if this portal requires SSL. """
# If properties aren't set yet, return true (assume SSL until the
# properties tell us otherwise)
if not self._properties:
return True
# If access property doesnt exist, will correctly return false
return self._properties.get('allSSL')
def is_multitenant(self):
""" Returns true if this portal is multitenant. """
return self._properties['portalMode'] == 'multitenant'
def is_arcgisonline(self):
""" Returns true if this portal is ArcGIS Online. """
return self._properties['portalName'] == 'ArcGIS Online' \
and self.is_multitenant()
def is_subscription(self):
""" Returns true if this portal is an ArcGIS Online subscription. """
return bool(self._properties.get('urlKey'))
def is_org(self):
""" Returns true if this portal is an organization. """
return bool(self._properties.get('id'))
def leave_group(self, group_id):
""" Removes the logged in user from the specified group.
Requires:
User must be logged in.
Arguments:
group_id: required string, specifies the group id
Returns:
a boolean indicating whether the operation was successful.
"""
resp = self.con.post('community/groups/' + group_id + '/leave',
self._postdata())
if resp:
return resp.get('success')
def login(self, username, password, expiration=60):
""" Logs into the portal using username/password.
Notes:
You can log into a portal when you construct a portal
object or you can login later. This function is
for the situation when you need to log in later.
Arguments
username: required string
password: required string
expiration: optional int, how long the token generated should last.
Returns
a string, the token
"""
newtoken = self.con.login(username, password, expiration)
if newtoken:
self._logged_in_user = self.get_user(username)
return newtoken
def logout(self):
""" Logs out of the portal.
Notes
The portal will forget any existing tokens it was using, all
subsequent portal calls will be anonymous until another login
call occurs.
Returns
No return value.
"""
self.con.logout()
def logged_in_user(self):
""" Returns information about the logged in user.
Returns
a dict with the following keys:
username string
storageUsage int
description string
tags comma-separated string
created int, when group created (ms since 1 Jan 1970)
modified int, when group last modified (ms since 1 Jan 1970)
fullName string
email string
idpUsername string, name of the user in their identity provider
"""
if self._logged_in_user:
# Return a defensive copy
return copy.deepcopy(self._logged_in_user)
return None
def reassign_user(self, username, target_username):
""" Reassigns all of a user's items and groups to another user.
Items are transferred to the target user into a folder named
<user>_<folder> where user corresponds to the user whose items were
moved and folder corresponds to the folder that was moved.
Note:
This method must be executed as an administrator. This method also
can not be undone. The changes are immediately made and permanent.
Arguments
username : required string, user who will have items/groups transferred
target_username : required string, user who will own items/groups after this.
Returns
a boolean indicating success
"""
postdata = self._postdata()
postdata['targetUsername'] = target_username
resp = self.con.post('community/users/' + username + '/reassign', postdata)
if resp:
return resp.get('success')
def reassign_group(self, group_id, target_owner):
""" Reassigns a group to another owner.
Arguments
group_id : required string, unique identifier for the group
target_owner: required string, username of new group owner
Returns
a boolean, indicating success
"""
postdata = self._postdata()
postdata['targetUsername'] = target_owner
resp = self.con.post('community/groups/' + group_id + '/reassign', postdata)
if resp:
return resp.get('success')
def reset_user(self, username, password, new_password=None,
new_security_question=None, new_security_answer=None):
""" Resets a user's password, security question, and/or security answer.
Notes
This function does not apply to those using enterprise accounts
that come from an enterprise such as ActiveDirectory, LDAP, or SAML.
It only has an effect on built-in users.
If a new security question is specified, a new security answer should
be provided.
Arguments
username required string, account being reset
password required string, current password
new_password optional string, new password if resetting password
new_security_question optional int, new security question if desired
new_security_answer optional string, new security question answer if desired
Returns
a boolean, indicating success
"""
postdata = self._postdata()
postdata['password'] = password
if new_password:
postdata['newPassword'] = new_password
if new_security_question:
postdata['newSecurityQuestionIdx'] = new_security_question
if new_security_answer:
postdata['newSecurityAnswer'] = new_security_answer
resp = self.con.post('community/users/' + username + '/reset',
postdata, ssl=True)
if resp:
return resp.get('success')
def remove_group_users(self, user_names, group_id):
""" Remove users from a group.
Arguments:
user_names required string, comma-separated list of users
group_id required string, the id for a group.
Returns:
a dictionary with a key notRemoved that is a list of users not removed.
"""
user_names = _unpack(user_names, 'username')
# Remove the users from the group
postdata = self._postdata()
postdata['users'] = ','.join(user_names)
resp = self.con.post('community/groups/' + group_id + '/removeUsers',
postdata)
return resp
def search(self, q, bbox=None, sort_field='title', sort_order='asc',
max_results=1000, add_org=True):
if add_org:
accountid = self._properties.get('id')
if accountid and q:
q += ' accountid:' + accountid
elif accountid:
q = 'accountid:' + accountid
count = 0
resp = self._search_page(q, bbox, 1, min(max_results, 100), sort_field, sort_order)
results = resp.get('results')
count += int(resp['num'])
nextstart = int(resp['nextStart'])
while count < max_results and nextstart > 0:
resp = self._search_page(q, bbox, nextstart, min(max_results - count, 100),
sort_field, sort_order)
results.extend(resp['results'])
count += int(resp['num'])
nextstart = int(resp['nextStart'])
return results
def search_groups(self, q, sort_field='title',sort_order='asc',
max_groups=1000, add_org=True):
""" Searches for portal groups.
Notes
A few things that will be helpful to know.
1. The query syntax has quite a few features that can't
be adequately described here. The query syntax is
available in ArcGIS help. A short version of that URL
is http://bitly.com/1fJ8q31.
2. Most of the time when searching groups you want to
search within your organization in ArcGIS Online
or within your Portal. As a convenience, the method
automatically appends your organization id to the query by
default. If you don't want the API to append to your query
set add_org to false.
Arguments
q required string, query string. See notes.
sort_field optional string, valid values can be title, owner, created
sort_order optional string, valid values are asc or desc
max_groups optional int, maximum number of groups returned
add_org optional boolean, controls whether to search within your org
Returns
A list of dictionaries. Each dictionary has the following keys.
access string, values=private, org, public
created int, ms since 1 Jan 1970
description string
id string, unique id for group
isInvitationOnly boolean
isViewOnly boolean
modified int, ms since 1 Jan 1970
owner string, user name of owner
phone string
snippet string, short summary of group
sortField string, how shared items are sorted
sortOrder string, asc or desc
tags string list, user supplied tags for searching
thumbnail string, name of file. Append to http://<community url>/groups/<group id>/info/
title string, name of group as shown to users
"""
if add_org:
accountid = self._properties.get('id')
if accountid and q:
q += ' accountid:' + accountid
elif accountid:
q = 'accountid:' + accountid
# Execute the search and get back the results
count = 0
resp = self._groups_page(q, 1, min(max_groups,100), sort_field, sort_order)
results = resp.get('results')
count += int(resp['num'])
nextstart = int(resp['nextStart'])
while count < max_groups and nextstart > 0:
resp = self._groups_page(q, 1, min(max_groups - count,100),
sort_field, sort_order)
resp_users = resp.get('results')
results.extend(resp_users)
count += int(resp['num'])
nextstart = int(resp['nextStart'])
return results
def search_users(self, q, sort_field='username',
sort_order='asc', max_users=1000, add_org=True):
""" Searches portal users.
This gives you a list of users and some basic information
about those users. To get more detailed information (such as role), you
may need to call get_user on each user.
Notes
A few things that will be helpful to know.
1. The query syntax has quite a few features that can't
be adequately described here. The query syntax is
available in ArcGIS help. A short version of that URL
is http://bitly.com/1fJ8q31.
2. Most of the time when searching groups you want to
search within your organization in ArcGIS Online
or within your Portal. As a convenience, the method
automatically appends your organization id to the query by
default. If you don't want the API to append to your query
set add_org to false. If you use this feature with an
OR clause such as field=x or field=y you should put this
into parenthesis when using add_org.
Arguments
q required string, query string. See notes.
sort_field optional string, valid values can be username or created
sort_order optional string, valid values are asc or desc
max_users optional int, maximum number of users returned
add_org optional boolean, controls whether to search within your org
Returns
A a list of dictionary objects with the following keys:
created time (int), when user created
culture string, two-letter language code
description string, user supplied description
fullName string, name of the user
modified time (int), when user last modified
region string, may be None
tags string list, of user tags
thumbnail string, name of file
username string, name of the user
"""
if add_org:
accountid = self._properties.get('id')
if accountid and q:
q += ' accountid:' + accountid
elif accountid:
q = 'accountid:' + accountid
# Execute the search and get back the results
count = 0
resp = self._users_page(q, 1, min(max_users, 100), sort_field, sort_order)
results = resp.get('results')
count += int(resp['num'])
nextstart = int(resp['nextStart'])
while count < max_users and nextstart > 0:
resp = self._users_page(q, nextstart, min(max_users - count, 100),
sort_field, sort_order)
resp_users = resp.get('results')
results.extend(resp_users)
count += int(resp['num'])
nextstart = int(resp['nextStart'])
return results
# Used to signup a new user to an on-premises portal.
def signup(self, username, password, fullname, email):
""" Signs up users to an instance of Portal for ArcGIS.
Notes:
This method only applies to Portal and not ArcGIS
Online. This method can be called anonymously, but
keep in mind that self-signup can also be disabled
in a Portal. It also only creates built-in
accounts, it does not work with enterprise
accounts coming from ActiveDirectory or your
LDAP.
There is another method called createUser that
requires administrator access that can always
be used against 10.2.1 portals or later that
can create users whether they are builtin or
enterprise accounts.
Arguments
username required string, must be unique in the Portal, >4 characters
password required string, must be >= 8 characters.
fullname required string, name of the user
email required string, must be an email address
Returns
a boolean indicating success
"""
if self.is_arcgisonline():
raise ValueError('Signup is not supported on ArcGIS Online')
postdata = self._postdata()
postdata['username'] = username
postdata['password'] = password
postdata['fullname'] = fullname
postdata['email'] = email
resp = self.con.post('community/signUp', postdata, ssl=True)
if resp:
return resp.get('success')
def update_user(self, username, access=None, preferred_view=None,
description=None, tags=None, thumbnail=None,
fullname=None, email=None, culture=None,
region=None):
""" Updates a user's properties.
Note:
Only pass in arguments for properties you want to update.
All other properties will be left as they are. If you
want to update description, then only provide
the description argument.
Arguments:
username required string, name of the user to be updated.
access optional string, values: private, org, public
preferred_view optional string, values: Web, GIS, null
description optional string, a description of the user.
tags optional string, comma-separated tags for searching
thumbnail optional string, path or url to a file. can be PNG, GIF,
JPEG, max size 1 MB
fullname optional string, name of the user, only for built-in users
email optional string, email address, only for built-in users
culture optional string, two-letter language code, fr for example
region optional string, two-letter country code, FR for example
Returns
a boolean indicating success
"""
properties = dict()
postdata = self._postdata()
if access:
properties['access'] = access
if preferred_view:
properties['preferredView'] = preferred_view
if description:
properties['description'] = description
if tags:
properties['tags'] = tags
if fullname:
properties['fullname'] = fullname
if email:
properties['email'] = email
if culture:
properties['culture'] = culture
if region:
properties['region'] = region
files = []
if thumbnail:
if _is_http_url(thumbnail):
thumbnail = urllib.urlretrieve(thumbnail)[0]
file_ext = os.path.splitext(thumbnail)[1]
if not file_ext:
file_ext = imghdr.what(thumbnail)
if file_ext in ('gif', 'png', 'jpeg'):
new_thumbnail = thumbnail + '.' + file_ext
os.rename(thumbnail, new_thumbnail)
thumbnail = new_thumbnail
files.append(('thumbnail', thumbnail, os.path.basename(thumbnail)))
postdata.update(properties)
# Send the POST request, and return the id from the response
resp = self.con.post('community/users/' + username + '/update', postdata, files, ssl=True)
if resp:
return resp.get('success')