Flask: AttributeError: 'NoneType' object has no attribute 'split'

Issue

Im new to Python/Flask and wanted to set Cookies for my Website. When i open the Website i get this error.

The functions that are causing Problems:


def numberinstring(nr: int, cookie: str):
          
        visited = cookie.split(":")

        for door in visited:
                if nr == int(door):
                        return True
        return False

def handlecookie(resp: Response, nr: int):

        cookie = request.cookies.get("Besucht")

        if cookie is None:
                resp.set_cookie("Besucht", str(nr))
                return resp

        if numberinstring(nr, cookie):
                return resp

        resp.set_cookie("Besucht",cookie + ":" + str(nr))
        return resp

I am confused to why it doesent work as I checked if cookie is None in line 15.

The Traceback:


File "C:\Users\PJ\Desktop\Kalender\main.py", line 48, in start

if numberinstring(i, cookie):
   ^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\PJ\Desktop\Kalender\main.py", line 12, in numberinstring

visited = cookie.split(":")
          ^^^^^^^^^^^^

Can somebody help me with this?

Solution

request.cookies.get("Besucht") will return None if there’s no KEY with name "Besucht" so check if cookie has value before calling the split method.

def numberinstring(nr: int, cookie: str):
      visited = ""
      if cookie:
          visited = cookie.split(":")

      for door in visited:
          if nr == int(door):
              return True
      return False

Answered By – Maxwell D. Dorliea

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published