如何连接本地与远程Odoo服务器并通过xmlrpc/erppeek插入数据?
Hey there! I’ve tackled this exact scenario multiple times, so let’s walk through how to get your local Odoo server talking to a remote one, then push data over using either Odoo’s native XML-RPC or the more user-friendly erppeek library.
Prerequisites First
Before diving into code, make sure these boxes are checked:
- Remote server accessibility: Your remote Odoo’s XML-RPC port (default 8069) is open in the firewall, and your local machine can reach the remote server’s IP/domain (test with
telnet your-remote-ip 8069to confirm). - Valid credentials: You have a user account on the remote server with permissions to create records in the models you’re syncing (e.g.,
res.partnerfor customers). Avoid using the admin account unless absolutely necessary—grant least-privilege access. - XML-RPC enabled: Remote Odoo has XML-RPC turned on (it’s enabled by default, but double-check your
odoo.confforxmlrpc_portandxmlrpc_interfacesettings if you run into issues).
Method 1: Using Odoo’s Native XML-RPC
XML-RPC is built into Odoo, so no extra packages are needed (Python’s standard xmlrpc.client does the job). Here’s how to set it up:
Step 1: Connect to Both Local & Remote Servers
First, establish connections to both servers and authenticate:
import xmlrpc.client # --- Remote Server Setup --- remote_url = "http://your-remote-server-ip:8069" remote_db = "remote_database_name" remote_user = "your-remote-username" remote_pass = "your-remote-password" # Authenticate with remote server remote_common = xmlrpc.client.ServerProxy(f"{remote_url}/xmlrpc/2/common") remote_uid = remote_common.authenticate(remote_db, remote_user, remote_pass, {}) if not remote_uid: raise Exception("Failed to authenticate with remote server! Check credentials/connection.") # Get proxy for remote model operations remote_models = xmlrpc.client.ServerProxy(f"{remote_url}/xmlrpc/2/object") # --- Local Server Setup --- local_url = "http://localhost:8069" local_db = "local_database_name" local_user = "local-username" local_pass = "local-password" local_common = xmlrpc.client.ServerProxy(f"{local_url}/xmlrpc/2/common") local_uid = local_common.authenticate(local_db, local_user, local_pass, {}) if not local_uid: raise Exception("Failed to authenticate with local server!") local_models = xmlrpc.client.ServerProxy(f"{local_url}/xmlrpc/2/object")
Step 2: Pull Data from Local & Push to Remote
Let’s use customer records (res.partner) as an example. We’ll fetch local customers, check if they exist remotely, and create them if not:
# Fetch customers from local Odoo (filter for actual customers) local_customers = local_models.execute_kw( local_db, local_uid, local_pass, 'res.partner', 'search_read', [[['customer_rank', '>', 0]]], # Filter: only records marked as customers {'fields': ['name', 'email', 'phone']} # Fields to sync ) # Sync each customer to remote server for customer in local_customers: # Check if customer already exists remotely (using email as unique identifier) existing_ids = remote_models.execute_kw( remote_db, remote_uid, remote_pass, 'res.partner', 'search', [[['email', '=', customer['email']]]] ) if not existing_ids: # Create new customer on remote server new_customer_id = remote_models.execute_kw( remote_db, remote_uid, remote_pass, 'res.partner', 'create', [{ 'name': customer['name'], 'email': customer['email'], 'phone': customer['phone'] }] ) print(f"Successfully created customer: {customer['name']} (Remote ID: {new_customer_id})") else: print(f"Customer {customer['name']} already exists on remote server (ID: {existing_ids[0]})")
Method 2: Using erppeek (Simpler Syntax)
erppeek is a third-party library that wraps XML-RPC into a more intuitive, ORM-like interface. It’s great if you want cleaner code.
Step 1: Install erppeek
First, install the package via pip:
pip install erppeek
Step 2: Connect & Sync Data
The code is much more concise with erppeek:
import erppeek # Connect to remote Odoo remote_client = erppeek.Client( 'http://your-remote-server-ip:8069', db='remote_database_name', user='your-remote-username', password='your-remote-password' ) # Connect to local Odoo local_client = erppeek.Client( 'http://localhost:8069', db='local_database_name', user='local-username', password='local-password' ) # Fetch local customers local_customers = local_client.ResPartner.search_read( [('customer_rank', '>', 0)], ['name', 'email', 'phone'] ) # Sync to remote for customer in local_customers: # Check for existing customer existing_customer = remote_client.ResPartner.search([('email', '=', customer['email'])]) if not existing_customer: new_customer = remote_client.ResPartner.create({ 'name': customer['name'], 'email': customer['email'], 'phone': customer['phone'] }) print(f"Created customer: {customer['name']} (Remote ID: {new_customer.id})") else: print(f"Customer {customer['name']} already exists (Remote ID: {existing_customer[0]})")
Key Notes for Production
- Error Handling: Add
try-exceptblocks to catch network timeouts, permission errors, or data validation issues. For example:try: new_customer = remote_client.ResPartner.create(...) except Exception as e: print(f"Failed to sync {customer['name']}: {str(e)}") - Security: If syncing over the public internet, use HTTPS (port 8071 by default) to encrypt credentials and data.
- Avoid Duplicates: Instead of using email (which might be missing), consider adding a custom
external_idfield to your local model to track remote IDs, ensuring one-way sync without duplicates. - Performance: For large datasets, use batch operations instead of looping through each record individually to reduce API calls.
内容的提问来源于stack exchange,提问作者Esraa

