error while importing images to odoo 11 using python script - python-3.x

I am trying to import images to odoo 11 using a python script. Earlier I used to work on a laptop with windows 7 installed and this script was working fine. But now, I have upgraded my laptop to windows 10 and I tried to run this same script but I am facing few errors.
Here is my script,
import csv
from pprint import pprint
import xmlrpc.client as xmlrpclib
class OpenERPXMLRPC():
#def __init__(self, host="0.0.0.0", port="8088", db="demo",
# user="admin",
# password="admin"):
def __init__(self, host="205.147.98.219", port="", db="BUILDSTATION_ROMFORD",
user="tina.santhosh#gmail.com",
password="buildstation1234*"):
common_url = "http://%s:%s/xmlrpc/common" % (host, port)
object_url = "http://%s:%s/xmlrpc/object" % (host, port)
com_sock = xmlrpclib.ServerProxy(common_url)
uid = com_sock.login(db, user, password)
if uid:
self.uid = uid
self.password = password
self.db = db
else:
print("Error in Authentication")
self.sock = xmlrpclib.ServerProxy(object_url)
def execute(self, model, method, *args):
res = self.sock.execute(self.db, self.uid, self.password, model,
method, *args)
return res
oe = OpenERPXMLRPC(db="BUILDSTATION_ROMFORD")
application = csv.reader(open('C:\\Users\\Asus\\Desktop\\test1.csv'))
for rec in application:
fields = rec
break
all_datas = []
count = 1
for rec in application:
all_datas.append(rec)
count = 0
all_error = []
for rec in all_datas:
count += 1
print(rec)
product_id = oe.execute(
'product.template',
'search',
[('name','=', rec[0])])
print("product_name--", product_id)
with open(rec[1], 'rb') as image:
image_base64 = image.read().encode("base64")
vals = {
'name': rec[0],
'image_medium': image_base64
}
oe.execute(
'product.template',
'write',
product_id,
vals)
I have created a separate file called test1.csv where I have uploaded only the product name and image location.
Here is the error that I am getting,
C:\Users\Asus>python c:\users\asus\desktop\final_import.py
['Airbrick Black', 'E:\\compressed images for odoo\\building materials\\airblocks\\ti0014.jpg']
product_name-- [4071]
Traceback (most recent call last):
File "c:\users\asus\desktop\final_import.py", line 55, in <module>
image_base64 = image.read().encode("base64")
AttributeError: 'bytes' object has no attribute 'encode'
any help here would be much appreciated.
Thanks,
Tina

Related

how to copy a vmware template to a given vcenter using pyVmomi module

