def createrpcconncetion(port):
     return xmlrpclib.ServerProxy("http://127.0.0.1:%s/" % port)
Esempio n. 2
0
 def __init__(self, url):
   super(GFiberTvMailbox, self).__init__()
   self.rpcclient = xmlrpclib.ServerProxy(url)
   self.Name = ''
   self.Node = ''
Esempio n. 3
0
from multiprocessing import Pool

import subprocess
import os
import json
import shutil
import xmlrpclib

PYPI = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
PATH = "/tmp/pypy.space"
PIP_CACHE = "/tmp/pipcache"
DOWNLOAD_PROCESSES = 50


def thing(args):
    name, count = args
    p = subprocess.Popen('docker run -v %s:/pipcache pypyspace pypy-5.0.0-linux64/bin/pypy -m pip --cache-dir=/pipcache install %s' % (PIP_CACHE, name),
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    stdout, _ = p.communicate()

    print "=" * 30, name, p.returncode, "=" * 30
    print stdout

    return name, p.returncode, stdout, count


if __name__ == '__main__':

    if os.path.exists(PATH):
Esempio n. 4
0
                #        print(attachment)
                #        binary_attachment = source.wiki.getAttachment(attachment).data
                #        try:
                #            attachment_path = dest.create_wiki_attachment(dest_project_id, users_map[info['author']], convert_xmlrpc_datetime(info['lastModified']), attachment, binary_attachment)
                #        except KeyError:
                #            attachment_path = dest.create_wiki_attachment(dest_project_id, default_user, convert_xmlrpc_datetime(info['lastModified']), attachment, binary_attachment)
                #        attachment_name = attachment.split('/')[-1]
                #        converted = converted.replace(r'](%s)' % attachment_name, r'](%s)' % os.path.relpath(attachment_path, '/namespace/project/wiki/page'))
                print('skip attachment', attachment)


if __name__ == "__main__":
    dest = Connection(gitlab_url, gitlab_access_token, dest_ssl_verify,
                      gitlab_impers_tokens_map)

    source = xmlrpclib.ServerProxy(trac_url)
    dest_project_id = get_dest_project_id(dest, dest_project_name)

    #    if svngit_mapfile is not None :
    #        svngit_map = dict()
    #        for line in open(svngit_mapfile, 'r') :
    #            l = line.split()
    #            assert len(l) >= 2, line
    #            githash = l[0]
    #            svnrev = l[1]
    #            svnbranch = l[2][1:] if len(l) > 2 else 'trunk'
    #            #print l[1], l[0]
    #            # if already have a svn revision entry from branch trunk, then ignore others
    #            if svnrev in svngit_map and svngit_map[svnrev][1] == 'trunk' :
    #                continue
    #            svngit_map[svnrev] = [githash, svnbranch]
# This is an example of how to connect to and use the Bitmessage API.
# See https://bitmessage.org/wiki/API_Reference

import xmlrpclib
import json
import time

if __name__ == '__main__':

    api = xmlrpclib.ServerProxy("http://*****:*****@localhost:8442/")

    print 'Let\'s test the API first.'
    inputstr1 = "hello"
    inputstr2 = "world"
    print api.helloWorld(inputstr1, inputstr2)
    print api.add(2,3)

    print 'Let\'s set the status bar message.'
    print api.statusBar("new status bar message")

    print 'Let\'s list our addresses:'
    print api.listAddresses()

    print 'Let\'s list our address again, but this time let\'s parse the json data into a Python data structure:'
    jsonAddresses = json.loads(api.listAddresses())
    print jsonAddresses
    print 'Now that we have our address data in a nice Python data structure, let\'s look at the first address (index 0) and print its label:'
    print jsonAddresses['addresses'][0]['label']

    print 'Uncomment the next two lines to create a new random address with a slightly higher difficulty setting than normal.'
    #addressLabel = 'new address label'.encode('base64')
Esempio n. 6
0
import xmlrpclib

n = 100  # se puede poner cualquier numero
server = xmlrpclib.ServerProxy('http://localhost:8080/')
print('adding number from 1 to ', n, " is equal to ", server.addThreads(n))
Esempio n. 7
0
def make_proxy(url, cert, key):
    return xmlrpclib.ServerProxy(url,
                                 transport=SafeTransportWithCert(cert, key),
                                 allow_none=True)
Esempio n. 8
0
#!/usr/local/bin/python2.7
# -*- coding:utf-8 -*-
import sys
import xmlrpclib

XML_RPC = "http://localhost:19388/RPC2"
g_xmlrpc_proxy = xmlrpclib.ServerProxy(XML_RPC)


def pkt_in(arg):
    pkt_in_rpc = g_xmlrpc_proxy.pkt_in(arg)
    print(pkt_in_rpc)


def proxyed(arg):
    proxyed_rpc = g_xmlrpc_proxy.proxyed(arg)
    print(proxyed_rpc)


def exec_insert():
    try:
        sys.argv[1]
        if sys.argv[1].split(':')[0] not in ['on', 'off', 'sm300', 'sm200']:
            print "wrong argv, must be: on:xxxx(ruleid) off:xxxx(ruleid)"
            sys.exit(0)
        else:
            pkt_in_(arg)
    except Exception as e:
        print "need argv: on:xxxx off:xxxx"
        print "exec default configuration"
        insert_power(arg)
Esempio n. 9
0
EXAMPLES = '''
  - name: Create a test app
    webfaction_app:
      name="my_wsgi_app1"
      state=present
      type=mod_wsgi35-python27
      login_name={{webfaction_user}}
      login_password={{webfaction_passwd}}
      machine={{webfaction_machine}}
'''

import xmlrpclib

from ansible.module_utils.basic import AnsibleModule

webfaction = xmlrpclib.ServerProxy('https://api.webfaction.com/')


def main():

    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True),
        state=dict(required=False,
                   choices=['present', 'absent'],
                   default='present'),
        type=dict(required=True),
        autostart=dict(required=False, type='bool', default=False),
        extra_info=dict(required=False, default=""),
        port_open=dict(required=False, type='bool', default=False),
        login_name=dict(required=True),
        login_password=dict(required=True, no_log=True),
