1PYTHON-OVH(1) Python-OVH PYTHON-OVH(1)
2
3
4
6 python-ovh - Python-OVH Documentation
7
8 Thin wrapper around OVH's APIs. Handles all the hard work including
9 credential creation and requests signing.
10
11 # -*- encoding: utf-8 -*-
12
13 import ovh
14
15 # Instantiate. Visit https://api.ovh.com/createToken/index.cgi?GET=/me
16 # to get your credentials
17 client = ovh.Client(
18 endpoint='ovh-eu',
19 application_key='<application key>',
20 application_secret='<application secret>',
21 consumer_key='<consumer key>',
22 )
23
24 # Print nice welcome message
25 print("Welcome", client.get('/me')['firstname'])
26
27 The easiest way to get the latest stable release is to grab it from
28 pypi using pip.
29
30 pip install ovh
31
32 Alternatively, you may get latest development version directly from
33 Git.
34
35 pip install -e git+https://github.com/ovh/python-ovh.git#egg=ovh
36
38 Constructor
39 __init__
40 High level helpers
41 request_consumerkey
42 Helpers to generate a consumer key. See new_consumer_key_request below
43 for a full working example or ConsumerKeyRequest for detailed implemen‐
44 tation.
45
46 The basic idea of ConsumerKeyRequest is to generate appropriate autho‐
47 rization requests from human readable function calls. In short: use it!
48
49 get/post/put/delete
50 Shortcuts around Client.call(). This is the recommended way to use the
51 wrapper.
52
53 For example, requesting the list of all bills would look like:
54
55 bills = client.get('/me/bills')
56
57 In a similar fashion, enabling network burst on a specific server would
58 look like:
59
60 client.put('/dedicated/server/%s/burst' % server_name, status='active')
61
62 param str target
63 Rest Method as shown in API's console.
64
65 param boolean need_auth
66 When False, bypass the signature process. This is interesting
67 when calling authentication related method. Defaults to True
68
69 param dict kwargs
70 (Client.post() and Client.put() only) all extra keyword argu‐
71 ments are passed as data dict to call. This is a syntaxic sugar
72 to call API entrypoints using a regular method syntax.
73
74 Low level API
75 call
76 time_delta
78 Methods
79 __init__
80 get
81 Globals
83 Constructor
84 __init__
85 Helpers
86 Generate rules
87 Trigger request
90 1. Create an application
91 To interact with the APIs, the SDK needs to identify itself using an
92 application_key and an application_secret. To get them, you need to
93 register your application. Depending the API you plan yo use, visit:
94
95 • OVH Europe
96
97 • OVH North-America
98
99 Once created, you will obtain an application key (AK) and an applica‐
100 tion secret (AS).
101
102 2. Configure your application
103 The easiest and safest way to use your application's credentials is
104 create an ovh.conf configuration file in application's working direc‐
105 tory. Here is how it looks like:
106
107 [default]
108 ; general configuration: default endpoint
109 endpoint=ovh-eu
110
111 [ovh-eu]
112 ; configuration specific to 'ovh-eu' endpoint
113 application_key=my_app_key
114 application_secret=my_application_secret
115 ; uncomment following line when writing a script application
116 ; with a single consumer key.
117 ;consumer_key=my_consumer_key
118
119 Depending on the API you want to use, you may set the endpoint to:
120
121 • ovh-eu for OVH Europe API
122
123 • ovh-ca for OVH North-America API
124
125 See Configuration for more informations on available configuration
126 mechanisms.
127
128 NOTE:
129 When using a versioning system, make sure to add ovh.conf to ignored
130 files. It contains confidential/security-sensitive information!
131
132 3. Authorize your application to access a customer account
133 To allow your application to access a customer account using the API on
134 your behalf, you need a consumer key (CK).
135
136 # -*- encoding: utf-8 -*-
137
138 try:
139 input = raw_input
140 except NameError:
141 pass
142
143 import ovh
144
145 # create a client using configuration
146 client = ovh.Client()
147
148 # Request RO, /me API access
149 access_rules = [
150 {'method': 'GET', 'path': '/me'},
151 ]
152
153 # Request token
154 validation = client.request_consumerkey(access_rules)
155
156 print("Please visit %s to authenticate" % validation['validationUrl'])
157 input("and press Enter to continue...")
158
159 # Print nice welcome message
160 print("Welcome", client.get('/me')['firstname'])
161 print("Btw, your 'consumerKey' is '%s'" % validation['consumerKey'])
162
163 Returned consumerKey should then be kept to avoid re-authenticating
164 your end-user on each use.
165
166 NOTE:
167 To request full and unlimited access to the API, you may use wild‐
168 cards:
169
170 access_rules = [
171 {'method': 'GET', 'path': '/*'},
172 {'method': 'POST', 'path': '/*'},
173 {'method': 'PUT', 'path': '/*'},
174 {'method': 'DELETE', 'path': '/*'}
175 ]
176
178 e-mail redirections may be freely configured on domains and DNS zones
179 hosted by OVH to an arbitrary destination e-mail using API call POST
180 /email/domain/{domain}/redirection.
181
182 For this call, the api specifies that the source address shall be given
183 under the from keyword. Which is a problem as this is also a reserved
184 Python keyword. In this case, simply prefix it with a '_', the wrapper
185 will automatically detect it as being a prefixed reserved keyword and
186 will substitute it. Such aliasing is only supported with reserved key‐
187 words.
188
189 # -*- encoding: utf-8 -*-
190
191 import ovh
192
193 DOMAIN = "example.com"
194 SOURCE = "sales@example.com"
195 DESTINATION = "contact@example.com"
196
197 # create a client
198 client = ovh.Client()
199
200 # Create a new alias
201 client.post('/email/domain/%s/redirection' % DOMAIN,
202 _from=SOURCE,
203 to=DESTINATION
204 localCopy=False
205 )
206 print("Installed new mail redirection from %s to %s" % (SOURCE, DESTINATION))
207
209 Let's say you want to integrate OVH bills into your own billing system,
210 you could just script around the /me/bills endpoints and even get the
211 details of each bill lines using /me/bill/{billId}/details/{billDe‐
212 tailId}.
213
214 This example assumes an existing Configuration with valid applica‐
215 tion_key, application_secret and consumer_key.
216
217 # -*- encoding: utf-8 -*-
218
219 import ovh
220
221 # create a client without a consumerKey
222 client = ovh.Client()
223
224 # Grab bill list
225 bills = client.get('/me/bill')
226 for bill in bills:
227 details = client.get('/me/bill/%s' % bill)
228 print("%12s (%s): %10s --> %s" % (
229 bill,
230 details['date'],
231 details['priceWithTax']['text'],
232 details['pdfUrl'],
233 ))
234
236 'Network burst' is a free service but is opt-in. What if you have, say,
237 10 servers in SBG-1 datacenter? You certainly don't want to activate it
238 manually for each servers. You could take advantage of a code like
239 this.
240
241 This example assumes an existing Configuration with valid applica‐
242 tion_key, application_secret and consumer_key.
243
244 # -*- encoding: utf-8 -*-
245
246 import ovh
247
248 # create a client
249 client = ovh.Client()
250
251 # get list of all server names
252 servers = client.get('/dedicated/server/')
253
254 # find all servers in SBG-1 datacenter
255 for server in servers:
256 details = client.get('/dedicated/server/%s' % server)
257 if details['datacenter'] == 'sbg1':
258 # enable burst on server
259 client.put('/dedicated/server/%s/burst' % server, status='active')
260 print("Enabled burst for %s server located in SBG-1" % server)
261
263 Thanks to the application key / consumer key mechanism, it is possible
264 to finely track applications having access to your data and revoke this
265 access. This examples lists validated applications. It could easily be
266 adapted to manage revocation too.
267
268 This example assumes an existing Configuration with valid applica‐
269 tion_key, application_secret and consumer_key.
270
271 # -*- encoding: utf-8 -*-
272
273 import ovh
274 from tabulate import tabulate
275
276 # create a client
277 client = ovh.Client()
278
279 credentials = client.get('/me/api/credential', status='validated')
280
281 # pretty print credentials status
282 table = []
283 for credential_id in credentials:
284 credential_method = '/me/api/credential/'+str(credential_id)
285 credential = client.get(credential_method)
286 application = client.get(credential_method+'/application')
287
288 table.append([
289 credential_id,
290 '[%s] %s' % (application['status'], application['name']),
291 application['description'],
292 credential['creation'],
293 credential['expiration'],
294 credential['lastUse'],
295 ])
296 print(tabulate(table, headers=['ID', 'App Name', 'Description',
297 'Token Creation', 'Token Expiration', 'Token Last Use']))
298
299 Before running this example, make sure you have the tabulate library
300 installed. It's a pretty cool library to pretty print tabular data in a
301 clean and easy way.
302
303 >>> pip install tabulate
304
305 The straightforward way to use OVH's API keys is to embed them directly
306 in the application code. While this is very convenient, it lacks of el‐
307 egance and flexibility.
308
309 Alternatively it is suggested to use configuration files or environment
310 variables so that the same code may run seamlessly in multiple environ‐
311 ments. Production and development for instance.
312
313 This wrapper will first look for direct instantiation parameters then
314 OVH_ENDPOINT, OVH_APPLICATION_KEY, OVH_APPLICATION_SECRET and OVH_CON‐
315 SUMER_KEY environment variables. If either of these parameter is not
316 provided, it will look for a configuration file of the form:
317
318 [default]
319 ; general configuration: default endpoint
320 endpoint=ovh-eu
321
322 [ovh-eu]
323 ; configuration specific to 'ovh-eu' endpoint
324 application_key=my_app_key
325 application_secret=my_application_secret
326 consumer_key=my_consumer_key
327
328 The client will successively attempt to locate this configuration file
329 in
330
331 1. Current working directory: ./ovh.conf
332
333 2. Current user's home directory ~/.ovh.conf
334
335 3. System wide configuration /etc/ovh.conf
336
337 This lookup mechanism makes it easy to overload credentials for a spe‐
338 cific project or user.
339
340 You can call all the methods of the API with the necessary arguments.
341
342 If an API needs an argument colliding with a Python reserved keyword,
343 it can be prefixed with an underscore. For example, from argument of
344 POST /email/domain/{domain}/redirection may be replaced by _from.
345
346 With characters invalid in python argument name like a dot, you can:
347
348 # -*- encoding: utf-8 -*-
349
350 import ovh
351
352 params = {}
353 params['date.from'] = '2014-01-01'
354 params['date.to'] = '2015-01-01'
355
356 # create a client
357 client = ovh.Client()
358
359 # pass parameters using **
360 client.post('/me/bills', **params)
361
363 If the user has not authenticated yet (ie, there is no valid Consumer
364 Key), you may force python-ovh to issue the call by passing
365 _need_auth=True to the high level get(), post(), put() and delete()
366 helpers or need_auth=True to the low level method Client.call() and
367 Client.raw_call().
368
369 This is needed when calling POST /auth/credential and GET /auth/time
370 which are used internally for authentication and can optionally be done
371 for most of the /order calls.
372
374 The high level get(), post(), put() and delete() helpers as well as the
375 lower level call() will returned a parsed json response or raise in
376 case of error.
377
378 In some rare scenario, advanced setups, you may need to perform cus‐
379 tomer processing on the raw request response. It may be accessed via
380 raw_call(). This is the lowest level call in python-ovh. See the
381 source for more information.
382
383 This wrapper uses standard Python tools, so you should feel at home
384 with it. Here is a quick outline of what it may look like. A good
385 practice is to run this from a virtualenv.
386
388 git clone https://github.com/ovh/python-ovh.git
389 cd python-ovh
390 python setup.py develop
391
392 You've developed a new cool feature ? Fixed an annoying bug ? We'd be
393 happy to hear from you !
394
396 Simply run nosetests. It will automatically load its configuration from
397 setup.cfg and output full coverage status. Since we all love quality,
398 please note that we do not accept contributions with test coverage un‐
399 der 100%.
400
401 pip install -e .[dev]
402 nosetests # 100% coverage is a hard minimum
403
405 Documentation is managed using the excellent Sphinx system. For exam‐
406 ple, to build HTML documentation:
407
408 cd python-ovh/docs
409 make html
410
412 • Documentation: https://eu.api.ovh.com/
413
414 • Community support: api-subscribe@ml.ovh.net
415
416 • Console: https://eu.api.ovh.com/console
417
418 • Create application credentials: https://eu.api.ovh.com/createApp/
419
421 • Documentation: https://ca.api.ovh.com/
422
423 • Community support: api-subscribe@ml.ovh.net
424
425 • Console: https://ca.api.ovh.com/console
426
427 • Create application credentials: https://ca.api.ovh.com/createApp/
428
429 • Contribute: https://github.com/ovh/python-ovh
430
431 • Report bugs: https://github.com/ovh/python-ovh/issues
432
433 • Download: http://pypi.python.org/pypi/ovh
434
436 Jean-Tiare Le Bigot
437
439 2013-2022, OVH SAS
440
441
442
443
4440.3 Aug 12, 2022 PYTHON-OVH(1)