Odoo8. Upload product image programmatically - python

I get an image from url and try to upload it to Odoo (product.template, image column). I tried many methods to do that but none of them helped me. Could you give me the right way to upload image of product to Odoo without using csv import.

This worked for me :
import urllib2
import base64
image = urllib2.urlopen('http://ddd.com/somepics.jpg').read()
image_base64 = base64.encodestring(image)
product.image_medium = image_base64 //(new api v9)
#in old api maybe something like
#prod_obj.write(prod_id, {'image_medium': image_base64})

you may need something like this
using a psycopg2 library
try:
logo = urllib2.urlopen(logo_url).read()
except:
print 'waitting 60s'
time.sleep(60)
logo = urllib2.urlopen(logo_url).read()
res_data={'image':psycopg2.Binary(logo)}
...

If you have image URL and need to set in product then you can do as following and call this method when install/upgrade your custom module.
import requests
import base64
#api.multi
def get_image(self):
for product in self:
img = False
if image.url:
response = requests.get(image.url)
if response.ok and response.content :
img = base64.b64encode(response.content)
else :
img = False
product.image = img

Related

Downloading A Picture of an individual Instagram post with with Instaloader and Python

Using Python and the Instaloader package I am able to to download A profile Picture via this code
import instaloader
dp = instaloader.Instaloader()
dp.download_profile(profile_name, profile_pic_only = True)
All I have to do is provide the profile name.
What I also want to archive is, I want to download the picture of an individual post, such as: https://www.instagram.com/p/CgbAU5GD6MU/
Can this be done with Python instaloader?
Thanks!
Sure! Get the urls you want and easily use them
import instaloader
L = instaloader.Instaloader()
post_url = 'https://www.instagram.com/p/CgbAU5GD6MU/'
post = instaloader.Post.from_shortcode(L.context, post_url.split('p/')[1].strip('/ '))
photo_url = post.url # this will be post's thumbnail (or first slide)
video_url = post.video_url # if post.is_video is True then it will be url of video file

How can I get url of images from browser in django view

What should I do to allow django to read the image url from browser?
I'm learning to do a django app for getting dominant colors from images in grasshopper, so that the results could appear in rhino. which need to get images from browser. Images were downloaded in my PC could work , but not images from browser. Then I wonder if there is any python library could help with this problem?
jsob = {"clusters": 5,"path": 0}
if request.method == "POST":
try:
data = request.POST["data"]
print(data)
received = json.loads(str(data))
jsob.update(received)
path = jsob.get("path")
clusters = int(jsob.get("clusters"))
dc = DominantColors(path, clusters)
colors = dc.dominantColors().tolist()
print(colors)
print(type(colors))
results = {"colors":colors}
return JsonResponse(results)
except Exception as e:
PASS
import requests instead of json and requests.get method take url of browser url.
import requests
requests.get('your urls goes here!')

In python, how do I get urllib to recognize multiple lines in a string as separate URLs?

I'm very new to code so forgive any errors I make in explanation! I'm trying to write code on python that uses Praw to access the /r/pics subreddit, scrape the source urls and display them with urllib, cv2 and numpy.
Currently my code looks like this:
import praw
import numpy as np
import urllib
import cv2
# urllib set-up
def reddit_scrape(url):
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
# reddit set-up
reddit = praw.Reddit(client_id = 'id',
client_secret = 'secret',
user_agent = 'agent')
subreddit = reddit.subreddit('pics')
hot_pics = subreddit.hot(limit=10)
for submission in hot_pics:
if not submission.stickied:
print(submission.url)
# print images
urls = [submission.url]
for url in urls:
image = reddit_scrape(url)
cv2.imshow('image', image)
cv2.waitKey(0)
My problem when I run this is that although the print(submission.url) line prints a full list of the top 10 posts, only the last url on the list is actually opened and displayed.
My guess is that the error lies somewhere in my definition of
urls = [submission.url]
But I can't define 'urls' to be a static list of urls, because the hot list changes over time.
What am I doing wrong? is there even a right way to do this? Any help would be greatly appreciated.
submission is whatever the last submission was at the end of your for loop. Instead of constructing urls outside the loop, so when you say urls = [submission.url] you're only getting the last url. Instead you should create a list and append them:
urls = []
for submission in hot_pics:
if not submission.stickied:
urls.append(submission.url)
Or even the more Pythonic:
urls = [submission.url for submission in hot_pics if not submission.stickied]
Then the for url in urls will loop through all the appended urls.