Esempio n. 10
0
#!/usr/bin/env python
import csv
import functools
import xmlrpclib
HOST = '70.35.200.126'
#HOST = '172.17.0.2'
PORT = 8069
DB = 'CMT_1_0'
USER = '******'
PASS = '******'
ROOT = 'http://%s:%d/xmlrpc/' % (HOST, PORT)

# 1. Login
uid = xmlrpclib.ServerProxy(ROOT + 'common').login(DB, USER, PASS)
print "Logged in as %s (uid:%d)" % (USER, uid)

call = functools.partial(
    xmlrpclib.ServerProxy(ROOT + 'object').execute, DB, uid, PASS)
#*****************************************************************************************
#*****************************************************************************************
reader = csv.reader(open('CSuprema.csv', 'rb'))

#actualizar campos de contactos comparando por nombre
for row in reader:
    nome = row[0]
    nombre = call('res.partner', 'search', [('name', '=', nome)])

    if len(nombre) > 0:
        print nombre[0]
        partner_id = call('res.partner', 'write', [nombre[0]],
                          {'x_cmt_prospeccion': 2})
Esempio n. 11
0
import xmlrpclib

server = xmlrpclib.ServerProxy(
    "http://www.pythonchallenge.com/pc/phonebook.php")
eg_obj = server.phone("Bert")

print eg_obj
Esempio n. 12
0
 def run(self):
     self.server = xmlrpclib.ServerProxy(self.url)
     self.server.init()
     while self.shouldIRun.isSet():
         self.data = self.server.step()
     self.server.term()
Esempio n. 13
0
    def execute(self, sDatabase, UID, sPassword, obj, method, *args):
        global rpc_url

        sock = xmlrpclib.ServerProxy(rpc_url + 'object')

        return sock.execute(sDatabase, UID, sPassword, obj, method, *args)
Esempio n. 14
0
 def __connect(self):
     # Get proxy to server
     url = "http://%s:%d" % (self.host, self.port)
     self._proxy = xmlrpclib.ServerProxy(url, allow_none=True)
     return self._proxy
