Difference between revisions of "Python API Wrapper Tutorial"

[unchecked revision][checked revision]
(42 intermediate revisions by 3 users not shown)
Line 1: Line 1:
 
__NOTOC__
 
__NOTOC__
 +
<p class=msnote>'''Important notice:''' The Python API wrapper for the MailStore Server Administration API provided on this website, represents an example implementation of an API client. This wrapper should help system administrators and developers to quickly understand how the Administration API of MailStore Server works and how to use it in own scripts. Please understand that beyond this documentation no further support for the Python API wrapper is provided. Unless stated otherwise, the Pythin API wrapper as well as all related example scripts are released under the terms an conditions of the [[wikipedia:MIT_License|MIT License]].</p>
  
This document explains the installation and usage of the Python API Wrapper  library, which is meant to be an example implementation of a MailStore Server Administration API client. The Administration API allows you to develop scripts for administration of MailStore Server.
+
This document explains the installation and usage of the Python API wrapper for the MailStore Server Administration API. In order to prevent loss of data, service interruption or other problems, it is highly recommended to use a non-productive test environment for this tutorial as well as for script development in general. The 30-day-trial version of MailStore Server is perfectly suited for this.
  
<p class=msnote>'''Please note:''' It is strongly recommended to use a non-productive test environment for this tutorial as well as for script development in general, in order to prevent loss of data or other problems. For example, the 30-day-trial version of MailStore Server is perfectly suited for this.</p>
+
== Installation ==
 +
The API wrapper library is tested against Python 3.2 and newer and is compatible with 32bit and 64bit versions of Python.  
  
