1

I have this code,

import json
from goose import Goose

def extract(url):
    g = Goose()
    article = g.extract(url=url)
    if article.top_image is None:
        return "none" 
    else:
        if article.top_image.src is None:
          return "none"
        else:
            resposne = {'image':article.top_image.src}
            return article.top_image.src

here instead of "none" I want to return image file. In order to upload image file, do I need to save image in my static file and return that as an Image?I've been doing returning image from static file with html whole time but I'm not sure how to do that with python, or is there other way?

mike braa
  • 647
  • 1
  • 12
  • 33
  • Not sure why you'd want to do this. You have an image URL; you should simply include that image in your URL so that the browser can download it directly from that address. – Daniel Roseman Jan 23 '16 at 11:13
  • @DanielRoseman yes but for some websites, the image url isn't working. for some reason when i type url for youtube it won't work(show broken image)....not sure why so I'm thinking to put default image if it won't work – mike braa Jan 23 '16 at 12:17
  • @DanielRoseman, and for some url the image is just blank white which I don't understand why,,,,do you know why? – mike braa Jan 23 '16 at 12:25

1 Answers1

2

You have the URL of the image resource in article.top_image.src so it should just be a matter of downloading the image and returning it. You can use requests module for the downloading part:

import requests

def extract(url):
    article = Goose().extract(url)
    if article.top_image is None or article.top_image.src is None
        return "none"

    r = requests.get(article.top_image.src)
    return r.content

This will return the actual image data from the function.

Possibly you want to return that image as a HTTP response, in which case you can return this from your view function:

return HttpResponse(extract(url), content_type="image/jpeg")
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • this code is basically same as the one I wrote, except simpler. What I'm asking is how do I insert a picture instead of "none" – mike braa Jan 24 '16 at 03:46
  • Basically the same... except that it actually retrieves the image data and returns it from the function as requested in your question. I don't understand what `insert` means. Insert into what? Into HTML rendered from a Django template? Are you hoping to embed the actual image data into the HTML, or simply add an `` tag that refers to the image file? – mhawke Jan 24 '16 at 06:54
  • I'm sorry, I wasn't being clear. I made a new post with more detail. http://stackoverflow.com/questions/34972110/how-to-return-image-in-python-file?noredirect=1#comment57675354_34972110 I'm hoping to return static image there so I can use post.image in html. I can see I wasn't clear here, totally my fault. If you can see the new post I've made, that provided more detail – mike braa Jan 24 '16 at 08:30