Esempio n. 15
0
    def transfer(self, cr, uid, order_id, context=None):
        _logger = logging.getLogger(__name__)
        def_id = self.search(cr, uid, [("in_use", '=', True)], context=None)
        if not def_id:
            return None

        record = self.browse(cr, uid, def_id, context=None)

        order = self.pool.get('sale.order').browse(cr,
                                                   uid,
                                                   order_id,
                                                   context=None)[0]
        _logger.info("++++++ %s" % order.name)

        #CREATE PO local
        po_client = record.po_client_id

        vals = {
            'partner_id': po_client,
            'location_id': 1,
            'pricelist_id': order.pricelist_id.id
        }

        po_local_id = self.pool.get('purchase.order').create(cr,
                                                             uid,
                                                             vals,
                                                             context=None)

        for line in order.order_line:
            vals = {
                'product_id': line.product_id.id,
                'name': line.name,
                'product_qty': line.product_uom_qty,
                'date_planned': datetime.now().strftime('%d/%m/%Y'),
                'price_unit': line.price_unit,
                'order_id': po_local_id,
                'taxes_id': [[6, False, [x.id for x in line.tax_id]]]
            }
            line_id = self.pool.get('purchase.order.line').create(cr,
                                                                  uid,
                                                                  vals,
                                                                  context=None)

        #CREATE REMOTE SO
        url = record.ro_url
        db = record.ro_db
        username = record.ro_user
        password = record.ro_pass

        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        uidx = common.authenticate(db, username, password, {})

        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

        par = models.execute_kw(
            db, uid, password, 'res.partner', 'read', [[190856]],
            {'fields': ['property_product_pricelist']})  #make user insertable

        par = par[0]
        pricelist = par['property_product_pricelist'][0] if par[
            'property_product_pricelist'] else 1
        vals = {
            'partner_id': record.remote_client_id,
            'pricelist_id': pricelist,
            'partner_invoice_id': record.remote_client_id,
            'partner_shipping_id': record.remote_client_id,
            'order_policy': 'picking',
            'picking_policy': 'direct',
            'warehouse_id': 1,
            'remote_document_id': order.name,
            'state': 'preorder'
        }

        so = models.execute_kw(db, uidx, password, 'sale.order', 'create',
                               [vals])

        for line in order.order_line:
            remote_product_id = models.execute_kw(
                db, uidx, password, 'product.product', 'search_read',
                [[['default_code', '=', line.product_id.default_code]]],
                {'fields': ['uom_id', 'product_tmpl_id']})

            vals = {
                "product_uos_qty":
                line.product_uos_qty,
                "product_uom_qty":
                line.product_uom_qty,
                "order_partner_id":
                record.remote_client_id,
                "product_template":
                remote_product_id[0]['product_tmpl_id'][0],
                "delay":
                0,
                'product_id':
                remote_product_id[0]['id'],
                'name':
                line.name,
                'product_uom':
                remote_product_id[0]['uom_id'][0]
                if 'uom_id' in remote_product_id[0] else 1,
                'price_unit':
                line.price_unit,
                'order_id':
                so,
                'tax_id': [[6, False, [x.id for x in line.tax_id]]],
                'state':
                'preorder'
            }
            models.execute_kw(db, uidx, password, 'sale.order.line', 'create',
                              [vals])
