|
4 | 4 | zerorpc is a flexible RPC implementation based on zeromq and messagepack.
|
5 | 5 | Service APIs exposed with zerorpc are called "zeroservices".
|
6 | 6 |
|
7 |
| -zerorpc comes with a convenient script, "zerorpc", allowing to: |
| 7 | +zerorpc can be used programmatically or from the command-line. It comes |
| 8 | +with a convenient script, "zerorpc", allowing to: |
8 | 9 |
|
9 | 10 | * expose Python modules without modifying a single line of code,
|
10 | 11 | * call those modules remotely through the command line.
|
@@ -139,3 +140,54 @@ it won't affect the worker (that's the magic of zeromq).
|
139 | 140 | addresses, and will dispatch requests to available workers. If you want
|
140 | 141 | to connect to multiple remote servers for high availability purposes,
|
141 | 142 | you insert something like HAProxy in the middle.
|
| 143 | + |
| 144 | + |
| 145 | +Exposing a zeroservice programmatically |
| 146 | +--------------------------------------- |
| 147 | + |
| 148 | +Of course, the command-line is simply a convenience wrapper for the zerorpc |
| 149 | +python API. Below are a few examples. |
| 150 | + |
| 151 | +Here's how to expose an object of your choice as a zeroservice:: |
| 152 | + |
| 153 | + class Cooler: |
| 154 | + """ Various convenience methods to make things cooler. """ |
| 155 | + |
| 156 | + def add_man(self, sentence): |
| 157 | + """ End a sentence with ", man!" to make it sound cooler, and |
| 158 | + return the result. """ |
| 159 | + return sentence + ", man!" |
| 160 | + |
| 161 | + def add_42(self, n): |
| 162 | + """ Add 42 to an integer argument to make it cooler, and return the |
| 163 | + result. """ |
| 164 | + return n + 42 |
| 165 | + |
| 166 | + def boat(self, sentence): |
| 167 | + """ Replace a sentence with "I'm on a boat!", and return that, |
| 168 | + because it's cooler. """ |
| 169 | + return "I'm on a boat!" |
| 170 | + |
| 171 | + import zerorpc |
| 172 | + |
| 173 | + s = zerorpc.Server(Cooler()) |
| 174 | + s.bind("tcp://0.0.0.0:4242") |
| 175 | + s.run() |
| 176 | + |
| 177 | +Let's save this code to *cooler.py* and run it:: |
| 178 | + |
| 179 | + $ python cooler.py |
| 180 | + |
| 181 | +Now, in another terminal, let's try connecting to our awesome zeroservice:: |
| 182 | + |
| 183 | + $ zerorpc -j tcp://:4242 add_42 1 |
| 184 | + 43 |
| 185 | + $ zerorpc tcp://:4242 add_man 'I own a mint-condition Wolkswagen Golf' |
| 186 | + "I own a mint-condition Wolkswagen Gold, man!" |
| 187 | + $ zerorpc tcp://:4242 boat 'I own a mint-condition Wolkswagen Gold, man!' |
| 188 | + "I'm on a boat!" |
| 189 | + |
| 190 | + |
| 191 | +Congratulations! You have just made the World a little cooler with your first |
| 192 | +zeroservice, man! |
| 193 | + |
0 commit comments