Name xmlrpc is not defined - python

Im trying to extract data from odoo using xml-rpc api.
import xmlrpc.client
url = "https://xxxxxx.odoo.com/"
db = "xxxxxxx"
username = " "
password = ""
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
However it said that name 'xmlrpc' is not defined, it is very weird since xmlrpclib is part of the standard library in Python, i dont need to install it. Can you suggest solution for this? Thanks.

Related

Python construct a URL with username and password credentials

I'm trying to port some basic code from JavaScript to Python. In JavaScript the URL class makes this trivial:
const url = new URL('https://python.org');
url.username = 'foo';
url.password = 'bar';
console.log(url.href)
https://foo:bar#python.org/
How do I do this natively in Python? In other words, how can this be done using core libraries (without any third party libraries e.g. the requests module)?
Thanks in advance!
Try using f-strings like this:
url = f"https://{username}:{password}#python.org"
print(url)
For instance, I use this technique to configure my applications to be able to access Internet when I am behing a corporate proxy.

How to query the sys_user table using REST?

I am using v2.0.1 of servicenow from PyPi to interact with ServiceNow. I need to be able to look up a user in the sys_user table so I can find the sys_id assigned to them. If anyone has some sample code they can share it would be appreciated.
I have tried using the following with no success:
from servicenow import Connection
from servicenow import ServiceNow
conn = conn = Connection.Auth(username='abc', password='xyz', instance='demo')
user = ServiceNow.Base(conn)
user.__table__ = 'sys_user.do'
rec = user.fetch_all({'user_name': 'abc123'})
This fails with
AttributeError: 'Base' object has no attribute 'fetch_all'
I am not familiar with PyPi, but I will tell you you can make standard REST calls to the /api/now/table/sys_user?sysparm_query=user_nameSTARTSWITH
Also, make sure to review the notes regarding JSON, JSONv2, vs SOAP and use the right connection auth string

Get the name or ID of the current Google Compute Instance

I'm running a number of Google Compute Engine instances that run Python code, and I want to find the name or the ID of each instance from inside the instances.
One solution I've found is to get the internal IP of the instance using:
import socket
internal_ip = socket.gethostbyname(socket.gethostname())
Then I list all the instances:
from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
credentials = GoogleCredentials.get_application_default()
self.compute = build('compute', 'v1', credentials=credentials)
result = self.compute.instances().list(project=project, zone=zone).execute()
Then I iterate over all the instances to check if the internal IP matches the IP of an instance:
for instance in result["items"]:
if instance["networkInterfaces"][0]["networkIP"] == internal_ip:
internal_id = instance["id"]
This works but it's a bit complicated, is there a more direct way to achieve the same thing, e.g. using Google's Python Client Library or the gcloud command line tool?
Instance Name:
socket.gethostname() or platform.node() should return the name of the instance. You might have to do a bit of parsing depending on your OS.
This worked for me on Debian and Ubuntu systems:
import socket
gce_name = socket.gethostname()
However, on a CoreOS instance, the hostname command gave the name of the instance plus the zone information, so you would have to do some parsing.
Instance ID / Name / More (Recommended):
The better way to do this is to use the Metadata server. This is the easiest way to get instance information, and works with basically any programming language or straight CURL. Here is a Python example using Requests.
import requests
metadata_server = "http://metadata/computeMetadata/v1/instance/"
metadata_flavor = {'Metadata-Flavor' : 'Google'}
gce_id = requests.get(metadata_server + 'id', headers = metadata_flavor).text
gce_name = requests.get(metadata_server + 'hostname', headers = metadata_flavor).text
gce_machine_type = requests.get(metadata_server + 'machine-type', headers = metadata_flavor).text
Again, you might need to do some parsing here, but it is really straightforward!
References:
How can I use Python to get the system hostname?
To get your instance name, execute the following from your VM:
curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H Metadata-Flavor:Google
and to get your instance id:
curl http://metadata.google.internal/computeMetadata/v1/instance/id -H Metadata-Flavor:Google
Check out the documentations for other available parameters: https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata

getting started with davlib.py

I want to write a script to connect and access a webdav server. I found out that there is a
/usr/local/lib/python2.7/dist-packages/davlib.py
But how to use it? There is no tutorial, no documentation and nothing to google. Anybody able to write a small hello world for it?
the test webdav server is on localhost:80/webdav and there is a davtest.txt file with the word dav inside.
$ cd <path_to_webdav>
$ ls
davtest.txt
$ cat davtest.txt
dav
I can read python, so if I could just connect and read that there is a file called davtest.txt or maybe even it's content I think I could get started working with the source. Not knowing how webDAV works and not knowing davlib.py both together is quite tough, though.
With webdav-lib I could solve that problem:
url = "davs://localhost:80/webdav/davtest.txt"
r = ResourceStorer(url)
result = r.downloadContent().read()
To do a simple get request using davlib
import davlib
import base64
host = 'myhost'
protocol = 'myprotocol'
username = 'myusername'
password = 'mypassword'
url = '{}://{}/{}'.format(protocol, host, some_file_path)
d = davlib.DAV(protocol=myprotocol, host=myhost)
auth_token = base64.encodestring('%s:%s' %(username, password)).strip()
header = {"Authenication": "Basic %s' %auth_token}
d.get(url,header)
Basic authentication is usable only on https. For more (dry) details on webDAV, see the RFC.
The most mature webDAV client library I've found is python-webdav-library

how can i use sharepoint (via soap?) from python?

I want to use Sharepoint with python (C-Python)
Has anyone tried this before ?
I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated
user = r'SERVER\user'
password = "yourpassword"
url = "http://sharepointserver/_vti_bin/SiteData.asmx?WSDL"
ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)
To get the wsdl :
import sys
# we use suds -> https://fedorahosted.org/suds
from suds import WebFault
from suds.client import *
import urllib2
# my 2 url conf
# url_sharepoint,url_NTLM_authproxy
import myconfig as my
# build url
wsdl = '_vti_bin/SiteData.asmx?WSDL'
url = '/'.join([my.url_sharepoint,wsdl])
# we need a NTLM_auth_Proxy -> http://ntlmaps.sourceforge.net/
# follow instruction and get proxy running
proxy_handler = urllib2.ProxyHandler({'http': my.url_NTLM_authproxy })
opener = urllib2.build_opener(proxy_handler)
client = SoapClient(url, {'opener' : opener})
print client.wsdl
main (mean) problem:
the sharepoint-server uses a NTLM-Auth [ :-( ]
so i had to use the NTLM-Auth-Proxy
To Rob and Enzondio : THANKS for your hints !
SOAP with Python is pretty easy. Here's a tutorial from Dive Into Python.
SharePoint exposes several web services which you can use to query and update data.
I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.
This article should give you enough information to get started.
http://www.developer.com/tech/article.php/3104621

Categories