Esempio n. 16
0
    def schedule_backup(self, cr, user, context={}):
        conf_ids = self.search(cr, user, [])
        confs = self.browse(cr, user, conf_ids)
        for rec in confs:
            db_list = self.get_db_list(cr, user, [], rec.host, rec.port)
            if rec.name in db_list:
                try:
                    if not os.path.isdir(rec.bkp_dir):
                        os.makedirs(rec.bkp_dir)
                except:
                    raise
                #Create name for dumpfile.
                bkp_file = '%s_%s.dump' % (time.strftime('%d_%m_%Y_%H_%M_%S'),
                                           rec.name)
                file_path = os.path.join(rec.bkp_dir, bkp_file)
                uri = 'http://' + rec.host + ':' + rec.port
                conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
                bkp = ''
                try:
                    bkp = execute(conn, 'dump', tools.config['admin_passwd'],
                                  rec.name, 'zip')
                except:
                    _logger.debug(
                        "Couldn't backup database %s. Bad database administrator password for server running at http://%s:%s"
                        % (rec.name, rec.host, rec.port))
                    continue
                bkp = base64.decodestring(bkp)
                fp = open(file_path, 'wb')
                fp.write(bkp)
                fp.close()
            else:
                _logger.debug("database %s doesn't exist on http://%s:%s" %
                              (rec.name, rec.host, rec.port))

            #Check if user wants to write to SFTP or not.
            if rec.sftpwrite is True:
                try:
                    #Store all values in variables
                    dir = rec.bkp_dir
                    pathToWriteTo = rec.sftppath
                    ipHost = rec.sftpip
                    portHost = rec.sftpport
                    usernameLogin = rec.sftpusername
                    passwordLogin = rec.sftppassword
                    #Connect with external server over SFTP
                    srv = pysftp.Connection(host=ipHost,
                                            username=usernameLogin,
                                            password=passwordLogin,
                                            port=portHost)
                    #set keepalive to prevent socket closed / connection dropped error
                    srv._transport.set_keepalive(30)
                    #Move to the correct directory on external server. If the user made a typo in his path with multiple slashes (/odoo//backups/) it will be fixed by this regex.
                    pathToWriteTo = re.sub('([/]{2,5})+', '/', pathToWriteTo)
                    print(pathToWriteTo)
                    try:
                        srv.chdir(pathToWriteTo)
                    except IOError:
                        #Create directory and subdirs if they do not exist.
                        currentDir = ''
                        for dirElement in pathToWriteTo.split('/'):
                            currentDir += dirElement + '/'
                            try:
                                srv.chdir(currentDir)
                            except:
                                print(
                                    '(Part of the) path didn\'t exist. Creating it now at '
                                    + currentDir)
                                #Make directory and then navigate into it
                                srv.mkdir(currentDir, mode=777)
                                srv.chdir(currentDir)
                                pass
                    srv.chdir(pathToWriteTo)
                    #Loop over all files in the directory.
                    for f in os.listdir(dir):
                        fullpath = os.path.join(dir, f)
                        if os.path.isfile(fullpath):
                            print(fullpath)
                            srv.put(fullpath)

                    #Navigate in to the correct folder.
                    srv.chdir(pathToWriteTo)

                    #Loop over all files in the directory from the back-ups.
                    #We will check the creation date of every back-up.
                    for file in srv.listdir(pathToWriteTo):
                        #Get the full path
                        fullpath = os.path.join(pathToWriteTo, file)
                        #Get the timestamp from the file on the external server
                        timestamp = srv.stat(fullpath).st_atime
                        createtime = datetime.datetime.fromtimestamp(timestamp)
                        now = datetime.datetime.now()
                        delta = now - createtime
                        #If the file is older than the daystokeepsftp (the days to keep that the user filled in on the Odoo form it will be removed.
                        if delta.days >= rec.daystokeepsftp:
                            #Only delete files, no directories!
                            if srv.isfile(fullpath) and ".dump" in file:
                                print("Delete: " + file)
                                srv.unlink(file)
                    #Close the SFTP session.
                    srv.close()
                except Exception, e:
                    _logger.debug(
                        'Exception! We couldn\'t back up to the FTP server..')
                    #At this point the SFTP backup failed. We will now check if the user wants
                    #an e-mail notification about this.
                    if rec.sendmailsftpfail:
                        try:
                            ir_mail_server = self.pool.get('ir.mail_server')
                            message = "Dear,\n\nThe backup for the server " + rec.host + " (IP: " + rec.sftpip + ") failed.Please check the following details:\n\nIP address SFTP server: " + rec.sftpip + "\nUsername: "******"\nPassword: "******"\n\nError details: " + tools.ustr(
                                e) + "\n\nWith kind regards"
                            msg = ir_mail_server.build_email(
                                "auto_backup@" + rec.name + ".com",
                                [rec.emailtonotify], "Backup from " +
                                rec.host + "(" + rec.sftpip + ") failed",
                                message)
                            ir_mail_server.send_email(cr, user, msg)
                        except Exception:
                            pass
            """Remove all old files (on local server) in case this is configured..
            This is done after the SFTP writing to prevent unusual behaviour:
            If the user would set local back-ups to be kept 0 days and the SFTP
            to keep backups xx days there wouldn't be any new back-ups added to the
            SFTP.
            If we'd remove the dump files before they're writen to the SFTP there willbe nothing to write. Meaning that if an user doesn't want to keep back-ups locally and only wants them on the SFTP (NAS for example) there wouldn't be any writing to the remote server if this if statement was before the SFTP write method right above this comment.
            """
            if rec.autoremove is True:
                dir = rec.bkp_dir
                #Loop over all files in the directory.
                for f in os.listdir(dir):
                    fullpath = os.path.join(dir, f)
                    timestamp = os.stat(fullpath).st_ctime
                    createtime = datetime.datetime.fromtimestamp(timestamp)
                    now = datetime.datetime.now()
                    delta = now - createtime
                    if delta.days >= rec.daystokeep:
                        #Only delete files (which are .dump), no directories.
                        if os.path.isfile(fullpath) and ".dump" in f:
                            print("Delete: " + fullpath)
                            os.remove(fullpath)