I am familiar with cloning a VM from template and copying the template within the same vcenter, but when i try to copy it to a specified vcenter i am unable to achieve this.. I am not sure whether this is possible or not using pyVmomi module
I am new to pyVmomi module, Below is my code, any help or suggestions would be greatly appreciated.
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
import ssl,time,argparse,sys
def get_obj(content, vimtype, name):
obj = None
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
for c in container.view:
if c.name == name:
obj = c
break
return obj
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source',dest='source', help="source vcenter of the template")
parser.add_argument('-t', '--target',dest='target',default=False, help="target vcenter to which the template should be copied")
parser.add_argument('-tmp', '--template',dest='template',default=False, help="the template passed by the user")
args = parser.parse_args()
source = args.source
target = args.target
template = args.template
if source == None or target == None or template == None:
print("please provide the source/target/template, Exiting..")
sys.exit(1)
# Connecting to source vcenter
username='username'
password='password'
si = None
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_NONE
si = SmartConnect(host=source,user=username,pwd=password,sslContext=context)
content = si.content
#get template object
template_vm = get_obj(content, [vim.VirtualMachine], template)
print(template_vm)
# Connecting to target vcenter
# Disconnect(si)
si2 = SmartConnect(host=target,user=username,pwd=password,sslContext=context)
content2 = si2.content
datacenter = get_obj(content2, [vim.Datacenter], 'mydatacenter')
destfolder = datacenter.vmFolder
datastore = get_obj(content2, [vim.Datastore], 'mydatastore')
# Relocation spec
relospec = vim.vm.RelocateSpec()
relospec.datastore = datastore
clonespec = vim.vm.CloneSpec()
clonespec.location = relospec
clonespec.template = True
task = template_vm.Clone(folder=destfolder, name='template_new', spec=clonespec)
if __name__== "__main__":
main()
When i switch connection to a target vcenter i get the below error
Traceback (most recent call last):
File "clone_template2.py", line 74, in <module>
main()
File "clone_template2.py", line 70, in main
task = template_vm.Clone(folder=destfolder, name='template_new', spec=clonespec)
File "/home/akshay/.local/lib/python3.8/site-packages/pyVmomi/VmomiSupport.py", line 706, in <lambda>
self.f(*(self.args + (obj,) + args), **kwargs)
File "/home/akshay/.local/lib/python3.8/site-packages/pyVmomi/VmomiSupport.py", line 512, in _InvokeMethod
return self._stub.InvokeMethod(self, info, args)
File "/home/akshay/.local/lib/python3.8/site-packages/pyVmomi/SoapAdapter.py", line 1397, in InvokeMethod
raise obj # pylint: disable-msg=E0702
pyVmomi.VmomiSupport.ManagedObjectNotFound: (vmodl.fault.ManagedObjectNotFound) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = "The object 'vim.Datastore:datastore-360' has already been deleted or has not been completely created",
faultCause = <unset>,
faultMessage = (vmodl.LocalizableMessage) [],
obj = 'vim.Datastore:datastore-360'
}

Python Pickle Problem - Output not matching with Hackerrank

I’m trying to solve the below question on Hackerrank.
It is working on Pycharm IDE but on Hackerrank the output is not matching with the expected output given. Below is the Code I used
import os
import builtins
import pickle
import sys
sys.tracebacklimit = 0
import traceback
import io
from logging import Logger
safe_builtins = {
'range',
'complex',
'set',
'frozenset'
}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
# Forbid everything else.
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
(module, name))
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
def func1(a):
try:
x = restricted_loads(pickle.dumps(a))
return a
except pickle.UnpicklingError:
s = traceback.format_exc()
return s
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0, 8, 3)))
return s[x]
except pickle.UnpicklingError:
s = traceback.format_exc()
return s
if __name__ == "__main__":
a = range(int(input()))
b = func1(a)
print(b)
y = tuple(input())
z = func2(y)
print(z)
Expected Output:
range(0, 50):
Traceback (most recent call last):
_pickle.UnpicklingError: global 'builtins.slice' is forbidden
Actual Output:
range(0, 50):
_pickle.UnpicklingError: global 'builtins.slice' is forbidden
Question: Why does the output not match in hackerrank when the code seems to be correct?
This is an acceptable answer for Hackerrank. I included sys.stdout.write("Traceback (most recent call last):\n") since we declared the traceback=0 initially and pickle.UnpicklingError class doesn't have a traceback message. Try the below code for Hacker rank.
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0, 8, 3)))
return s[x]
except pickle.UnpicklingError as e :
sys.stdout.write("Traceback (most recent call last):\n")
s = traceback.format_exc()
return s
PS: This is just an acceptable answer for Hackerrank. I just made simple modifications according to the output needs. This might not be a good practice everywhere. And I dont have full knowledge of it either.
import os
import builtins
import pickle
import sys
sys.tracebacklimit=0
import traceback
import io
from logging import Logger
safe_builtins = {
'range',
'complex',
'set',
'frozenset'
}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
# Forbid everything else.
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
(module, name))
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
def func1(a):
try:
x = restricted_loads(pickle.dumps(a))
return a
except pickle.UnpicklingError:
s = traceback.format_exc()
return s
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0, 8, 3)))
return s[x]
except pickle.UnpicklingError as e :
sys.stdout.write("Traceback (most recent call last):\n")
s = traceback.format_exc()
return s
if __name__ == "__main__":
a = range(int(input()))
b = func1(a)
print(b)
y = tuple(input())
z = func2(y)
print(z)

Reddit and Twitter bot in Python using PRAW