= Installation =
+
Python binaries for various operating systems can be downloaded from the [http://www.python.org/download/ Python download page] or installed using the package manager of most Linux distributions.
  
The API library is tested against Python 3.2 to Python 3.4. It is compatible with the 32bit and the 64bit versions of Python.  
+
Additionally create a folder "mailstore" in the Python's site-packages directory and extract the files from the [[Media:python-api-wrapper.zip|Python API wrapper library]] into this folder.
  
You can get Python binaries for various operating systems from the [http://www.python.org/download/ Python download page] or you can install it using the package manager of your Linux distribution.
+
In a UNIX like operating system the location of the site-packages directory can be found by executing the following command in a shell:
  
Additionally you need the [ftp://ftp.mailstore.com/pub/Scripts/Python/Python-MailStore-API-Wrapper.zip MailStore API library] which has to be installed in your Python's site-packages ''mailstore'' directory.  The location of the site-packages directory can be found with the following command
 
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
+
python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
 
</source>
 
</source>
  
= Log in =
+
In Windows the location of the site-packages directory can be found by opening a ''cmd'', navigating in the Python3 installation directory and executing the following command:
  
Before the API library can be used to it must first be imported with
+
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 +
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
 +
</source>
 +
 
 +
== Instantiating the API Client ==
 +
Before the API wrapper library can be used, it must first be imported with:
  
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
Line 24: Line 30:
 
</source>
 
</source>
  
Now you are able to instantiate the ''mailstore.server.Client'' class  
+
Now the ''mailstore.mgmt.ServerClient'' class can be instantiated as follows:
 +
 
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
serverClient = mailstore.server.Client(username="admin", password="admin", host="127.0.0.1", port=8463)
+
serverClient = mailstore.mgmt.ServerClient(username="admin", password="admin", host="127.0.0.1", port=8463)
 
</source>
 
</source>
  
Default values can be omitted. The admin/admin credentials are only valid when connecting from the MailStore Server computer itself to ''localhost''.
+
Default values can be omitted. The default admin credentials (username and password set to ''admin'') are only usable when connecting from the MailStore Server computer itself to ''localhost''. Find a listing of all default values in the following table:
Find a listing of all default values in the following table:
 
  
 
{| class="wikitable"
 
{| class="wikitable"
! width="250px" |Parameter
+
! width="150px" | Parameter
! Default Value
+
! width="100px" | Default Value
 +
! Description
 
|-
 
|-
| username  
+
| <tt>username</tt>
 
| admin
 
| admin
 +
| Username used for connecting to the API.
 
|-
 
|-
| password
+
| <tt>password</tt>
 
| admin
 
| admin
 +
| Password used for connecting to the API.
 
|-
 
|-
| host  
+
| <tt>host</tt>
 
| 127.0.0.1
 
| 127.0.0.1
 +
| Hostname or IP address of the MailStore Server computer.
 
|-
 
|-
| port
+
| <tt>port</tt>
 
| 8463
 
| 8463
 +
| TCP port on which MailStore Server is listening for API requests.
 
|-
 
|-
| autoHandleToken
+
| <tt>autoHandleToken</tt>
 
| True
 
| True
 +
| If set to ''True'', the caller does not need to handle tokens of long running tasks, but instead has to wait for the result. When set to ''False'' and the ''statusCode'' is ''running'', a status token is returned and must be handled appropriately by the caller of the method. Further details about token handling is described the corresponding section [[#Automatic Token Handling|Automatic Token Handling]] of this document.
 
|-
 
|-
| waitTime
+
| <tt>waitTime</tt>
| 1
+
| 1000
 +
| Specifies the number of milliseconds the API should wait for a final result. Otherwise the process is treated as ''running'', in which case token handling as defined by the status of ''autoHandleToken'' becomes necessary.
 
|-
 
|-
| logLevel
+
| <tt>callback</tt>
 +
| None
 +
| A callback function to which interim statuses of long running tasks should be passed. This allows keeping track of the tasks' progress even if  ''autoHandleToken'' is enabled. This can be quite useful in order to notify users about the progress without having to deal with the token logic as a whole.
 +
|-
 +
| <tt>logLevel</tt>
 
| 2
 
| 2
 +
| Has to be in the range ''0'' to ''4'', where 0 (''NONE'') has the lowest verbosity and 4 (''DEBUG'') the highest. The loglevels are defined in the following order (low to high verbosity) ''NONE'', ''ERROR'', ''WARNING'', ''INFO'' and ''DEBUG''. Log entries will always be printed to ''stdout''.
 +
|-
 +
| <tt>ignoreInvalidSSLCerts</tt>
 +
| False
 +
| Has to be set to ''True'' or ''False''. Has to be enabled if untrusted certificates are used, otherwise an error occurs when using recent Python versions (>= 3.4.3).
 
|}
 
|}
  
If ''autoHandleToken'' is enabled, you do not have to care about long running processes, instead you just have to wait for the result. When this value is set to ''False'', a status token is returned and you have to handle the token yourself. Further details about long running processes will be give later in this document.
+
== Invoking API Method ==
 +
After the API client has been successfully instantiated, API methods can easily be invoked. When the method call was successful, the ''statusCode'' is ''succeeded'' and the result is stored in the dictionary ''result'' as shown in the following example:
 +
 
 +
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 +
print(serverClient.GetServerInfo())
 +
 +
{'logOutput': None, 'statusText': None, 'error': None, 'percentProgress': None, 'token': None, 'result': {'machineName': 'WIN-2012-R2-X64', 'version': '9.0.3.9857'}, 'statusVersion': 2, 'statusCode': 'succeeded'}
 +
</source>
  
The ''waitTime'' value specifies the value that is passed to the ''get-status'' call. When you call a long running method like ''VerifyStore'', this is the amount of seconds you have to wait for a status update.
+
If ''autoHandleToken'' was set to ''False'' and the ''statusCode'' returns ''running'', manual token handling is required as described in the [[#Auto Handle Token|Automatic Token Handling]] section.
  
''logLevel'' has to be in the range ''0'' to ''4'' where loglevel 0 (''NONE'') has the lowest verbosity and 4 (''DEBUG'') the highest. The loglevels are defined in the following order (low to high verbosity) ''NONE'', ''ERROR'', ''WARNING'', ''INFO'' and ''DEBUG''.
+
For any other ''statusCode'' value than ''succeeded'' and ''running'' the occurrence of an error has to be assumed, in which further information such as the error message and error details are available in the dictionary ''error'' as shown below:
  
Log entries will be printed to ''stdout''.
+
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 +
userInfo = serverClient.GetUserInfo("john.doe")
  
= Invoking Simple Calls =
+
if userInfo["statusCode"] == 'succeeded':
 +
    print(userInfo["result"]["emailAddresses"])
 +
else:
 +
    print(userInfo["error"]["message"])
 +
</source>
  
Simple calls will always return immediately and not token handling is required.
+
=== Examples ===
 +
Create and print a list of all email addresses assigned to MailStore users.  
  
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
print(serverClient.GetServerInfo())
+
serverClient = mailstore.mgmt.ServerClient()
+
addresses = list()
{'machineName': 'WIN2012MS', 'version': '8.1.2.9268'}
+
for user in serverClient.GetUsers()["result"]:
 +
addresses += serverClient.GetUserInfo(user["userName"])["result"]["emailAddresses"]
 +
print("\n".join(sorted(set(addresses))))
 
</source>
 
</source>
  
When the call was successful the information is stored in the returned Python dictionary. When it failed, an HTTP error will be thrown.
+
Create and print a list of all regular users archive privileges
  
== Examples ==
+
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 +
serverClient = mailstore.mgmt.ServerClient()
  
To get detailed information of all users you could use the following snippet:
+
privileges_map = dict()
 +
for user in serverClient.GetUsers()["result"]:
 +
    user_info = serverClient.GetUserInfo(user["userName"])["result"]
 +
    if "privilegesOnFolders" in user_info:
 +
        for privilege in user_info["privilegesOnFolders"]:
 +
            if privilege["folder"] not in privileges_map:
 +
                privileges_map[privilege["folder"]] = {user["userName"]: privilege["privileges"]}
 +
            else:
 +
                privileges_map[privilege["folder"]].update({user["userName"]: privilege["privileges"]})
  
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
+
for archive, user_dict in privileges_map.items():
serverClient = mailstore.server.Client(username="admin", password="admin", host="127.0.0.1", port=8463)
+
    print("Archive: {}".format(archive))
for user in serverClient.GetUserList():
+
    for username, priv in user_dict.items():
    print(serverClient.GetUserInfo(user["userName"]))
+
        print("\tUser: {}: {}".format(username, ", ".join(priv)))
 
</source>
 
</source>
  
A list with all assigned email address can be retrieved as follows:
+
Create and print a list of all admin users.
  
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
serverClient = mailstore.server.Client(username="admin", password="admin", host="127.0.0.1", port=8463)
+
serverClient = mailstore.mgmt.ServerClient()
emailaddresses = list()
+
admins = list()
for user in serverClient.GetUserList():
+
 
    emailaddresses += serverClient.GetUserInfo(user["userName"])['emailAddresses']
+
for user in serverClient.GetUsers()["result"]:
print(emailaddresses)
+
    if "admin" in serverClient.GetUserInfo(user["userName"])["result"]["privileges"]:
 +
        admins.append(user["userName"])
 +
 
 +
print("\n".join(admins))
 
</source>
 
</source>
  
 +
== Long Running Tasks ==
 +
The execution of certain API methods like ''VerifyStore'' may take several minutes or even hours until it finishes. There are different options available to deal with these long running tasks:
  
 +
# [[#Automatic Token Handling|Automatic Token Handling]]
 +
# [[#Automatic Token Handling with Callback Function|Automatic Token Handling with Callback Function]]
 +
# [[#Manual Token Handling|Manual Token Handling]]
  
= Long Running Calls =
+
Generally it is recommended to expect that every method call can become a long running task, as this depends on the ''waitTime'' value, the called method but also the overall load on the server. Thus it is not advisable to globally turn off automatic token handling when instantiating the API client.
  
The execution of certain API methods like ''VerifyStore'' can take several minutes or even hours until it finishes. These long running calls are executed asynchronously on the MailStore Server and you can decide whether to poll for status updates regularly and, in order to output the progress, process them in your own script or let the Python API library silently handle this for you and just wait for the call to finish.
+
If desired, automatic token handling can be enabled or disabled for each invoked method by adding ''autoHandleToken=True/False'' to the method's argument list.
  
== Invoking ==
+
Once a method has been invoked with manual token handling or a callback function, it can be cancelled by using the ''CancelAsync'' method as described in [[#Cancelling Long Running Tasks|Cancelling Long Running Tasks]].
When ''autoHandleToken'' is set to ''True'' (default), the library polls the status in the background automatically and will return the final result when the process has ended.  
 
  
 
=== Automatic Token Handling ===
 
=== Automatic Token Handling ===
 +
When ''autoHandleToken'' is set to ''True'' (default), the wrapper polls the status of long running tasks automatically in the background and will return the final result when the process has ended.
  
 +
==== Code ====
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
serverClient = mailstore.server.Client(autoHandleToken=True)
+
import mailstore
storeID = 1
+
 
print(serverClient.VerifyStore(storeID))
+
serverClient = mailstore.mgmt.ServerClient(autoHandleToken=True)
+
storeID = 1
{'status': 'succeeded', 'progressPercentage': 100, 'messages': [{'text': 'Verifying file group #2...', 'type': 'line'}, {'text': 'Creating a list of messages to be verified...', 'type': 'line'}, {'text': '234 messages are about to be verified.', 'type': 'line'}, {'text': 'Verifying...', 'type': 'line'}, {'text': 100 messages verified...', 'type': 'line'}, {'text': ' 200 messages verified...', 'type': 'line'}, {'text': '  234 messages verified.', 'type': 'line'}, {'text': 'Finished. No errors have been found.', 'type': 'line'}]}
+
print(serverClient.VerifyStore(storeID))
 +
</source>
 +
 
 +
==== Output ====
 +
<source lang="text" smart-tabs="true" toolbar="false" gutter="false">
 +
{'logOutput': None, 'statusText': None, 'error': None, 'percentProgress': 100, 'token': 'd242d822a59bd4db308eef8b85af7d2a', 'result': None, 'statusVersion': 71, 'statusCode': 'succeeded'}
 
</source>
 
</source>
  
=== Manual Token Handling ===
+
=== Automatic Token Handling with Callback Function ===
Set ''autoHandleToken'' to ''False'' to get the token and  handle it all by yourself. You are able to poll for status updates manually by passing the token to the ''GetStatus'' method. The main call has finished when the ''status'' has changed some else than ''running''. Please refer to the source code for available token handling helper methods.
+
If a caller wants to keep track of the progress of a long running task (i.e. to inform the user about the progress), although automatic token handling was enabled, he could pass a function as ''callback'' argument to the instance of the API client.
  
 +
==== Code ====
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
import time
+
import mailstore
  
serverClient = mailstore.server.Client(autoHandleToken=False) 
+
def showProgress(progress):
storeID = 2
+
  print(progress["logOutput"], end="", flush=True)
token = serverClient.VerifyStore(storeID)
 
print(token)
 
while True:
 
    time.sleep(1)
 
    status = serverClient.GetStatus(token)
 
    print(status)
 
    if status["status"] != "running":
 
        break
 
  
{'statusUrl': '/JSON/Status/243fc983-89c3-19ef-196a-dbe082894cc5', 'statusToken': '243fc983-89c3-19ef-196a-dbe082894cc5'}
+
serverClient = mailstore.mgmt.ServerClient(autoHandleToken=True, callback=showProgress)
{'progressPercentage': 0, 'messages': [{'type': 'line', 'text': 'Verifying file group #2...'}, {'type': 'line', 'text': 'Creating a list of messages to be verified...'}, {'type': 'line', 'text': '234 messages are about to be verified.'}, {'type': 'line', 'text': 'Verifying...'}, {'type': 'line', 'text': '  100 messages verified...'}], 'status': 'running'}
+
storeID = 3
{'progressPercentage': 100, 'messages': [{'type': 'line', 'text': 'Verifying file group #2...'}, {'type': 'line', 'text': 'Creating a list of messages to be verified...'}, {'type': 'line', 'text': '234 messages are about to be verified.'}, {'type': 'line', 'text': 'Verifying...'}, {'type': 'line', 'text': '  100 messages verified...'}, {'type': 'line', 'text': '  200 messages verified...'}, {'type': 'line', 'text': '  234 messages verified.'}, {'type': 'line', 'text': 'Finished. No errors have been found.'}], 'status': 'succeeded'}
+
print(serverClient.VerifyStore(storeID))
 
</source>
 
</source>
  
Pass the token to the ''HandleToken'' method will result in exactly the same behavior as if ''autoHandleToken=True'' would have been set.
+
==== Output ====
 
+
<source lang="text" smart-tabs="true" toolbar="false" gutter="false">
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
+
Verifying file group #3...
serverClient = mailstore.server.Client(autoHandleToken=False)
+
Creating a list of messages to be verified...
  storeID = 2
+
1249 messages are about to be verified.
  token = serverClient.VerifyStore(storeID)
+
Verifying...
  print(token)
+
  100 messages verified...
  print(serverClient.HandleToken(token))
+
  200 messages verified...
 +
  300 messages verified...
 +
  400 messages verified...
 +
  500 messages verified...
 +
  600 messages verified...
 +
  700 messages verified...
 +
  800 messages verified...
 +
  900 messages verified...
 +
  1000 messages verified...
 +
  1100 messages verified...
 +
  1200 messages verified...
 +
  1249 messages verified.
 +
Finished. No errors have been found.
 +
{'error': None, 'result': None, 'logOutput': ' 1000 messages verified...\r\n 1100 messages verified...\r\n 1200 messages verified...\r\n 1249 messages verified.\r\nFinished. No errors have been found.\r\n', 'token': 'c56f032d9db263133c1a413f79744b84', 'statusVersion': 71, 'statusText': None, 'percentProgress': 100, 'statusCode': 'succeeded'}
 
</source>
 
</source>
  
=== Selective Token Handling ===
+
=== Manual Token Handling ===
 +
If ''autoHandleToken'' is set to ''False'' the caller must handle long running tasks and the corresponding tokens all by itself. To poll for status updates, the ''GetStatus'' method must be called periodically passing the last returned result as parameter. ''GetStatus'' will extract the status token itself, poll for the latest update and return the received data to the caller again. The main call has finished when the ''statusCode'' changes to something different than ''running''. Calling ''GetStatus'' without passing a status token will result in an exception.
  
The Token handling behavior can be modified globally and locally. If the API client was instantiated with ''autoHandleToken=True'', each method can still be called with ''autoHandleToken=False'' and vice versa to disable or enable automatic token handling whenever necessary. Methods that do not return a token, do not accept the ''autoHandleToken'' parameter.
+
==== Code ====
 +
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 +
import mailstore
 +
import time
  
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
+
serverClient = mailstore.mgmt.ServerClient(autoHandleToken=False)
serverClient = mailstore.server.Client(autoHandleToken=False)
+
storeID = 3
storeID = 2
+
status = serverClient.VerifyStore(storeID)
token = serverClient.VerifyStore(storeID, autoHandleToken=True)
 
print(token)
 
  
{'status': 'succeeded', 'messages': [{'text': 'Verifying file group #2...', 'type': 'line'}, {'text': 'Creating a list of messages to be verified...', 'type': 'line'}, {'text': '234 messages are about to be verified.', 'type': 'line'}, {'text': 'Verifying...', 'type': 'line'}, {'text': '  100 messages verified...', 'type': 'line'}, {'text': '  200 messages verified...', 'type': 'line'}, {'text': '  234 messages verified.', 'type': 'line'}, {'text': 'Finished. No errors have been found.', 'type': 'line'}], 'progressPercentage': 100}
+
while True:
 +
    if status["statusCode"] != "running":
 +
        break
 +
    print(status["logOutput"], end="", flush=True)
 +
    status = serverClient.GetStatus(status)
 +
    time.sleep(1)
 
</source>
 
</source>
  
== Cancelling ==
+
==== Output ====
 +
<source lang="text" smart-tabs="true" toolbar="false" gutter="false">
 +
Verifying file group #3...
 +
Creating a list of messages to be verified...
 +
1249 messages are about to be verified.
 +
Verifying...
 +
  100 messages verified...
 +
  200 messages verified...
 +
  300 messages verified...
 +
  400 messages verified...
 +
  500 messages verified...
 +
  600 messages verified...
 +
  700 messages verified...
 +
  800 messages verified...
 +
  900 messages verified...
 +
  1000 messages verified...
 +
  1100 messages verified...
 +
  1200 messages verified...
 +
  1249 messages verified.
 +
Finished. No errors have been found.
 +
</source>
  
Currently long running calls cannot be cancelled. This is not a limitation of the Python wrapper, but of the MailStore Management API itself. This will be changed in the next major release of MailStore Server.
+
=== Cancelling Long Running Tasks ===
 +
Tasks invoked by using the callback method or manual token handling, can be canceled at any time by using the ''CancelAsync'' method. Please notice that the API does not acknowledge the success of the cancellation request. Instead the caller must continue to monitor the ''statusCode'' of the canceled method.
  
= Exception Handling =
+
==== Code ====
 +
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
 +
import mailstore
 +
import time
  
When there are no HTTP errors, the returned value is always a python dictionary.
+
serverClient = mailstore.mgmt.ServerClient(autoHandleToken=False)
 +
storeID = 3
 +
status = serverClient.VerifyStore(storeID)
  
In case an error occured, the call will raise an ''Exception''. All MailStore Exceptions are derived from ''mailstore.errors.MailStoreBaseError'' which itself is derived from ''Exception''.
+
while True:
 
+
    if status["statusCode"] != "running":
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
+
        break
try:
+
    print(status["logOutput"], end="")
    print(serverClient.GetUserInfo("not_such_user"))
+
    status = serverClient.GetStatus(status)
except mailstore.errors.MailStoreBaseError as e:
+
    time.sleep(1)
    print(e)
+
    serverClient.CancelAsync(status)
 
ERROR ('internal MailStore Server error',)
 
500 Internal Server Error https://127.0.0.1:8463/JSON/Invoke/GetUserInfo POST userName=not_such_user Command in MethodList: True
 
 
</source>
 
</source>
  
= Pretty Printing the Output =
+
==== Output ====
 
+
<source lang="text" smart-tabs="true" toolbar="false" gutter="false">
There is a helper function that formats the returned values in more readable manner.
+
Verifying file group #3...
 
+
Creating a list of messages to be verified...
<source lang="python" smart-tabs="true" toolbar="false" gutter="false">
+
1249 messages are about to be verified.
mailstore.pprint(serverClient.GetUserInfo("admin"))
+
Verifying...
 
+
  100 messages verified...
authentication integrated
+
  200 messages verified...
distinguishedName
+
  300 messages verified...
privileges
+
  400 messages verified...
    admin
+
  500 messages verified...
fullName Administrator
+
  600 messages verified...
userName admin
+
  700 messages verified...
 +
  800 messages verified...
 +
  900 messages verified...
 +
  1000 messages verified...
 +
  1100 messages verified...
 
</source>
 
</source>
  
= Methods Overview=
+
== Methods Overview ==
 +
All methods listed in the [[Administration API - Function Reference|function reference]] are implemented in the Python API library. Use
  
All the methods listed in [[MailStore_Server_Administration_API_Commands|the method overview]] are implemented in the Python API library.
+
  pydoc3 mailstore.mgmt.ServerClient
  
Additional (helper) methods available. Please see the source code for further details about these methods.
+
to access the build in documentation, which also includes an overview of all methods and their parameters.
  
 
[[de:Python API-Wrapper Tutorial]]
 
[[de:Python API-Wrapper Tutorial]]
 
[[en:Python API Wrapper Tutorial]]
 
[[en:Python API Wrapper Tutorial]]

Revision as of 16:31, 16 July 2018

Important notice: The Python API wrapper for the MailStore Server Administration API provided on this website, represents an example implementation of an API client. This wrapper should help system administrators and developers to quickly understand how the Administration API of MailStore Server works and how to use it in own scripts. Please understand that beyond this documentation no further support for the Python API wrapper is provided. Unless stated otherwise, the Pythin API wrapper as well as all related example scripts are released under the terms an conditions of the MIT License.

This document explains the installation and usage of the Python API wrapper for the MailStore Server Administration API. In order to prevent loss of data, service interruption or other problems, it is highly recommended to use a non-productive test environment for this tutorial as well as for script development in general. The 30-day-trial version of MailStore Server is perfectly suited for this.

Installation

The API wrapper library is tested against Python 3.2 and newer and is compatible with 32bit and 64bit versions of Python.

Python binaries for various operating systems can be downloaded from the Python download page or installed using the package manager of most Linux distributions.

Additionally create a folder "mailstore" in the Python's site-packages directory and extract the files from the Python API wrapper library into this folder.

In a UNIX like operating system the location of the site-packages directory can be found by executing the following command in a shell:

python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

In Windows the location of the site-packages directory can be found by opening a cmd, navigating in the Python3 installation directory and executing the following command:

python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

Instantiating the API Client

Before the API wrapper library can be used, it must first be imported with:

 import mailstore

Now the mailstore.mgmt.ServerClient class can be instantiated as follows:

serverClient = mailstore.mgmt.ServerClient(username="admin", password="admin", host="127.0.0.1", port=8463)

Default values can be omitted. The default admin credentials (username and password set to admin) are only usable when connecting from the MailStore Server computer itself to localhost. Find a listing of all default values in the following table:

Parameter Default Value Description
username admin Username used for connecting to the API.
password admin Password used for connecting to the API.
host 127.0.0.1 Hostname or IP address of the MailStore Server computer.
port 8463 TCP port on which MailStore Server is listening for API requests.
autoHandleToken True If set to True, the caller does not need to handle tokens of long running tasks, but instead has to wait for the result. When set to False and the statusCode is running, a status token is returned and must be handled appropriately by the caller of the method. Further details about token handling is described the corresponding section Automatic Token Handling of this document.
waitTime 1000 Specifies the number of milliseconds the API should wait for a final result. Otherwise the process is treated as running, in which case token handling as defined by the status of autoHandleToken becomes necessary.
callback None A callback function to which interim statuses of long running tasks should be passed. This allows keeping track of the tasks' progress even if autoHandleToken is enabled. This can be quite useful in order to notify users about the progress without having to deal with the token logic as a whole.
logLevel 2 Has to be in the range 0 to 4, where 0 (NONE) has the lowest verbosity and 4 (DEBUG) the highest. The loglevels are defined in the following order (low to high verbosity) NONE, ERROR, WARNING, INFO and DEBUG. Log entries will always be printed to stdout.
ignoreInvalidSSLCerts False Has to be set to True or False. Has to be enabled if untrusted certificates are used, otherwise an error occurs when using recent Python versions (>= 3.4.3).

Invoking API Method

After the API client has been successfully instantiated, API methods can easily be invoked. When the method call was successful, the statusCode is succeeded and the result is stored in the dictionary result as shown in the following example:

print(serverClient.GetServerInfo())
 
{'logOutput': None, 'statusText': None, 'error': None, 'percentProgress': None, 'token': None, 'result': {'machineName': 'WIN-2012-R2-X64', 'version': '9.0.3.9857'}, 'statusVersion': 2, 'statusCode': 'succeeded'}

If autoHandleToken was set to False and the statusCode returns running, manual token handling is required as described in the Automatic Token Handling section.

For any other statusCode value than succeeded and running the occurrence of an error has to be assumed, in which further information such as the error message and error details are available in the dictionary error as shown below:

userInfo = serverClient.GetUserInfo("john.doe")

if userInfo["statusCode"] == 'succeeded':
    print(userInfo["result"]["emailAddresses"])
else:
    print(userInfo["error"]["message"])

Examples

Create and print a list of all email addresses assigned to MailStore users.

serverClient = mailstore.mgmt.ServerClient()
addresses = list()
for user in serverClient.GetUsers()["result"]:
	addresses += serverClient.GetUserInfo(user["userName"])["result"]["emailAddresses"]
print("\n".join(sorted(set(addresses))))

Create and print a list of all regular users archive privileges

serverClient = mailstore.mgmt.ServerClient()

privileges_map = dict()
for user in serverClient.GetUsers()["result"]:
    user_info = serverClient.GetUserInfo(user["userName"])["result"]
    if "privilegesOnFolders" in user_info:
        for privilege in user_info["privilegesOnFolders"]:
            if privilege["folder"] not in privileges_map:
                privileges_map[privilege["folder"]] = {user["userName"]: privilege["privileges"]}
            else:
                privileges_map[privilege["folder"]].update({user["userName"]: privilege["privileges"]})

for archive, user_dict in privileges_map.items():
    print("Archive: {}".format(archive))
    for username, priv in user_dict.items():
        print("\tUser: {}: {}".format(username, ", ".join(priv)))

Create and print a list of all admin users.

serverClient = mailstore.mgmt.ServerClient()
admins = list()

for user in serverClient.GetUsers()["result"]:
    if "admin" in serverClient.GetUserInfo(user["userName"])["result"]["privileges"]:
        admins.append(user["userName"])

print("\n".join(admins))

Long Running Tasks

The execution of certain API methods like VerifyStore may take several minutes or even hours until it finishes. There are different options available to deal with these long running tasks:

  1. Automatic Token Handling
  2. Automatic Token Handling with Callback Function
  3. Manual Token Handling

Generally it is recommended to expect that every method call can become a long running task, as this depends on the waitTime value, the called method but also the overall load on the server. Thus it is not advisable to globally turn off automatic token handling when instantiating the API client.

If desired, automatic token handling can be enabled or disabled for each invoked method by adding autoHandleToken=True/False to the method's argument list.

Once a method has been invoked with manual token handling or a callback function, it can be cancelled by using the CancelAsync method as described in Cancelling Long Running Tasks.

Automatic Token Handling

When autoHandleToken is set to True (default), the wrapper polls the status of long running tasks automatically in the background and will return the final result when the process has ended.

Code

import mailstore

serverClient = mailstore.mgmt.ServerClient(autoHandleToken=True)
storeID = 1
print(serverClient.VerifyStore(storeID))

Output

{'logOutput': None, 'statusText': None, 'error': None, 'percentProgress': 100, 'token': 'd242d822a59bd4db308eef8b85af7d2a', 'result': None, 'statusVersion': 71, 'statusCode': 'succeeded'}

Automatic Token Handling with Callback Function

If a caller wants to keep track of the progress of a long running task (i.e. to inform the user about the progress), although automatic token handling was enabled, he could pass a function as callback argument to the instance of the API client.

Code

import mailstore

def showProgress(progress):
   print(progress["logOutput"], end="", flush=True)

serverClient = mailstore.mgmt.ServerClient(autoHandleToken=True, callback=showProgress)
storeID = 3
print(serverClient.VerifyStore(storeID))

Output

Verifying file group #3...
Creating a list of messages to be verified...
1249 messages are about to be verified.
Verifying...
  100 messages verified...
  200 messages verified...
  300 messages verified...
  400 messages verified...
  500 messages verified...
  600 messages verified...
  700 messages verified...
  800 messages verified...
  900 messages verified...
  1000 messages verified...
  1100 messages verified...
  1200 messages verified...
  1249 messages verified.
Finished. No errors have been found.
{'error': None, 'result': None, 'logOutput': '  1000 messages verified...\r\n  1100 messages verified...\r\n  1200 messages verified...\r\n  1249 messages verified.\r\nFinished. No errors have been found.\r\n', 'token': 'c56f032d9db263133c1a413f79744b84', 'statusVersion': 71, 'statusText': None, 'percentProgress': 100, 'statusCode': 'succeeded'}

Manual Token Handling

If autoHandleToken is set to False the caller must handle long running tasks and the corresponding tokens all by itself. To poll for status updates, the GetStatus method must be called periodically passing the last returned result as parameter. GetStatus will extract the status token itself, poll for the latest update and return the received data to the caller again. The main call has finished when the statusCode changes to something different than running. Calling GetStatus without passing a status token will result in an exception.

Code

import mailstore
import time

serverClient = mailstore.mgmt.ServerClient(autoHandleToken=False)
storeID = 3
status = serverClient.VerifyStore(storeID)

while True:
    if status["statusCode"] != "running":
        break
    print(status["logOutput"], end="", flush=True)
    status = serverClient.GetStatus(status)
    time.sleep(1)

Output

Verifying file group #3...
Creating a list of messages to be verified...
1249 messages are about to be verified.
Verifying...
  100 messages verified...
  200 messages verified...
  300 messages verified...
  400 messages verified...
  500 messages verified...
  600 messages verified...
  700 messages verified...
  800 messages verified...
  900 messages verified...
  1000 messages verified...
  1100 messages verified...
  1200 messages verified...
  1249 messages verified.
Finished. No errors have been found.

Cancelling Long Running Tasks

Tasks invoked by using the callback method or manual token handling, can be canceled at any time by using the CancelAsync method. Please notice that the API does not acknowledge the success of the cancellation request. Instead the caller must continue to monitor the statusCode of the canceled method.

Code

import mailstore
import time

serverClient = mailstore.mgmt.ServerClient(autoHandleToken=False)
storeID = 3
status = serverClient.VerifyStore(storeID)

while True:
    if status["statusCode"] != "running":
        break
    print(status["logOutput"], end="")
    status = serverClient.GetStatus(status)
    time.sleep(1)
    serverClient.CancelAsync(status)

Output

Verifying file group #3...
Creating a list of messages to be verified...
1249 messages are about to be verified.
Verifying...
  100 messages verified...
  200 messages verified...
  300 messages verified...
  400 messages verified...
  500 messages verified...
  600 messages verified...
  700 messages verified...
  800 messages verified...
  900 messages verified...
  1000 messages verified...
  1100 messages verified...

Methods Overview

All methods listed in the function reference are implemented in the Python API library. Use

 pydoc3 mailstore.mgmt.ServerClient

to access the build in documentation, which also includes an overview of all methods and their parameters.