How to retrieve an image from redis in python flask

I am trying to store an image in the redis and retrieve it and send it to an HTML template. I am able to cache the image but I dunno how to retrieve the image back and send it to the HTML template. This is the part of my code which does caching and retrieving.
from urllib2 import Request, urlopen
import json
import redis
import urlparse
import os
from StringIO import StringIO
import requests
from PIL import Image
from flask import send_file
REDIS_URL = urlparse.urlparse(os.environ.get('REDISCLOUD_URL', 'redis://:#localhost:6379/'))
r = redis.StrictRedis(
host=REDIS_URL.hostname, port=REDIS_URL.port,
password=REDIS_URL.password)
class MovieInfo(object):
def __init__(self, movie):
self.movie_name = movie.replace(" ", "+")
def get_movie_info(self):
url = 'http://www.omdbapi.com/?t=' + self.movie_name + '&y=&plot=short&r=json'
result = Request(url)
response = urlopen(result)
infoFromJson = json.loads(response.read())
self._cache_image(infoFromJson)
return infoFromJson
def _cache_image(self, infoFromJson):
key = "{}".format(infoFromJson['Title'])
# Open redis.
cached = r.get(key)
if not cached:
response = requests.get(infoFromJson['Poster'])
image = Image.open(StringIO(response.content))
r.setex(key, (60*60*5), image)
return True
def get_image(self, key):
cached = r.get(key)
if cached:
image = StringIO(cached)
image.seek(0)
return send_file(image, mimetype='image/jpg')
if __name__ == '__main__':
M = MovieInfo("Furious 7")
M.get_movie_info()
M.get_image("Furious 7")
Any help on the retrieving part would be helpful. Also whats the best way to send the image file from a cache to a HTML template in Flask.
What you saved in Redis is a string,
Something likes:'<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=300x475 at 0x4874090>'.
response.content is rawData . use Image.frombytes() to get Image object.
Check here : Doc
You can't create nested structures in Redis, meaning you can't (for
example) store a native redis list inside a native redis hash-map.
If you really need nested structures, you might want to just store a
JSON-blob (or something similar) instead. Another option is to store
an "id"/key to a different redis object as the value of the map key,
but that requires multiple calls to the server to get the full object.
Try this:
response = requests.get(infoFromJson['Poster'])
# Create a string buffer then set it raw data in redis.
output = StringIO(response.content)
r.setex(key, (60*60*5), output.getvalue())
output.close()
see: how-to-store-a-complex-object-in-redis-using-redis-py

Use cv.CaptureFromCAM in Django

I use cv.CaptureFromCAM in a Django app, but my script block a this command.Without Django, it works and I can see my webcam turns on.
Here's my script :
import cv, Image
def takePhoto():
"""Return a PIL img"""
print "Taking photo"
cv_img = cv.QueryFrame( cv.CaptureFromCAM(0) )
pil_img = Image.fromstring("L", cv.GetSize(cv_img), cv_img.tostring())
return pil_img
If someone know why I can't use a method like cv.CaptureFromCAM in Django's scripts ?
PS : I already tried to decompose in several lines...
Resolved :
I put cv.CaptureFromCAM in a var settings.py for launch it at website start up.
I access to that var for take a photo, example :
In settings.py:
CAM = cv.CaptureFromCAM(0)
In views.py:
from django.http import HttpResponse
import cv, Image
def instantPhoto(request) :
cv_img = cv.QueryFrame( CAM[0] )
pil_img = Image.fromstring("RGB", cv.GetSize(cv_img), cv_img.tostring())
response = HttpResponse(mimetype="image/png")
pil_img.save(response, "PNG")
return response

Categories

Resources