]> git.evergreen-ils.org Git - working/Evergreen.git/blob - docs/development/python_client.py
Add "Intro to OpenSRF" to development section
[working/Evergreen.git] / docs / development / python_client.py
1 #!/usr/bin/env python
2 """OpenSRF client example in Python"""
3 import osrf.system
4 import osrf.ses
5
6 def osrf_substring(session, text, sub):
7     """substring: Accepts a string and a number as input, returns a string"""
8     request = session.request('opensrf.simple-text.substring', text, sub)
9
10     # Retrieve the response from the method
11     # The timeout parameter is optional
12     response = request.recv(timeout=2)
13
14     request.cleanup()
15     # The results are accessible via content()
16     return response.content()
17
18 def osrf_split(session, text, delim):
19     """split: Accepts two strings as input, returns an array of strings"""
20     request = session.request('opensrf.simple-text.split', text, delim)
21     response = request.recv()
22     request.cleanup()
23     return response.content()
24
25 def osrf_statistics(session, strings):
26     """statistics: Accepts an array of strings as input, returns a hash"""
27     request = session.request('opensrf.simple-text.statistics', strings)
28     response = request.recv()
29     request.cleanup()
30     return response.content()
31
32
33 if __name__ == "__main__":
34     file = '/openils/conf/opensrf_core.xml'
35
36     # Pull connection settings from <config><opensrf> section of opensrf_core.xml
37     osrf.system.System.connect(config_file=file, config_context='config.opensrf')
38
39     # Set up a connection to the opensrf.settings service
40     session = osrf.ses.ClientSession('opensrf.simple-text')
41
42     result = osrf_substring(session, "foobar", 3)
43     print(result)
44     print
45
46     result = osrf_split(session, "This is a test", " ")
47     print("Received %d elements: [" % len(result)),
48     print(', '.join(result)), ']'
49
50     many_strings = (
51         "First I think I'll have breakfast",
52         "Then I think that lunch would be nice",
53         "And then seventy desserts to finish off the day"
54     )
55     result = osrf_statistics(session, many_strings)
56     print("Length: %d" % result["length"])
57     print("Word count: %d" % result["word_count"])
58
59     # Cleanup connection resources
60     session.cleanup()