Esempio n. 17
0
#
# Use this module to retrive the fields you need according to the type
# of the OpenOffice operation:
#  * Insert a Field
#  * Insert a RepeatIn
#

import xmlrpclib
import time

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')


def get(object, level=3, ending=[], ending_excl=[], recur=[], root=''):
    res = sock.execute('terp', 3, 'admin', 'account.invoice', 'fields_get')
    key = res.keys()
    key.sort()
    for k in key:
        if (not ending or res[k]['type'] in ending) and (
            (not ending_excl) or not (res[k]['type'] in ending_excl)):
            print root + '/' + k

        if res[k]['type'] in recur:
            print root + '/' + k
        if (res[k]['type'] in recur) and (level > 0):
            get(res[k]['relation'], level - 1, ending, ending_excl, recur,
                root + '/' + k)


print 'Field selection for a rields', '=' * 40
get('account.invoice',
Esempio n. 18
0
runNumber = args.runNumber
stream = args.stream
if args.tag != "":
    tag = args.tag
else:  # Try to retrieve the data project tag via atlasdqm
    if (not os.path.isfile("atlasdqmpass.txt")):
        print "To retrieve the data project tag, you need to generate an atlasdqm key and store it in this directory as atlasdqmpass.txt (yourname:key)"
        print "To generate a kay, go here : https://atlasdqm.cern.ch/dqauth/"
        print "You can also define by hand the data project tag wit hthe option -t"
        sys.exit()
    passfile = open("atlasdqmpass.txt")
    passwd = passfile.read().strip()
    passfile.close()
    passurl = 'https://%[email protected]' % passwd
    s = xmlrpclib.ServerProxy(passurl)
    run_spec = {
        'stream': 'physics_CosmicCalo',
        'proc_ver': 1,
        'source': 'tier0',
        'low_run': runNumber,
        'high_run': runNumber
    }
    run_info = s.get_run_information(run_spec)
    if '%d' % runNumber not in run_info.keys() or len(
            run_info['%d' % runNumber]) < 2:
        print "Unable to retrieve the data project tag via atlasdqm... Please double check your atlasdqmpass.txt or define it by hand with -t option"
        sys.exit()
    tag = run_info['%d' % runNumber][1]

amiTag = args.amiTag
Esempio n. 19
0
import xmlrpclib
import json
import time

start_time = time.time()

database = 'v10_pos_big_data'
login = '******'
password = '******'
url = 'http://localhost:8069'

common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(database, login, password, {})

models = xmlrpclib.ServerProxy(url + '/xmlrpc/object')

for i in range(0, 100000):
    try:
        vals = {
            'list_price': 10.0,
            'description': u'description',
            'display_name': 'Product - %s' % str(i),
            'name': 'Product Eg : %s' % str(i),
            'pos_categ_id': 2,
            'to_weight': u'True',
        }
        with open("img.png", "rb") as f:
            data = f.read()
            vals['image'] = data.encode("base64")
        models.execute_kw(database, uid, password, 'product.product', 'create', [vals])
        print 'created: %s' % i
Esempio n. 20
0
#!/usr/bin/python
#*- coding: UTF-8 -*-

import xmlrpclib
import datetime

proxy = xmlrpclib.ServerProxy("http://localhost:8000/")

today = proxy.today()
# convert the ISO8601 string to a datetime object
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
Esempio n. 21
0
def send(msg):
    if debug:
        print msg
        return
    xmlrpclib.ServerProxy(server).hub.deliver(msg)
Esempio n. 22
0
#port = '9069'
#dbname = 'metro_0926_2'
#username = '******'
#pwd = 'develop'

#host = '10.1.1.141'
#port = '80'
#dbname = 'metro_production'
#username = '******'
#pwd = 'erp123'

host = '10.1.1.141'
port = '80'
dbname = 'metro_test'
username = '******'
pwd = 'erp123-test'

sock_common = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/common' %
                                    (host, port))
