开发者

Can the Django dev server correctly serve SVG?

I am trying to serve a svg map using:

<ob开发者_JS百科ject data="map.svg" type="image/svg+xml" width="400" height="300">
    <embed src="map.svg" type="image/svg+xml" width="400" height="300" />
</object>

In Firefox this leads to a plugin prompt. If I rename map.svg to map.xml it shows the image correctly. I assume this is because the Django's dev server (specifically django.views.static.serve) is not serving the svg with the correct mime-type. Is this the problem, and if so, is there a patch?


I don't have Django available to test this at the moment but it looks like the static server uses the mimetypes library to determine the content type (specifically guess_type()).

With a little bit a Googling, I came across some code that you could probably throw in your settings.py to add support for the svg content type:

import mimetypes

mimetypes.add_type("image/svg+xml", ".svg", True)
mimetypes.add_type("image/svg+xml", ".svgz", True)

There's also this blog post specific to Pylons but it mentions a similar issue. He specifies that the MIME types are stored in "/etc/mime.types" and that SVG is missing because it's not an official MIME type. He may be right, since I can't find a MIME-type for SVG anywhere on the IANA.


If you're serving the SVG dynamically from a regular django view, you can specify the mimetype in the HTTPResponse object you return from that view. In this case, you'll want the mimetype in place for both dev and production use:

def myview(request):
    svg_data = generate_some_svg_data()
    return HttpResponse(svg_data, mimetype="image/svg+xml")


In my case the issuer was the deployment with nginx+gunicorn. My nginx docker image served the text/plain mimetype for .svg file. This extension of mime.types resolved the issue:

http {
    include mime.types;
    types {
        image/svg+xml svg;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