I am a beginner in Python, and trying out making a bot which automatically Tweets anything which is posted on a Subreddit that I have made.
I took help from some of the tutorials online which has the following code
import praw
import json
import requests
import tweepy
import time
access_token = '************************************'
access_token_secret = '************************************'
consumer_key = '************************************'
consumer_secret = '************************************'
def strip_title(title):
if len(title) == 94:
return title
else:
return title[:93] + "..."
def tweet_creator(subreddit_info):
post_dict = {}
post_ids = []
print("[bot] Getting posts from Reddit")
for submission in subreddit_info.get_hot(limit=20):
post_dict[strip_title(submission.title)] = submission.url
post_ids.append(submission.id)
print("[bot] Generating short link using goo.gl")
mini_post_dict = {}
for post in post_dict:
post_title = post
post_link = post_dict[post]
short_link = shorten(post_link)
mini_post_dict[post_title] = short_link
return mini_post_dict, post_ids
def setup_connection_reddit(subreddit):
print("[bot] setting up connection with Reddit")
r = praw.Reddit(' %s' %(subreddit))
subreddit = r.get_subreddit(subreddit)
return subreddit
def shorten(url):
headers = {'content-type': 'application/json'}
payload = {"longUrl": url}
url = "https://www.googleapis.com/urlshortener/v1/url"
r = requests.post(url, data=json.dumps(payload), headers=headers)
link = json.loads(r.text)['id']
return link
def duplicate_check(id):
found = 0
with open('posted_posts.txt', 'r') as file:
for line in file:
if id in line:
found = 1
return found
def add_id_to_file(id):
with open('posted_posts.txt', 'a') as file:
file.write(str(id) + "\n")
def main():
subreddit = setup_connection_reddit('*Name of the subreddit*')
post_dict, post_ids = tweet_creator(subreddit)
tweeter(post_dict, post_ids)
def tweeter(post_dict, post_ids):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
for post, post_id in zip(post_dict, post_ids):
found = duplicate_check(post_id)
if found == 0:
print("[bot] Posting this link on twitter")
print(post + " " + post_dict[post] + " #Python #reddit #bot")
api.update_status(post+" "+post_dict[post]+" #Python #reddit #bot")
add_id_to_file(post_id)
time.sleep(30)
else:
print("[bot] Already posted")
if __name__ == '__main__':
main()
The code seems fine in PyCharm, however I am getting the following error when I try to run it directly from the folder via Terminal using the rolling code, reddit_bot2.py is my file name:
python3 reddit_bot2.py
When I try to run the code I am getting the following error:
mahesh#Maheshs-MacBook-Air Atoms % python3 reddit_bot2.py
[bot] setting up connection with Reddit
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/configparser.py", line 846, in items
d.update(self._sections[section])
KeyError: '**Name of the subreddit to fetch posts from**'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mahesh/Python_Bot/Atoms/reddit_bot2.py", line 82, in <module>
main()
File "/Users/mahesh/Python_Bot/Atoms/reddit_bot2.py", line 62, in main
subreddit = setup_connection_reddit('Bot167')
File "/Users/mahesh/Python_Bot/Atoms/reddit_bot2.py", line 36, in setup_connection_reddit
r = praw.Reddit(' %s' %(subreddit))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/praw/reddit.py", line 227, in __init__
self.config = Config(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/praw/config.py", line 85, in __init__
self.custom = dict(Config.CONFIG.items(site_name), **settings)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/configparser.py", line 849, in items
raise NoSectionError(section)
configparser.NoSectionError: No section: ' Bot167'
You provided the name of a praw.ini configuration which does not exist.
For help with creating a Reddit instance, visit
https://praw.readthedocs.io/en/latest/code_overview/reddit_instance.html
For help on configuring PRAW, visit
https://praw.readthedocs.io/en/latest/getting_started/configuration.html
Any help in this regards would be highly appreciated.
Thanks :)

Getting NameError while importing a module

