如果Content-Type是类似图像的东西,elif是text / html然后做其他事情。这该怎么做?

时间:2016-04-15 14:30:33

标签: python django

首先,我为标题道歉。我不知道如何解释这个,所以我写这样的标题。

我想查看Content-Type,如果是image /运行这些代码

from PIL import Image
import io, uuid, requests

class LinkCreateView(CreateView):
    model = Link
    form_class = LinkForm

    def form_valid(self, form):
        headers = {'content-type': 'image/'}
        r = requests.get(form.instance.url, headers=headers)
        i = Image.open(io.BytesIO(r.content)).convert('RGB')
        image_io = io.BytesIO()
        try:
            crop_image = ImageOps.fit(i, method=Image.ANTIALIAS, size=(65, 65), bleed=0.5, centering=(0.5, 0.5))
            hash = str(uuid.uuid1())
            name = "{}.jpeg".format(hash)
            crop_image.save(image_io, format="jpeg")
            form.instance.img.save(name, ContentFile(image_io.getvalue()))
        finally:
            image_io.close()

        f = form.save(commit=False)
        f.rank_score = 0.0
        f.submitter = self.request.user
        f.save()

        return super(CreateView, self).form_valid(form)

如果是text / html,则运行这些代码;

from PIL import Image
import io, uuid, requests, lxml.html

url = ("http://website.com")
page = requests.get(url)
hash = str(uuid.uuid1())
tree = lxml.html.fromstring(page.content)
og = tree.xpath('/html/head/meta[@property="og:image"][1]/@content')
r = requests.get(og[0])
i = Image.open(io.BytesIO(r.content)).convert('RGB')
crop_image = ImageOps.fit(i, method=Image.ANTIALIAS, size=(65,65), bleed=0.5, centering=(0.5, 0.5))
crop_image.save("{}.jpeg".format(hash))

我试过,除此之外的事情都行不通。我不知道如何将第二段代码实现到第一段。这两个代码本身都很完美。

我试过这些代码:

if page.headers['Content-Type'] == 'text/html:
    .....
elif page.headers['Content-Type'] == 'image/':
    ..... 

感谢LearnerEarner,我的问题解决了。工作代码如下

class LinkCreateView(CreateView):
    model = Link
    form_class = LinkForm

    def form_valid(self, form):
        r = requests.get(form.instance.url)
        image_io = io.BytesIO()
        hash = str(uuid.uuid1())
        try:
            if r.headers['Content-Type'].startswith("image/"):
                i = Image.open(io.BytesIO(r.content)).convert('RGB')
                crop_image = ImageOps.fit(i, method=Image.ANTIALIAS, size=(65, 65), bleed=0.5, centering=(0.5, 0.5))
                name = "{}.jpeg".format(hash)
                crop_image.save(image_io, format="jpeg")
                form.instance.img.save(name, ContentFile(image_io.getvalue()))
            elif r.headers['Content-Type'].startswith("text/html"):
                tree = lxml.html.fromstring(r.content)
                og = tree.xpath('/html/head/meta[@property="og:image"][1]/@content')
                r = requests.get(og[0])
                i = Image.open(io.BytesIO(r.content)).convert('RGB')
                crop_image = ImageOps.fit(i, method=Image.ANTIALIAS, size=(65, 65), bleed=0.5, centering=(0.5, 0.5))
                name = "{}.jpeg".format(hash)
                crop_image.save(image_io, format="jpeg")
                form.instance.img.save(name, ContentFile(image_io.getvalue()))
        finally:
            image_io.close()

        f = form.save(commit=False)
        f.rank_score = 0.0
        f.submitter = self.request.user
        f.save()

        return super(CreateView, self).form_valid(form)

1 个答案:

答案 0 :(得分:0)

  

我试过这些代码:

if page.headers['Content-Type'] == 'text/html:
    .....
elif page.headers['Content-Type'] == 'image/':
    .....

据我所知,没有通用的内容类型,例如' image /'(除非您在响应标头中明确发送此类Content-Type)。 MIME类型必须是特定的。

在其他条件下使用之前,打印并观察requests.get的响应标题,以查看确切的内容类型。

如果您期望的是HTML和图像,则无需具有图像的特定条件。你可以尝试这样的事情:

if page.headers['Content-Type'] == 'text/html':
    ....
else:
    try:
        #treat it as image and proceed
    except:
        #may be not an image

OR

你可以这样做:

if page.headers['Content-Type'] == 'text/html:
    .....
elif page.headers['Content-Type'].startswith("image/"):
    .....

请参阅此list for MIME Types