Dealing with optional urlparse parameters in url

231 views Asked by At

My little script deals with a couple of parameters passed from the url;

bright = int(urlparse.parse_qs(urlparse.urlparse(self.path).query).get('bright', None)[0])
loops = int(urlparse.parse_qs(urlparse.urlparse(self.path).query).get('loops', None)[0])
speed = float(urlparse.parse_qs(urlparse.urlparse(self.path).query).get('speed', None)[0])/1000

However some of the parameters are optional and sometimes for example 'bright' is not passed in the url since it's not relevant. When thats the case it throws me this error;

bright = int(urlparse.parse_qs(urlparse.urlparse(self.path).query).get('bright', None)[0])
TypeError: 'NoneType' object has no attribute '__getitem__'

Which I can understand.. it's trying to parse something that's not there. What would be the best way to deal with this? Is there a way to first get a list of the parameters present in the url before trying to parse them?

1

There are 1 answers

0
Sam Chats On BEST ANSWER

Why not just loop over the parameter dictionary you get from parse_qs() to see the available parameters present in the url?

Also, you can catch a None occurrence with a try/except block, and act accordingly.