PortalPy (version 1.0)
index
c:\portalpy\portalpy.py

The portalpy module for working with the ArcGIS Online and Portal APIs.

 
Modules
       
collections
copy
gzip
httplib
imghdr
json
logging
mimetools
mimetypes
os
re
tempfile
unicodedata
urllib
urllib2
urlparse

 
Classes
       
__builtin__.object
Portal

 
class Portal(__builtin__.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')
 
  Methods defined here:
__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=r'c:\users\davi3690\appdata\local\temp\2')
The Portal constructor. Requires URL and optionally username/password.
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.
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.
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'})
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.
delete_user(self, username, cascade=False, 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
    choose to cascade then those items and groups will be reassigned to
    the user identified in the reassign_to option.  If you choose not to cascade
    the deletion will either succeed or fail depending on whether the user's items
    and groups have previously been transferred.
    
    When cascading, this method will delete up to 10,000 items.  If the user
    has more than 10,000 items the method will fail.  
 
Arguments
     username       required string, the name of the user
     cascade:       optional boolean, true means reassign items and groups
     reassign_to    optional string, new owner of items and groups
 
Returns
    a boolean indicating whether the operation succeeded or failed.
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
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).
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
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)
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']
get_properties(self, force=False)
Returns the portal properties (using cache unless force=True).
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
get_version(self, force=False)
Returns the portal version (using cache unless force=True). 
 
Note:
    The version information is retrieved when you create the
    Portal object and then cached for future requests.  If you
    want to make a request to the Portal and not rely on the
    cache then you can set the force argument to True.
    
Arguments:
    force        boolean, true=make a request, false=use cache
    
Returns
    a string with the version.  The version is an internal number
    that may not match the version of the product purchased.  So
    2.3 is returned from Portal 10.2.1 for instance.
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.
is_all_ssl(self)
Returns true if this portal requires SSL.
is_arcgisonline(self)
Returns true if this portal is ArcGIS Online.
is_logged_in(self)
Returns true if logged into the portal.
is_multitenant(self)
Returns true if this portal is multitenant.
is_org(self)
Returns true if this portal is an organization.
is_subscription(self)
Returns true if this portal is an ArcGIS Online subscription.
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.
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
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
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.
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
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.
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
search(self, q, bbox=None, sort_field='title', sort_order='asc', max_results=1000, add_org=True)
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
search_users(self, q, sort_field='username', sort_order='asc', max_users=1000, add_org=True)
Searches portal users. 
 
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 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 dictionary object 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
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
update_group(self, group_id, title=None, tags=None, description=None, snippet=None, access=None, is_invitation_only=None, sort_field=None, sort_order=None, is_view_only=None, thumbnail=None)
Updates a group.
 
Note
    Only provide the values for the arguments you wish to update.
    
Arguments
    group_id              required string, the group to modify
    title                 optional string, name of the group
    tags                  optional 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 or file location to group image
    is_invitation_only    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 boolean indicating success
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
update_user_role(self, username, role)
Updates a user's role.
 
Notes
    There are three types of roles in Portal - user, publisher, and administrator.
    A user can share items, create maps, create groups, etc.  A publisher can 
    do everything a user can do and create hosted services.  An administrator can 
    do everything that is possible in Portal.
    
Arguments
    username        required string, the name of the user whose role will change
    role            required string, one of these values org_user, org_publisher, org_admin
 
Returns
    a boolean, that indicates success