import requests
import json
token= "12882xxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
class T_bot:
def __init__(self):
self.base= "https://api.telegram.org/bot{}/".format(token)
self.sendurl= "https://api.telegram.org/bot{}/sendMessage".format(token)
#self.data= {'chat_id':1067109380, 'text': 'Hi I hope you are doing fine' }
def gett(self, offset=None):
url= self.base+"getUpdates?timeout=100"
if offset:
url = url+"&offset={}".format(offset+1)
a= requests.get(url)
return a.json()
def send(self, msg, chat_id):
url= self.base+"sendMessage?chat_id={}&text={}".format(chat_id,msg)
if msg is not None:
requests.get(url)
when I'm importing the above code (bot.py)as:
from bot import T_bot
update_id= None
def make_reply(msg):
reply= 'okay'
return reply
update_id= None
while True:
updates= T_bot.gett(self, offset= update_id)
updates= updates["result"]
if updates:
for item in updates:
update_id= item['update_id']
try:
message= item['message']['text']
except:
message= None
fromm= item['message']['from']['id']
reply= make_reply(message)
T_bot.send(reply, fromm)
it is throwing a NameError when I'm running the main file above:
Traceback (most recent call last):
File "C:\Users\shivam\Desktop\pypy\server.py", line 13, in <module>
updates= T_bot.gett(self, offset= update_id)
NameError: name 'self' is not defined
I understand that I have to instantiate class first but how can I do it when I'm importing another module. somebody, please explain it!
You will have to instantiate the class first.
Ie.
from bot import T_bot
update_id = None
def make_reply(msg):
reply = 'okay'
return reply
update_id = None
instantiated_class = T_bot()
while True:
updates = instantiated_class.gett(offset=update_id)
updates = updates["result"]
if updates:
for item in updates:
update_id = item['update_id']
try:
message = item['message']['text']
except:
message = None
fromm = item['message']['from']['id']
reply = make_reply(message)
T_bot.send(reply, fromm)

Python OS polling select

I am following the David Beazley Python Concurrency From the Ground Up: LIVE! - PyCon 2015 talk where I aim to understand basics of Python concurrency.
I would like to know why Python select is failing which is used for polling the operating system (OS) and check if there is some task that needs to be done.
from socket import *
from select import select
from collections import deque
tasks = deque()
recv_wait = {}
send_wait = {}
def fib(n):
if n <= 2:
return 1
else:
return fib(n-1)+fib(n-2)
def run():
while any([tasks, recv_wait, send_wait]):
while not tasks:
can_recv, can_send, _ = select(recv_wait, send_wait, [])
for s in can_recv:
tasks.append(recv_wait.pop(s))
for s in can_send:
tasks.append(send_wait.pop(s))
task = tasks.popleft()
try:
why, what = next(task)
if why == 'recv':
recv_wait[what] = task
elif why == 'send':
send_wait[what] = task
else:
raise RuntimeError("Arg!!")
except StopIteration:
print("task done")
def fib_server(address):
sock = socket(AF_INET, SOCK_STREAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(5)
while True:
yield 'recv', sock
client, addr = sock.accept()
print("Connection", addr)
tasks.append(fib_handler(client))
def fib_handler(client):
while True:
yield 'recv', client
req = client.recv(100)
if not req:
break
n = int(req)
result = fib(n)
result = fib(n)
resp = str(result).encode('ascii') + b'\n'
yield 'send',resp
client.send(resp)
print("Closed")
tasks.append(fib_server(('', 25000)))
run()
# Separate terminal window
nc localhost 25000
12
# Running Python server
➜ python3 -i aserver.py
Connection ('127.0.0.1', 61098)
Traceback (most recent call last):
File "aserver.py", line 63, in <module>
run()
File "aserver.py", line 20, in run
can_recv, can_send, _ = select(recv_wait, send_wait,[])
TypeError: argument must be an int, or have a fileno() method.
def fib_handler(client):
while True:
yield 'recv', client
req = client.recv(100)
if not req:
break
n = int(req)
result = fib(n)
result = fib(n) # duplicate
resp = str(result).encode('ascii')+ b'\n'
yield 'send',resp # should be yielding fd (client)
client.send(resp)
print("Closed")

Resources