Django development server and MIME types

后端 未结 3 1996
半阙折子戏
半阙折子戏 2021-01-11 12:23

Is there anyway of setting MIME types in the django development server? Specifically, I would love to remove this message from the warnings in Chrome dev tools.



        
相关标签:
3条回答
  • 2021-01-11 12:50

    Turns out it was as simple as adding

    if DEBUG:
        import mimetypes
        mimetypes.add_type("image/png", ".png", True)
    

    to settings.py

    0 讨论(0)
  • 2021-01-11 12:55

    Year 2020 ANSWER:

    if you want any mime content type to auto detect by browser this is the solution.

    after many painful failed static attempts this is the dynamic solution.

    def fetch(request):
        import mimetypes
        clientRequestUrl=os.getcwd()+'/servlet'+request.path
        try: return HttpResponse(fread(clientRequestUrl), content_type=mimetypes.guess_type(request.path)[0])
        except Exception as e: return HttpResponse(str(e)+'===> Error Thrown <br>')
    
    • here fread() reads file directly in try except block its just an I/O wrapper
    • content_type=mimetypes.guess_type(request.path)[0] does the MIME detection magic [0] ie first element is required because it returns a tuple first being the mime type and second being encoding.
    • request.path is passed in above line because it guesses MIME based on file path. for example text/css for file named stylsheet.css if client(browser) request it.
    • clientRequestUrl = exact url the client is trying to request to server.
    0 讨论(0)
  • 2021-01-11 13:00

    The Django development server uses the mimetypes module to guess the appropriate MIME type for any given file, and under the hood that module uses different configurations depending on your OS.

    On Windows in particular it loads content types from HKEY_CLASSES_ROOT in the registry (for instance the key HKEY_CLASSES_ROOT\.js\Content Type for .js files) and it seems this configuration can often be set in ways you wouldn't expect (such as by opening a javascript file in a text editor)- it's not even Python or Django specific, since Go also uses the registry and is affected the same way.

    Modifying the registry key for the affected file extensions should fix this issue without requiring any Django settings changes (however it is a system-wide configuration change that may not be desirable):

    Windows Registry Editor Version 5.00
    
    ; Fixing the question's issue with PNG
    [HKEY_CLASSES_ROOT\.png]
    "Content Type"="image/png"
    
    ; Fixing a common problem with Javascript files
    [HKEY_CLASSES_ROOT\.js]
    "Content Type"="text/javascript"
    

    On other operating systems MIME mappings are configured in a file that most users will never modify, so this tends not to be a problem. If needed however, mimetypes.knownfiles is a list of paths expected to contain MIME type mappings which could be edited as needed.

    0 讨论(0)
提交回复
热议问题