uid = sock_common.login(dbname, username, pwd)
sock = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/object' % (host, port))
ids = sock.execute(dbname, uid, pwd, 'sale.product', 'search',
                   [('analytic_account_id', '=', False)])
for id in ids:
    ana_act_id = sock.execute(dbname, uid, pwd, 'sale.product',
                              'create_analytic_account', id)
    sock.execute(dbname, uid, pwd, 'sale.product', 'write', [id],
                 {'analytic_account_id': ana_act_id})
    print 'Updated MFG ID:%s' % id

print 'done...'
Esempio n. 23
0
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""
#end_pymotw_header

import xmlrpclib

server = xmlrpclib.ServerProxy('http://localhost:9000', allow_none=True)
print 'Allowed:', server.show_type(None)

server = xmlrpclib.ServerProxy('http://localhost:9000', allow_none=False)
try:
    server.show_type(None)
except TypeError as err:
    print 'ERROR:', err
Esempio n. 24
0
# -*- coding: utf-8 -*-

from odoo import models, fields, api, _, exceptions
from datetime import datetime
import xmlrpclib
import os

url = 'http://10.0.5.11:8095'
db = 'vvti_v_7'
username = '******'
password = '******'

sock_common = xmlrpclib.ServerProxy('{}/xmlrpc/common'.format(url))
uid = sock_common.login(db, username, password)

sock = xmlrpclib.ServerProxy('{}/xmlrpc/object'.format(url))

py_template_string = '''# -*- coding: utf-8 -*-

from odoo import models, fields, api, _, exceptions
from datetime import datetime


class {0}(models.Model):
    _name = '{1}'
    _description = '{2}'

{3}
        '''

