I'm trying to display multiple images (pulled from datastore) in one page.
Doing this only displays 1 image...
class Stocks(db.Model):
ticker = db.StringProperty()
picture = db.BlobProperty(default=None)
What i use to serve:
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(stock.picture)
Is this the only way i can server the picture?
Can i do it in a way where i do multiple image response outs?
Something along the lines like this.
self.response.out.write('<img src=' + stock.picture + '>')
UPDATE: Thanks for the reply. Totally didn't know you could do something like that.
So i did this:
app = webapp2.WSGIApplication([('/dailystocks', frontend_dailyStocks),('/image/.*', ServeImage),('/mainPage', MainPage)], debug=True)
Then this:
class MainPage(webapp2.RequestHandler):
def get(self):
images = Stocks.all().fetch(100)
html = ['<img src="/image/%s" />' % img.key() for img in images]
self.response.out.write(html)
class ServeImage(webapp2.RequestHandler):
def get(self):
key = self.request.get('key')
image = Stocks.get(key)
if image:
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image.picture)
else:
self.abort(404)
The thing loaded but it showed a list of broken image links.
This is an example image link:
http://*****.appspot.com/image/ag9zfmpwZ2V0bGlzdGluZ3NyEwsSBlN0b2NrcxiAgICAwOGGCAw
For each picture you want to serve, you'll need a separate HTTP call. So you may write a handler to serve an image, much like you suggested, as follows:
class ServeImage(webapp2.RequestHandler):
def get(self):
key = self.request.get('key')
image = Stocks.get(key)
if image:
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image.picture)
else:
self.abort(404)
Then in your main handler, load the images and render the html, referencing the ServeImage handler in each img tag ...
class MainPage(webapp2.RequestHandler):
def get(self):
images = Stocks.all().fetch(100)
html = ['<img src="/image?key=%s" />' % img.key() for img in images]
self.response.out.write(html)
You'll need to route the url /image to your ServeImage handler.
Related
I am trying to use Luigi to build a small scraping pipeline and I'm using Pillow to save the images from the pages I scrape. However, I'm struggling with the output when I try to save each image in loop (e.g. I want to save img_1, img_2, img_3, etc. in the output folder). I tried to pass an "image_id" parameter within the output function but it doesn't work and I can't figure out how to accomplish this.
class DownloadImages(luigi.Task):
def requires(self):
pass # taking out dependencies for this example
def output(self, image_id):
return luigi.LocalTarget(f"img/img_{image_id}.jpeg")
def run(self):
resp = requests.get("https://my-site.com")
soup = BeautifulSoup(resp.content, "html.parser")
images_list = soup.select("img")
for image_id in range(len(images_list)):
image_url = images_list[image_id]["src"]
img = Image.open(requests.get(image_url, stream=True).raw)
img.save(self.output(image_id).path)
New answer since it's completely different:
python -m luigi --module scraper DownloadImages --local-scheduler
from PIL import Image
import requests
import luigi
class DownloadImages(luigi.Task):
save_path = f"img/*.jpg"
def output(self):
return luigi.LocalTarget(self.save_path)
def run(self):
img_ids = [1,2,3]
self.imgs = []
for img_id in img_ids:
img = Image.open(requests.get("https://i.kym-cdn.com/entries/icons/original/000/000/007/bd6.jpg", stream=True).raw)
img.save(self.save_path.replace("*", f"img_{img_id}"))
The Point of luigi is to have a workflow. It uses output to pass the location of your data between tasks. You cannot have additional arguments since you are not supposed to call that function (except to get the location where you want to save your output).
Disclaimer: I might have used it wrong too. Please go look at the Documentation
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!')
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
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
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