skip to Main Content

I’m getting the above TypeError from a healthcheck route on Django 3.1.2 on python 3.6.

The full error logged is:

ERROR 2020-11-02 18:32:32,046 /home/centos/venv/lib/python3.6/site-packages/django/utils/log.py log_response Internal Server Error: /healthcheck/
Traceback (most recent call last):
  File "/home/centos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/centos/venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 116, in __call__
    response = self.process_response(request, response)
  File "/home/centos/venv/lib/python3.6/site-packages/django/middleware/common.py", line 113, in process_response
    response['Content-Length'] = str(len(response.content))
  File "/home/centos/venv/lib/python3.6/site-packages/django/http/response.py", line 315, in content
    return b''.join(self._container)
TypeError: sequence item 0: expected a bytes-like object, str found

That error is raised every time the route is requested. The full view definition is:

def healthcheck_view(request):
    response = HttpResponse("OK", content_type="text/plain")
    return response

What on earth have I done??

2

Answers


  1. Chosen as BEST ANSWER

    Well, I eventually "resolved" this by nuking the whole root dir and reinstalling, after which I couldn't reproduce the error. I'm still unable to explain what the cause was, but I suspect it's something that (a) I did wrong, and (b) is immediately obvious after the fact. Thanks for the help anyway.


  2. Upgrade sentry_sdk:

    # version 0.19.1 sentry_sdk.integrations.django.middleware:
                    # Necessary for Django 3.1
                    sentry_wrapped_method.__self__ = old_method.__self__  # type: ignore
    

    Edit

    To trigger this exact exception do this:

    def health_check_view(request):
        response = HttpResponse("OK", content_type="text/plain")
        response._container = ["OK"]
        return response
    

    Are you sure you’re running Django 3.1?

    Looks like the else clause is missing in your HttpResponse.content:

            if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):
                content = b''.join(self.make_bytes(chunk) for chunk in value)
                if hasattr(value, 'close'):
                    try:
                        value.close()
                    except Exception:
                        pass
            else:
                content = self.make_bytes(value)
    

    Should be fixable by doing HttpResponse(b"OK", content_type="text/plain"), but if you’re convinced you’re running 3.1, I’d dig deeper.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search