view_template_string = '''
Esempio n. 25
0
    parser = argparse.ArgumentParser(description='Script for creating Payroll from csv file')
    parser.add_argument('-w', '--xlsfile', help='e.g -w xlsfile.csv', required=True)
    args = vars(parser.parse_args())
except ImportError:
    parser = None

WBFILE = args['xlsfile']
"""
try:
    db = 'SMARTACQUADB'
    username = '******'
    password = '******'
    port = '8081'
    host = 'localhost'
    url = 'http://%s:%s' % (host, port)
    models = xmlrpclib.ServerProxy('%s/xmlrpc/2/object' % (url))
    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    uid = common.authenticate(db, username, password, {})

    assert uid,'com.login failed'
    version = common.version()
    print "odoo version ",version['server_version']
    assert version['server_version'] == '12.0','Server not 12.0'
except Exception, e:
    raise


TODAY = datetime.now().strftime('%d.%m.%Y')
DATAFOLDER = 'data'

def create_vendor(pname, phone,email):
Esempio n. 26
0
# -*- encoding: utf-8 -*-
import xmlrpclib  #导入xmlrpc库,这个库是python的标准库。

username = '******'  #用户登录名
pwd = 'admin'  #用户的登录密码,测试时请换成自己的密码
dbname = 'odo'  #数据库帐套名,测试时请换成自己的帐套名

# 第一步,取得uid
sock_common = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)

#replace localhost with the address of the server
sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')

# 调用res.partner对象的create方法在数据库中插入一个业务伙伴
partner = {
    'name': '测试',  #字段
    'lang': 'zh_CN',
}
partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner)

# 删除一条或多条记录
deleteID = [94, 93]  #需要删除的ID,一个list
result = sock.execute(dbname, uid, pwd, 'res.partner', 'unlink', deleteID)

#更新一条或多条记录
updateID = [78, 79]
values = {'name': '更新'}
result1 = sock.execute(dbname, uid, pwd, 'res.partner', 'write', updateID,
                       values)
Esempio n. 27
0
def sendNZB(nzb):

    addToTop = False
    nzbgetXMLrpc = "%(username)s:%(password)s@%(host)s:%(port)s/xmlrpc"

    if lazylibrarian.NZBGET_HOST is None:
        logger.error(u"No NZBget host found in configuration. Please configure it.")
        return False

    if lazylibrarian.NZBGET_PORT is 0:
        logger.error(u"No NZBget port found in configuration. Please configure it.")
        return False

    if lazylibrarian.NZBGET_HOST.startswith('https://'):
        nzbgetXMLrpc = 'https://' + nzbgetXMLrpc
        lazylibrarian.NZBGET_HOST.replace('https://', '', 1)
    else:
        nzbgetXMLrpc = 'http://' + nzbgetXMLrpc
        lazylibrarian.NZBGET_HOST.replace('http://', '', 1)

    url = nzbgetXMLrpc % {"host": lazylibrarian.NZBGET_HOST, "username": lazylibrarian.NZBGET_USER,
                          "port": lazylibrarian.NZBGET_PORT, "password": lazylibrarian.NZBGET_PASS}
    
    nzbGetRPC = xmlrpclib.ServerProxy(url)
    try:
        if nzbGetRPC.writelog("INFO", "lazylibrarian connected to drop off %s any moment now." % (nzb.name + ".nzb")):
            logger.debug(u"Successfully connected to NZBget")
        else:
            logger.info(u"Successfully connected to NZBget, but unable to send %s" % (nzb.name + ".nzb"))

    except httplib.socket.error as e:
        logger.error(u"Please check your NZBget host and port (if it is running). \
            NZBget is not responding to this combination: %s" % e)
        return False

    except xmlrpclib.ProtocolError as e:
        if e.errmsg == "Unauthorized":
            logger.error(u"NZBget password is incorrect.")
        else:
            logger.error(u"Protocol Error: %s" % e.errmsg)
        return False

    nzbcontent64 = None
    if nzb.resultType == "nzbdata":
        data = nzb.extraInfo[0]
        nzbcontent64 = standard_b64encode(data)

    logger.info(u"Sending NZB to NZBget")
    logger.debug(u"URL: " + url)

    dupekey = ""
    dupescore = 0

    try:
        # Find out if nzbget supports priority (Version 9.0+), old versions
        # beginning with a 0.x will use the old command
        nzbget_version_str = nzbGetRPC.version()
        nzbget_version = int(nzbget_version_str[:nzbget_version_str.find(".")])
        logger.debug("NZB Version %s" % nzbget_version)
        # for some reason 14 seems to not work with >= 13 method? I get invalid param autoAdd
        # PAB think its fixed now, code had autoAdd param as "False", it's not a string, it's bool so False
        if nzbget_version == 0:  # or nzbget_version == 14:
            if nzbcontent64 is not None:
                    nzbget_result = nzbGetRPC.append(nzb.name + ".nzb",
                                                     lazylibrarian.NZBGET_CATEGORY, addToTop, nzbcontent64)
            else:
                # from lazylibrarian.common.providers.generic import GenericProvider
                # if nzb.resultType == "nzb":
                #     genProvider = GenericProvider("")
                #     data = genProvider.getURL(nzb.url)
                #     if (data is None):
                #         return False
                #     nzbcontent64 = standard_b64encode(data)
                # nzbget_result = nzbGetRPC.append(nzb.name + ".nzb", lazylibrarian.NZBGET_CATEGORY,
                #       addToTop, nzbcontent64)
                return False
        elif nzbget_version == 12:
            if nzbcontent64 is not None:
                nzbget_result = nzbGetRPC.append(nzb.name + ".nzb", lazylibrarian.NZBGET_CATEGORY,
                                                 lazylibrarian.NZBGET_PRIORITY, False,
                                                 nzbcontent64, False, dupekey, dupescore, "score")
            else:
                nzbget_result = nzbGetRPC.appendurl(nzb.name + ".nzb", lazylibrarian.NZBGET_CATEGORY,
                                                    lazylibrarian.NZBGET_PRIORITY, False, nzb.url, False,
                                                    dupekey, dupescore, "score")
        # v13+ has a new combined append method that accepts both (url and content)
        # also the return value has changed from boolean to integer
        # (Positive number representing NZBID of the queue item. 0 and negative numbers represent error codes.)
        elif nzbget_version >= 13:
            nzbget_result = True if nzbGetRPC.append(nzb.name + ".nzb", nzbcontent64 if nzbcontent64 is not None
                                                     else nzb.url, lazylibrarian.NZBGET_CATEGORY,
                                                     lazylibrarian.NZBGET_PRIORITY, False, False, dupekey,
                                                     dupescore, "score") > 0 else False
        else:
            if nzbcontent64 is not None:
                nzbget_result = nzbGetRPC.append(nzb.name + ".nzb", lazylibrarian.NZBGET_CATEGORY,
                                                 lazylibrarian.NZBGET_PRIORITY, False, nzbcontent64)
            else:
                nzbget_result = nzbGetRPC.appendurl(nzb.name + ".nzb", lazylibrarian.NZBGET_CATEGORY,
                                                    lazylibrarian.NZBGET_PRIORITY, False, nzb.url)

        if nzbget_result:
            logger.debug(u"NZB sent to NZBget successfully")
            return True
        else:
            logger.error(u"NZBget could not add %s to the queue" % (nzb.name + ".nzb"))
            return False
    except Exception as e:
        logger.error(u"Connect Error to NZBget: could not add %s to the queue: %s" % (nzb.name + ".nzb", e))
        return False
Esempio n. 28
0
    def transfer(self, cr, uid, order_id, context=None):
        _logger = logging.getLogger(__name__)
        def_id = self.search(cr, uid, [("in_use", '=', True)], context=None)
        if not def_id:
            return None

        record = self.browse(cr, uid, def_id, context=None)

        url = record.ro_url
        db = record.ro_db
        username = record.ro_user
        password = record.ro_pass

        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
        uidx = common.authenticate(db, username, password, {})

        models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

        order = self.pool.get('sale.order').browse(cr,
                                                   uidx,
                                                   order_id,
                                                   context=None)[0]
        _logger.info("++++++ %s" % order.name)
        par = models.execute_kw(
            db, uid, password, 'res.partner', 'read', [[190856]],
            {'fields': ['property_product_pricelist']})  #make user insertable

        par = par[0]
        pricelist = par['property_product_pricelist'][0] if par[
            'property_product_pricelist'] else 1
        vals = {
            'partner_id': 191286,
            'location_id': 1,
            'pricelist_id': pricelist
        }

        po = models.execute_kw(db, uidx, password, 'purchase.order', 'create',
                               [vals])

        for line in order.order_line:
            remote_product_id = models.execute_kw(
                db, uidx, password, 'product.product', 'search_read',
                [[['default_code', '=', line.product_id.default_code]]],
                {'fields': ['uom_id']})
            remote_uom = models.execute_kw(
                db, uidx, password, 'product.uom', 'search',
                [[['name', '=', remote_product_id[0]['uom_id'][1]]]])

            vals = {
                'product_id': remote_product_id[0]['id'],
                'name': line.name,
                'product_uom': remote_uom[0] if len(remote_uom) else 1,
                'product_qty': line.product_uom_qty,
                'date_planned': datetime.now().strftime('%d/%m/%Y'),
                'price_unit': line.price_unit,
                'order_id': po,
                'taxes_id': [[6, False, [x.id for x in line.tax_id]]]
            }
            models.execute_kw(db, uidx, password, 'purchase.order.line',
                              'create', [vals])

        order.remote_order_id = po
Esempio n. 29
0
#!/usr/bin/env python
# coding: utf-8
import xmlrpclib
import xlrd
import datetime

print "\nSTART time:", datetime.datetime.today()

url = 'http://localhost:8069'
dbname = 'tts_live_test'
username = '******'
pwd = 'AlphaAdmin2019'

sock_common = xmlrpclib.ServerProxy('%s/xmlrpc/common' % (url, ))
sock = xmlrpclib.ServerProxy('%s/xmlrpc/object' % (url, ))
uid = sock_common.login(dbname, username, pwd)

workbook = xlrd.open_workbook(
    '/Users/vieterp/code/vieterp/tools/tts/product_cost_update.xlsx')
worksheet = workbook.sheet_by_index(0)

num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = 0

while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)

    default_code = row[0].value.strip()
    cost = row[3].value or 0
Esempio n. 30
0
 def offloading(self, orig_file, width, height, br, path):
     proxy = xmlrpclib.ServerProxy("http://155.69.55.92:10002/")
     with open(orig_file, "rb") as handle:
         segment = xmlrpclib.Binary(handle.read())
     with open(path, "wb") as handle:
         handle.write(proxy.python_logo(segment, width, height, br).data)