Perform the following steps to create, write, and unlink a book's information through RPC:
- Add the jsonrpc_operation.py file. You can place this file anywhere you want because the RPC program will work independently.
- Add the following code to the file:
# place authentication and get_json_payload method (see last recipe for more)
if user_id:
# creates the books records
create_data = [
{'name': 'Book 1', 'date_release': '2019-01-26'},
{'name': 'Book 3', 'date_release': '2019-02-12'},
{'name': 'Book 5', 'date_release': '2019-05-08'},
{'name': 'Book 7', 'date_release': '2019-05-14'}
]
payload = get_json_payload("object", "execute_kw", db_name, user_id, password, 'library.book', 'create', [create_data])
res = requests.post(json_endpoint, data=payload, headers=headers).json()
print("Books created:", res)
books_ids = res['result']
# Write in existing book record
book_to_write = books_ids[1] # We will use ids of recently created books
write_data = {'name': 'Book 2'}
payload = get_json_payload("object", "execute_kw", db_name, user_id, password, 'library.book', 'write', [book_to_write, write_data])
res = requests.post(json_endpoint, data=payload, headers=headers).json()
print("Books written:", res)
# Delete in existing book record
book_to_unlink = books_ids[2:] # We will use ids of recently created books
payload = get_json_payload("object", "execute_kw", db_name, user_id, password, 'library.book', 'unlink', [book_to_unlink])
res = requests.post(json_endpoint, data=payload, headers=headers).json()
print("Books deleted:", res)
else:
print("Failed: wrong credentials")
- Run the Python script from the Terminal with the following command:
python3 jsonrpc_operation.py
The preceding program will create four books. Writing one book and deleting two books gives you the following output (the IDs created may be different based on on your database):