Package: ovh
Lightweight wrapper around OVHcloud’s APIs. Handles all the hard work including
credential creation and requests signing.importovh# Instantiate. Visit https://api.ovh.com/createToken/?GET=/me# to get your credentialsclient=ovh.Client(endpoint='ovh-eu',application_key='<application key>',application_secret='<application secret>',consumer_key='<consumer key>',)# Print nice welcome messageprint("Welcome",client.get('/me')['firstname'])InstallationThe python wrapper works with Python 3.6+.The easiest way to get the latest stable release is to grab it frompypiusingpip.pipinstallovhAlternatively, you may get latest development version directly from Git.pipinstall-egit+https://github.com/ovh/python-ovh.git#egg=ovhPeople looking for Python 2 compatibility should use 0.6.x version.Example UsageUse the API on behalf of a user1. Create an applicationTo interact with the APIs, the SDK needs to identify itself using anapplication_keyand anapplication_secret. To get them, you need
to register your application. Depending the API you plan to use, visit:OVH EuropeOVH USOVH North-AmericaSo you Start EuropeSo you Start North AmericaKimsufi EuropeKimsufi North AmericaOnce created, you will obtain anapplication key (AK)and anapplication
secret (AS).2. Configure your applicationThe easiest and safest way to use your application’s credentials is to create anovh.confconfiguration file in application’s working directory. Here is how
it looks like:[default]; general configuration: default endpointendpoint=ovh-eu[ovh-eu]; configuration specific to 'ovh-eu' endpointapplication_key=my_app_keyapplication_secret=my_application_secret; uncomment following line when writing a script application; with a single consumer key.;consumer_key=my_consumer_keyDepending on the API you want to use, you may set theendpointto:ovh-eufor OVH Europe APIovh-usfor OVH US APIovh-cafor OVH North-America APIsoyoustart-eufor So you Start Europe APIsoyoustart-cafor So you Start North America APIkimsufi-eufor Kimsufi Europe APIkimsufi-cafor Kimsufi North America APISeeConfigurationfor more information on available configuration mechanisms.NoteWhen using a versioning system, make sure to addovh.confto ignored
files. It contains confidential/security-sensitive information!3. Authorize your application to access a customer accountTo allow your application to access a customer account using the API on your
behalf, you need aconsumer key (CK).Here is a sample code you can use to allow your application to access a
customer’s information:importovh# create a client using configurationclient=ovh.Client()# Request RO, /me API accessck=client.new_consumer_key_request()ck.add_rules(ovh.API_READ_ONLY,"/me")# Request tokenvalidation=ck.request()print("Please visit%sto authenticate"%validation['validationUrl'])input("and press Enter to continue...")# Print nice welcome messageprint("Welcome",client.get('/me')['firstname'])print("Btw, your 'consumerKey' is '%s'"%validation['consumerKey'])ReturnedconsumerKeyshould then be kept to avoid re-authenticating your
end-user on each use.NoteTo request full and unlimited access to the API, you may useadd_recursive_rules:# Allow all GET, POST, PUT, DELETE on /* (full API)ck.add_recursive_rules(ovh.API_READ_WRITE,'/')Install a new mail redirectione-mail redirections may be freely configured on domains and DNS zones hosted by
OVH to an arbitrary destination e-mail using API callPOST/email/domain/{domain}/redirection.For this call, the api specifies that the source address shall be given under thefromkeyword. Which is a problem as this is also a reserved Python keyword.
In this case, simply prefix it with a ‘_’, the wrapper will automatically detect
it as being a prefixed reserved keyword and will substitute it. Such aliasing
is only supported with reserved keywords.importovhDOMAIN="example.com"SOURCE="sales@example.com"DESTINATION="contact@example.com"# create a clientclient=ovh.Client()# Create a new aliasclient.post('/email/domain/%s/redirection'%DOMAIN,_from=SOURCE,to=DESTINATION,localCopy=False)print("Installed new mail redirection from%sto%s"%(SOURCE,DESTINATION))Grab bill listLet’s say you want to integrate OVH bills into your own billing system, you
could just script around the/me/billsendpoints and even get the details
of each bill lines using/me/bill/{billId}/details/{billDetailId}.This example assumes an existingConfigurationwith validapplication_key,application_secretandconsumer_key.importovh# create a clientclient=ovh.Client()# Grab bill listbills=client.get('/me/bill')forbillinbills:details=client.get('/me/bill/%s'%bill)print("%12s(%s):%10s-->%s"%(bill,details['date'],details['priceWithTax']['text'],details['pdfUrl'],))Enable network burst in SBG1‘Network burst’ is a free service but is opt-in. What if you have, say, 10
servers inSBG-1datacenter? You certainly don’t want to activate it
manually for each servers. You could take advantage of a code like this.This example assumes an existingConfigurationwith validapplication_key,application_secretandconsumer_key.importovh# create a clientclient=ovh.Client()# get list of all server namesservers=client.get('/dedicated/server/')# find all servers in SBG-1 datacenterforserverinservers:details=client.get('/dedicated/server/%s'%server)ifdetails['datacenter']=='sbg1':# enable burst on serverclient.put('/dedicated/server/%s/burst'%server,status='active')print("Enabled burst for%sserver located in SBG-1"%server)List application authorized to access your accountThanks to the application key / consumer key mechanism, it is possible to
finely track applications having access to your data and revoke this access.
This examples lists validated applications. It could easily be adapted to
manage revocation too.This example assumes an existingConfigurationwith validapplication_key,application_secretandconsumer_key.importovhfromtabulateimporttabulate# create a clientclient=ovh.Client()credentials=client.get('/me/api/credential',status='validated')# pretty print credentials statustable=[]forcredential_idincredentials:credential_method='/me/api/credential/'+str(credential_id)credential=client.get(credential_method)application=client.get(credential_method+'/application')table.append([credential_id,'[%s]%s'%(application['status'],application['name']),application['description'],credential['creation'],credential['expiration'],credential['lastUse'],])print(tabulate(table,headers=['ID','App Name','Description','Token Creation','Token Expiration','Token Last Use']))Before running this example, make sure you have thetabulatelibrary installed. It’s a
pretty cool library to pretty print tabular data in a clean and easy way.>>> pip install tabulateOpen a KVM (remote screen) on a dedicated serverRecent dedicated servers come with an IPMI interface. A lightweight control board embedded
on the server. Using IPMI, it is possible to get a remote screen on a server. This is
particularly useful to tweak the BIOS or troubleshoot boot issues.Hopefully, this can easily be automated using a simple script. It assumes Java Web Start is
fully installed on the machine and a consumer key allowed on the server exists.importovhimportsysimporttimeimporttempfileimportsubprocess# check argumentsiflen(sys.argv)!=3:print("Usage:%sSERVER_NAME ALLOWED_IP_V4"%sys.argv[0])sys.exit(1)server_name=sys.argv[1]allowed_ip=sys.argv[2]# create a clientclient=ovh.Client()# create a KVMclient.post('/dedicated/server/'+server_name+'/features/ipmi/access',ipToAllow=allowed_ip,ttl=15,type="kvmipJnlp")# open the KVM, when readywhileTrue:try:# use a named temfile and feed it to java web startwithtempfile.NamedTemporaryFile()asf:f.write(client.get('/dedicated/server/'+server_name+'/features/ipmi/access?type=kvmipJnlp')['value'])f.flush()subprocess.call(["javaws",f.name])breakexcept:time.sleep(1)Running is only a simple command line:# Basicpythonopen_kvm.pyns1234567.ip-42-42-42.eu$(curlifconfig.ovh)# Use a specific consumer keyOVH_CONSUMER_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApythonopen_kvm.pyns1234567.ip-42-42-42.eu$(curl-sifconfig.ovh)ConfigurationYou have 3 ways to provide configuration to the client:write it directly in the application coderead environment variables or predefined configuration filesread it from a custom configuration fileEmbed the configuration in the codeThe straightforward way to use OVH’s API keys is to embed them directly in the
application code. While this is very convenient, it lacks of elegance and
flexibility.Example usage:client=ovh.Client(endpoint='ovh-eu',application_key='<application key>',application_secret='<application secret>',consumer_key='<consumer key>',)Environment vars and predefined configuration filesAlternatively it is suggested to use configuration files or environment
variables so that the same code may run seamlessly in multiple environments.
Production and development for instance.This wrapper will first look for direct instantiation parameters thenOVH_ENDPOINT,OVH_APPLICATION_KEY,OVH_APPLICATION_SECRETandOVH_CONSUMER_KEYenvironment variables. If either of these parameter is not
provided, it will look for a configuration file of the form:[default]; general configuration: default endpointendpoint=ovh-eu[ovh-eu]; configuration specific to 'ovh-eu' endpointapplication_key=my_app_keyapplication_secret=my_application_secretconsumer_key=my_consumer_keyThe client will successively attempt to locate this configuration file inCurrent working directory:./ovh.confCurrent user’s home directory~/.ovh.confSystem wide configuration/etc/ovh.confThis lookup mechanism makes it easy to overload credentials for a specific
project or user.Example usage:client=ovh.Client()Use v1 and v2 API versionsWhen using OVHcloud APIs (not So you Start or Kimsufi ones), you are given the
opportunity to aim for two API versions. For the European API, for example:the v1 is reachable throughhttps://eu.api.ovh.com/v1the v2 is reachable throughhttps://eu.api.ovh.com/v2the legacy URL ishttps://eu.api.ovh.com/1.0Callingclient.get, you can target the API version you want:client=ovh.Client(endpoint="ovh-eu")# Call to https://eu.api.ovh.com/v1/xdsl/xdsl-yourserviceclient.get("/v1/xdsl/xdsl-yourservice")# Call to https://eu.api.ovh.com/v2/xdsl/xdsl-yourserviceclient.get("/v2/xdsl/xdsl-yourservice")# Legacy call to https://eu.api.ovh.com/1.0/xdsl/xdsl-yourserviceclient.get("/xdsl/xdsl-yourservice")Custom configuration fileYou can also specify a custom configuration file. With this method, you won’t be able to inherit values from environment.Example usage:client=ovh.Client(config_file='/my/config.conf')Passing parametersYou can call all the methods of the API with the necessary arguments.If an API needs an argument colliding with a Python reserved keyword, it
can be prefixed with an underscore. For example,fromargument ofPOST/email/domain/{domain}/redirectionmay be replaced by_from.With characters invalid in python argument name like a dot, you can:importovhparams={}params['date.from']='2014-01-01'params['date.to']='2015-01-01'# create a clientclient=ovh.Client()# pass parameters using **client.post('/me/bills',**params)Advanced usageUn-authenticated callsIf the user has not authenticated yet (ie, there is no valid Consumer Key), you
may forcepython-ovhto issue the call by passing_need_auth=Trueto
the high levelget(),post(),put()anddelete()helpers orneed_auth=Trueto the low level methodClient.call()andClient.raw_call().This is needed when callingPOST /auth/credentialandGET /auth/timewhich are used internally for authentication and can optionally be done for
most of the/ordercalls.Access the raw requests response objectsThe high levelget(),post(),put()anddelete()helpers as well
as the lower levelcall()will returned a parsed json response or raise in
case of error.In some rare scenario, advanced setups, you may need to perform customer
processing on the raw request response. It may be accessed viaraw_call().
This is the lowest level call inpython-ovh. See the source for more
information.HackingThis wrapper uses standard Python tools, so you should feel at home with it.
Here is a quick outline of what it may look like. A good practice is to run
this from avirtualenv.Get the sourcesgitclonehttps://github.com/ovh/python-ovh.gitcdpython-ovhpythonsetup.pydevelopYou’ve developed a new cool feature? Fixed an annoying bug? We’d be happy
to hear from you!Run the testsSimply runpytest. It will automatically load its configuration fromsetup.cfgand output full coverage status. Since we all love quality, please
note that we do not accept contributions with test coverage under 100%.pipinstall-e.[dev]pytestBuild the documentationDocumentation is managed using the excellentSphinxsystem. For example, to
build HTML documentation:cdpython-ovh/docsmakehtmlSupported APIsOVH EuropeDocumentation:https://eu.api.ovh.com/Community support:api-subscribe@ml.ovh.netConsole:https://eu.api.ovh.com/consoleCreate application credentials:https://eu.api.ovh.com/createApp/Create script credentials(all keys at once):https://eu.api.ovh.com/createToken/OVH USDocumentation:https://api.us.ovhcloud.com/Console:https://api.us.ovhcloud.com/console/Create application credentials:https://api.us.ovhcloud.com/createApp/Create script credentials(all keys at once):https://api.us.ovhcloud.com/createToken/OVH North AmericaDocumentation:https://ca.api.ovh.com/Community support:api-subscribe@ml.ovh.netConsole:https://ca.api.ovh.com/consoleCreate application credentials:https://ca.api.ovh.com/createApp/Create script credentials(all keys at once):https://ca.api.ovh.com/createToken/So you Start EuropeDocumentation:https://eu.api.soyoustart.com/Community support:api-subscribe@ml.ovh.netConsole:https://eu.api.soyoustart.com/console/Create application credentials:https://eu.api.soyoustart.com/createApp/Create script credentials(all keys at once):https://eu.api.soyoustart.com/createToken/So you Start North AmericaDocumentation:https://ca.api.soyoustart.com/Community support:api-subscribe@ml.ovh.netConsole:https://ca.api.soyoustart.com/console/Create application credentials:https://ca.api.soyoustart.com/createApp/Create script credentials(all keys at once):https://ca.api.soyoustart.com/createToken/Kimsufi EuropeDocumentation:https://eu.api.kimsufi.com/Community support:api-subscribe@ml.ovh.netConsole:https://eu.api.kimsufi.com/console/Create application credentials:https://eu.api.kimsufi.com/createApp/Create script credentials(all keys at once):https://eu.api.kimsufi.com/createToken/Kimsufi North AmericaDocumentation:https://ca.api.kimsufi.com/Community support:api-subscribe@ml.ovh.netConsole:https://ca.api.kimsufi.com/console/Create application credentials:https://ca.api.kimsufi.com/createApp/Create script credentials(all keys at once):https://ca.api.kimsufi.com/createToken/Related linksContribute:https://github.com/ovh/python-ovhReport bugs:https://github.com/ovh/python-ovh/issuesDownload:http://pypi.python.org/pypi/ovhLicense3-Clause BSD