External API - Integrating with Other Systems

Total Page:16

File Type:pdf, Size:1020Kb

External API - Integrating with Other Systems External API - Integrating with Other Systems Overview Overview The PerfectWORK server provides an external API, which is used by its web client and is available for other client applications. In this chapter, we'll learn how to use the PerfectWORK external API from our own client programs, using PerfectWORK's external API. To avoid introducing additional languages the reader might not be familiar with, here we will focus on Python-based clients, although the techniques to handle the RPC calls also applies to other programming languages. We'll describe how to use the PerfectWORK RPC calls, and then use that knowledge to build a simple Library command-line application using Python. Setting up Python on the client machine The Odoo API can be accessed externally using two different protocols: XML-RPC and JSON-RPC. Any external program capable of implementing a client for one of these protocols will be able to interact with an Odoo server. To avoid introducing additional programming languages, we will keep using Python to explore the external API. Until now, we have been running Python code only on the server. This time, we will use Python on the client side, so it's possible you might need to do some additional setup on your workstation. To follow the examples in this chapter, you'll need to be able to run Python files on your work computer. We will be using Python 3 for this. At this point, you should make sure you have Python 3 installed in your workstation. This can be confirmed running the python3 --version command in a Terminal. If not, you may refer the official website for your platform's installation package, at https:/​/​www.​python.​org/​downloads/​. For Ubuntu, at this point, you probably already have Python 3 installed. If not, you can install it by running the following: $ sudo apt-get install python3 python3-pip If you are a Windows user and have Odoo installed on your machine, you may be wondering why you don't already have a Python interpreter and why additional installation is needed. The short answer is that the Odoo installation has an embedded Python interpreter that isn't easily used outside. Connecting to Odoo API using XML- RPC The simplest method to access the server is using XML-RPC. We can use the xmlrpclib library from Python's standard library for this. Remember that we are programming a client to connect to a server, so we need an Odoo server instance running to connect to. In our examples, we will assume that an Odoo server instance is running on the same machine (localhost), but you can use any reachable IP address or server name, if the server is running on a different machine. Let's make first contact with the Odoo external API. Start a Python 3 console and type in the following: >>> from xmlrpc import client >>> srv = 'http://localhost:8069' >>> common = client.ServerProxy('%s/xmlrpc/2/common' % srv) >>> common.version(){'server_version': '12.0', 'server_version_info': [12, 0, 0, 'final', 0,''], 'server_serie': '12.0', 'protocol_version': 1} Here, we import the xmlrpc.client library and then set up a variable with the information for the server address and listening port. Feel free to adapt these to your specific setup. Next, we set up access to the server's public services (not requiring a login), exposed at the /xmlrpc/2/common endpoint. One of the methods that's available is version(), which inspects the server version. We use it to confirm that we can communicate with the server. Another public method is authenticate(). In fact, this doesn't create a session, as you might be led to believe. This method just confirms that the username and password are accepted and returns the user ID that should be used in requests instead of the username, as shown here: >>> db = '12-library' >>> user, pwd = 'admin', 'admin' >>> uid = common.authenticate(db, user, pwd, {})>>> print(uid) 2 We start by setting, in the db variable, the database name we will use. In our example, it's 12- library, but you are free to change it if you are working with a database with a different name. If the login credentials are not correct, a False value is returned, instead of a user ID. The authenticate() last argument is the user agent environment, used to provide the server with some metadata about the client. It's mandatory, but can be an empty dictionary. Running server methods using XML-RPC With XML-RPC, no session is maintained and the authentication credentials are sent with every request. This adds some overhead to the protocol, but makes it simpler to use. Next, we set up access to the server methods that need a login to be accessed. These are exposed at the /xmlrpc/2/object endpoint, as shown in the following: >>> api = client.ServerProxy('%s/xmlrpc/2/object' % srv) >>> api.execute_kw(db, uid, pwd, 'res.partner', 'search_count', [[]]) 42 Here, we are accessing the server API for the first time, performing a count on the Partner records. Methods are called using the execute_kw() method that takes the following arguments: The name of the database to connect to The connection user ID The user password The target model identifier name The method to call A list of positional arguments An optional dictionary with keyword arguments (not used in the example) The preceding example calls the search_count method of the res.partner model with one positional argument, [], and no keyword arguments. The positional argument is a search domain; since we are providing an empty list, it counts all of the Partners. Frequent actions are search and read. When called from the RPC, the search method returns a list of IDs matching a domain. The browse method is not available from the RPC, and read should be used in its place to obtain a list of record IDs and retrieve their data, as shown in the followingcode: >>> domain = [('is_company', '=', True)] >>> api.execute_kw(db, uid, pwd, 'res.partner', 'search', [domain])[14, 10, 11, 15, 12, 13, 9, 1] >>> api.execute_kw(db, uid, pwd, 'res.partner', 'read', [[14]], {'fields':['id', 'name', 'country_id']})[ {'id': 14, 'name': 'Azure Interior', 'country_id': [233, 'UnitedStates']}] Note that, for the read method, we're using one positional argument for the list of IDs, [14], and one keyword argument, fields. We can also notice that many-to-one relational fields, such as country_id, are retrieved as a pair, with the related record's ID and display name. That's something to keep in mind when processing the data in your code. The search and read combination is so frequent that a search_read method is provided to perform both operations in a single step. The same result from the previous two steps can be obtained with the following instruction: >>> api.execute_kw(db, uid, pwd, 'res.partner', 'search_read', [domain], {'fields': ['id', 'name', 'country_id']}) The search_read method behaves like read, but expects a domain as a first positional argument instead of a list of IDs. It's worth mentioning that the fields argument on read and search_read isn't mandatory. If not provided, all fields will be retrieved. This may cause expensive computations of function fields and a large amount of data to be retrieved but probably never used, so it is generally recommended to provide an explicit list of fields. Search and read API methods We have seen, in Chapter 7, Recordsets – Working with Model Data, the most important model methods used to generate recordsets and how to write to them. But there are a few more model methods available for more specific actions, as shown here: read([fields]) is similar to the browse method, but, instead of a recordset, it returns a list of rows of data with the fields given as its argument. Each row is a dictionary. It provides a serialized representation of the data that can be sent through RPC protocols and is intended to be used by client programs and not in server logic. search_read([domain], [fields], offset=0, limit=None, order=None) performs a search operation followed by a read on the resulting record list. It's intended to be used by RPC clients and saves them the extra round trip needed when doing search followed by read on the results. All other model methods are exposed through RPC, except for the ones prefixed with an underscore, which are considered private. This means that we can use create, write, and unlink to modify data on the server as follows: >>> x = api.execute_kw(db, uid, pwd, 'res.partner', 'create', [{'name': 'Packt Pub'}]) >>> print(x) 51 >>> api.execute_kw(db, uid, pwd, 'res.partner', 'write', [[x], {'name': 'Packt Publishing'}])True >>> api.execute_kw(db, uid, pwd, 'res.partner', 'read', [[x], ['id', 'name']])[{'id': 51, 'name': 'Packt Publishing'}] >>> api.execute_kw(db, uid, pwd, 'res.partner', 'unlink', [[x]])True>>> api.execute_kw(db, uid, pwd, 'res.partner', 'read', [[x]])[] One limitation of the XML-RPC protocol is that it does not support None values. There's an XML- RPC extension that supports None values, but whether this is available will depend on the particular XML-RPC library being used on your client. Methods that don't return anything may not be usable through XML-RPC, since they are implicitly returning None. This is why methods should always finish with at least a return True statement. Another alternative is to use JSON-RPC instead, also supported. The OdooRPC library allows for this, and we will use it later in this chapter, in the Using the OdooRPC library section. It is worth repeating that the Odoo external API can be used by most programming languages.
Recommended publications
  • Intermedia: a System for Linking Multimedia Documents. IRIS
    DOCUMENT RESUME ED 296 735 IR 052 399 AUTHOR Yankelovich, Nicole TITLE Intermedia: A System for Linking Multimrdia Documents. IRIS Technical Report 86-2. INSTITUTION Brown Univ., Providence, RI. Inst. for Research in Information and Scholarship. PUB DATE 86 NOTE 19p. PUB TYPE Reports - Descriptive (141) EDRS PRICE MF01/PC01 Plus Postage. D'1CRIPTORS Bibliographic Coupling; *Computer Assisted Instruction; Computer Graphics; *Computer System Design; Higher Education; *Information Retrieval; *Man Machine Systems; *Multimedia Instruction; Word Processing IDENTIFIERS *Hypermedia ABSTRACT "Intermedia" is a hypermedia system which was developed for use in university research and teaching. It provides a framework for object-oriented, direct manipulation editors and applications, and the capability to link together materials created with those applications. Instructors are able to construct exploratory environments for their students as well as use applications for their day-to-day work, research, and writing. This paper provides a discussion of hypermedia systems in general, as well as a description of the Intermedia system which focuses on several important user features, and illustrates the operation of the system thrw,h a sample session. The text is supplemented by 15 figures. (19 references) (Author/EW) *********************************************************************** Reproductions supplied by EDRS are the best that can be made from the original document. *********************************************************************** INTERMEDIA: A System for customizing, visualizing, integratingand 0 Linking Multimedia Documents retrieving information. oi This paper describes Intermedia,one such tool designed for use in theuniversity O Nicole Yankelovich environment. The system, developedat Lid "PERMISSION TO REPRODUCE THIS Brown University's Institute for Researchin MATERIAL HAS BEEN GRANTED BY Information and Scholarship (IRIS),contains U.S.
    [Show full text]
  • Io — I/O Functions
    Title stata.com io — I/O functions Contents Description Remarks and examples Reference Also see Contents [M-5] Manual entry Function Purpose Console output printf( ) printf() display sprintf() display into string errprintf( ) errprintf() display error message display( ) display() display text interpreting SMCL displayas( ) displayas() set whether output is displayed displayflush( ) displayflush() flush terminal output buffer liststruct( ) liststruct() list structure’s contents more( ) more() create --more-- condition setmore() query or set more on or off setmoreonexit() set more on or off on exit File directories direxists( ) direxists() whether directory exists dir( ) dir() file list chdir( ) pwd() obtain current working directory chdir() change current working directory mkdir() make new directory rmdir() remove directory File management findfile( ) findfile() find file fileexists( ) fileexists() whether file exists cat( ) cat() read file into string matrix unlink( ) unlink() erase file adosubdir( ) adosubdir() obtain ado-subdirectory for file 1 2 io — I/O functions File I/O fopen( ) fopen() open file fclose() close file fget() read line of ASCII file fgetnl() same, but include newline character fread() read k bytes of binary file fput() write line into ASCII file fwrite() write k bytes into binary file fgetmatrix() read matrix fputmatrix() write matrix fstatus() status of last I/O command ftell() report location in file fseek() seek to location in file ftruncate() truncate file at current position ferrortext( ) ferrortext() error text of file error code freturncode()
    [Show full text]
  • Version 7.8-Systemd
    Linux From Scratch Version 7.8-systemd Created by Gerard Beekmans Edited by Douglas R. Reno Linux From Scratch: Version 7.8-systemd by Created by Gerard Beekmans and Edited by Douglas R. Reno Copyright © 1999-2015 Gerard Beekmans Copyright © 1999-2015, Gerard Beekmans All rights reserved. This book is licensed under a Creative Commons License. Computer instructions may be extracted from the book under the MIT License. Linux® is a registered trademark of Linus Torvalds. Linux From Scratch - Version 7.8-systemd Table of Contents Preface .......................................................................................................................................................................... vii i. Foreword ............................................................................................................................................................. vii ii. Audience ............................................................................................................................................................ vii iii. LFS Target Architectures ................................................................................................................................ viii iv. LFS and Standards ............................................................................................................................................ ix v. Rationale for Packages in the Book .................................................................................................................... x vi. Prerequisites
    [Show full text]
  • Cygwin User's Guide
    Cygwin User’s Guide Cygwin User’s Guide ii Copyright © Cygwin authors Permission is granted to make and distribute verbatim copies of this documentation provided the copyright notice and this per- mission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this documentation under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this documentation into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. Cygwin User’s Guide iii Contents 1 Cygwin Overview 1 1.1 What is it? . .1 1.2 Quick Start Guide for those more experienced with Windows . .1 1.3 Quick Start Guide for those more experienced with UNIX . .1 1.4 Are the Cygwin tools free software? . .2 1.5 A brief history of the Cygwin project . .2 1.6 Highlights of Cygwin Functionality . .3 1.6.1 Introduction . .3 1.6.2 Permissions and Security . .3 1.6.3 File Access . .3 1.6.4 Text Mode vs. Binary Mode . .4 1.6.5 ANSI C Library . .4 1.6.6 Process Creation . .5 1.6.6.1 Problems with process creation . .5 1.6.7 Signals . .6 1.6.8 Sockets . .6 1.6.9 Select . .7 1.7 What’s new and what changed in Cygwin . .7 1.7.1 What’s new and what changed in 3.2 .
    [Show full text]
  • Chapter 19 RECOVERING DIGITAL EVIDENCE from LINUX SYSTEMS
    Chapter 19 RECOVERING DIGITAL EVIDENCE FROM LINUX SYSTEMS Philip Craiger Abstract As Linux-kernel-based operating systems proliferate there will be an in­ evitable increase in Linux systems that law enforcement agents must process in criminal investigations. The skills and expertise required to recover evidence from Microsoft-Windows-based systems do not neces­ sarily translate to Linux systems. This paper discusses digital forensic procedures for recovering evidence from Linux systems. In particular, it presents methods for identifying and recovering deleted files from disk and volatile memory, identifying notable and Trojan files, finding hidden files, and finding files with renamed extensions. All the procedures are accomplished using Linux command line utilities and require no special or commercial tools. Keywords: Digital evidence, Linux system forensics !• Introduction Linux systems will be increasingly encountered at crime scenes as Linux increases in popularity, particularly as the OS of choice for servers. The skills and expertise required to recover evidence from a Microsoft- Windows-based system, however, do not necessarily translate to the same tasks on a Linux system. For instance, the Microsoft NTFS, FAT, and Linux EXT2/3 file systems work differently enough that under­ standing one tells httle about how the other functions. In this paper we demonstrate digital forensics procedures for Linux systems using Linux command line utilities. The ability to gather evidence from a running system is particularly important as evidence in RAM may be lost if a forensics first responder does not prioritize the collection of live evidence. The forensic procedures discussed include methods for identifying and recovering deleted files from RAM and magnetic media, identifying no- 234 ADVANCES IN DIGITAL FORENSICS tables files and Trojans, and finding hidden files and renamed files (files with renamed extensions.
    [Show full text]
  • Dmlite Shell
    DMLite Shell Ivan Calvet CERN IT/SDC-ID 4th DPM Workshop 13th December 2013 Presentation of DMLite Shell . Tool to administrate DMLite . Shell who provides bash-like commands . Made for admins and developers, not for users (root access needed) DMLite Shell – 4th DPM Workshop 13/12/13 2 Under the hood . Developed in Python (2.4) . Based on the python wrapper for DMLite called pydmlite DMLite Shell – 4th DPM Workshop 13/12/13 3 Usage as a command . Execute only one command: . Execute a script: DMLite Shell – 4th DPM Workshop 13/12/13 4 Usage as a shell (1/2) . Launch the shell: . Launch it with a specific configuration: DMLite Shell – 4th DPM Workshop 13/12/13 5 Usage as a shell (2/2) . Auto-completion . Type checking . Syntax checking DMLite Shell – 4th DPM Workshop 13/12/13 6 Commands (1/2) . 41 commands: . 5 to manage the shell: init, help, version, getimplid, exit . 20 to manage files: pwd, cd, ls, mkdir, unlink, rmdir, mv, du, ln, readlink, comment, info, create, chmod, chown, chgrp, checksum, utime, acl, setguid . 3 to manage replicas: replicaadd, replicamodify, replicadel DMLite Shell – 4th DPM Workshop 13/12/13 7 Commands (2/2) . 5 to manage pools: pooladd, poolinfo, poolmodify, pooldel, qryconf . 4 to manage users: useradd, userinfo, userban, userdel . 4 to manage groups: groupadd, groupinfo, groupban, groupdel DMLite Shell – 4th DPM Workshop 13/12/13 8 Demonstration DMLite Shell – 4th DPM Workshop 13/12/13 9 Need help? https://svnweb.cern.ch/trac/lcgdm/wiki/Dpm/Dev/Dmlite/Shell Check the Man page DMLite Shell – 4th DPM Workshop 13/12/13 10 Future improvements .
    [Show full text]
  • 21Files2.Pdf
    Here is a portion of a Unix directory tree. The ovals represent files, the rectangles represent directories (which are really just special cases of files). A simple implementation of a directory consists of an array of pairs of component name and inode number, where the latter identifies the target file’s inode to the operating system (an inode is data structure maintained by the operating system that represents a file). Note that every directory contains two special entries, “.” and “..”. The former refers to the directory itself, the latter to the directory’s parent (in the case of the slide, the directory is the root directory and has no parent, thus its “..” entry is a special case that refers to the directory itself). While this implementation of a directory was used in early file systems for Unix, it suffers from a number of practical problems (for example, it doesn’t scale well for large directories). It provides a good model for the semantics of directory operations, but directory implementations on modern systems are more complicated than this (and are beyond the scope of this course). Here are two directory entries referring to the same file. This is done, via the shell, through the ln command which creates a (hard) link to its first argument, giving it the name specified by its second argument. The shell’s “ln” command is implemented using the link system call. Here are the (abbreviated) contents of both the root (/) and /etc directories, showing how /unix and /etc/image are the same file. Note that if the directory entry /unix is deleted (via the shell’s “rm” command), the file (represented by inode 117) continues to exist, since there is still a directory entry referring to it.
    [Show full text]
  • The Updated Content Editor in Blackboard Learn
    The Updated Content Editor in Blackboard Learn Detailed comparison for tools Current Content Editor New Content Editor Comments Bold, Italics, Underline, and Strikethrough. Functionality unchanged, but Latin characters B, I, U, and S represent the formatting instead of T for all. In the format drop-down, relative sizes are now displayed. Formatted code is renamed preformatted. In the size selector, absolute sizes are shown rather than relative size indicators with an absolute size in parenthesis. Font choices are displayed as the indicated font rather than just a list of font names. Bullet type options are now displayed visually rather than as a text list. List type options are now displayed visually rather than as a text list. Options are reorganized into a single window to find and replace. When searching, there are new options to find by whole words only or just in the selection. Current Content Editor New Content Editor Comments Text and background color selection menus have been reorganized. Color picker options have been simplified into a page instead of having multiple tabs. The “highlight color” tool has been renamed the “background color” tool. The remove formatting icon has changed. Cut and copy are generally unchanged. Paste has one change and several enhancements. • When pasting a link for the following websites, it will automatically be converted into embedded media content: YouTube, Daily Motion, Vimeo. • The New York Times, WordPress, SlideShare, and Facebook will embed summary previews of the linked content. • Pasting from Microsoft Word and Excel has been improved and now supports retaining images as part of the paste.
    [Show full text]
  • Injection Attacks
    1 Web Security I: Injection Attacks Chengyu Song Slides modified from Dawn Song and John Mitchell 2 What is Web? Web is a platform for deploying applications and sharing information, portably and securely 3 Hypertext Transfer Protocol HTTP: a common data communication protocol on the web. 4 Uniform Resource Locator URL: global identifiers of network-retrievable resources 5 HTTP request Sending commands to the sever side, like system call. 6 HTTP response Retrieving results from the server side, like system call returns. 7 HyperText Markup Language HTML: a markup language to create structured documents that can embed images, objects, create interactive forms, etc. <html> <body> <div>foo <a href="http://google.com">Go to Google!</a></div> <form> <input type="text" /> <input type="radio" /> <input type="checkbox" /> </form> </body> </html> 8 Web security: a historical perspective • Similar to Internet, web is an example of "bolt-on security" • Originally, the World Wide Web (www) was invented to allow physicists to share their research papers • Only textual web pages + links to other pages • No security model to speak of 9 Web security: nowadays • The web became complex and adversarial quickly • Web pages become very complex with embedded images, JavaScript, dynamic HTML, AJAX, CSS, frames, audio, video, sensors, VR, ... from different servers • Today, a web site is a distributed application • Web applications also become very diverse, news, shopping, videos, social network, banking, gaming, ... • Attackers have various motivations 10 Desirable
    [Show full text]
  • Mckesson Radiology™ Radiologist Manual
    McKesson Radiology™ Radiologist Manual Revision 1.0 Document ID: 2016-35625 McKesson Radiology Radiologist Manual Table of Contents Chapter 1 – McKesson Terminology ............................................................................................................................................ 5 Chapter 2 – The McKesson Radiology PACS Dataflow ................................................................................................................. 7 Chapter 3 – Understanding McKesson Radiology ........................................................................................................................ 8 Logging on to McKesson Radiology ......................................................................................................................................... 8 Properties of the Study Lists .................................................................................................................................................... 8 Customizing the Study Lists ................................................................................................................................................... 13 Custom Filters ........................................................................................................................................................................ 14 Chapter 4 – Rad Report ............................................................................................................................................................. 17 What is Rad Report
    [Show full text]
  • Gnu Coreutils Core GNU Utilities for Version 5.93, 2 November 2005
    gnu Coreutils Core GNU utilities for version 5.93, 2 November 2005 David MacKenzie et al. This manual documents version 5.93 of the gnu core utilities, including the standard pro- grams for text and file manipulation. Copyright c 1994, 1995, 1996, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”. Chapter 1: Introduction 1 1 Introduction This manual is a work in progress: many sections make no attempt to explain basic concepts in a way suitable for novices. Thus, if you are interested, please get involved in improving this manual. The entire gnu community will benefit. The gnu utilities documented here are mostly compatible with the POSIX standard. Please report bugs to [email protected]. Remember to include the version number, machine architecture, input files, and any other information needed to reproduce the bug: your input, what you expected, what you got, and why it is wrong. Diffs are welcome, but please include a description of the problem as well, since this is sometimes difficult to infer. See section “Bugs” in Using and Porting GNU CC. This manual was originally derived from the Unix man pages in the distributions, which were written by David MacKenzie and updated by Jim Meyering.
    [Show full text]
  • Basilisk.Utils.Pdf
    Package ‘basilisk.utils’ September 24, 2021 Version 1.5.0 Date 2021-04-08 Title Basilisk Installation Utilities Imports utils, methods, tools, dir.expiry Suggests knitr, rmarkdown, BiocStyle, testthat biocViews Infrastructure Description Implements utilities for installation of the basilisk package, primarily for creation of the underlying Conda instance. This allows us to avoid re-writing the same R code in both the configure script (for centrally administered R installations) and in the lazy installation mechanism (for distributed package binaries). It is highly unlikely that developers - or, heaven forbid, end-users! - will need to interact with this package directly; they should be using the basilisk package instead. License GPL-3 RoxygenNote 7.1.1 VignetteBuilder knitr git_url https://git.bioconductor.org/packages/basilisk.utils git_branch master git_last_commit ea7cb0c git_last_commit_date 2021-05-19 Date/Publication 2021-09-24 Author Aaron Lun [aut, cre, cph] Maintainer Aaron Lun <[email protected]> R topics documented: activateEnvironment . .2 cleanConda . .3 clearExternalDir . .4 destroyOldVersions . .5 1 2 activateEnvironment dir.create2 . .6 getBinaries . .7 getCondaDir . .8 getExternalDir . .9 getSystemDir . 10 installConda . 10 isWindows . 12 lockExternalDir . 12 setCondaPackageDir . 13 setVariable . 14 unlink2 . 15 useSystemDir . 16 Index 17 activateEnvironment Activate a Conda environment Description Mimic the (de)activation of a Conda environment by modifying environment variables in the current R process. Usage activateEnvironment(envpath = NULL, loc = getCondaDir()) deactivateEnvironment(listing) Arguments envpath String containing the path to the Conda environment to activate. If NULL, the base Conda instance at getCondaDir() is activated. loc String containing the path to the root of a conda instance. listing Named list of strings containing name:value pairs for environment variables, typically the output of activateEnvironment.
    [Show full text]