Search code examples
pythonhttprequestwebapp2

Python string is null but also isn't None nor empty string


class StartAnalysis(BaseHandler):
    def post(self):
        playlist = self.request.get('playlist')
        language = self.request.get('language')

If I make a POST request without this playlist field, then this happens:

>>> playlist
null
>>> type(playlist)
<type 'unicode'>
>>> playlist is None
False
>>> not playlist
False
>>> playlist == ''
False
>>> playlist == u''
False

How am I supposed to check that it's None? And why is it saying that it's null and not None?

I'm using AppEngine.

My javascript code making the POST request:

let params = new URLSearchParams(location.search);
let url_id = params.get('id');
let url_language = params.get('language');
const url = 'http://localhost:8080/start-analysis?playlist=' + url_id + '&language=' + url_language;
$.ajax({
    url: url,
    type: 'POST',
    success: function(results) {
       ...
    },
    error: function(error) {
       ...
    }
});

Solution

  • I changed to using application/json for the POST requests instead of the default application/x-www-form-urlencoded and that seemed to fix the problem of the request sending the string "null" instead of just an empty string when one of the parameters was empty or missing.

    let params = new URLSearchParams(location.search);
    let url_id = params.get('id');
    let url_language = params.get('language');
    const url = 'http://localhost:8080/start-analysis';
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({'playlist': url_id,'language': url_language}),
        success: function(results) {
            ...
        },
        error: function(response, status, error) {
            ...
        }
    });
    
    

    And the backend receives it like:

    class StartAnalysis(BaseHandler):
        def post(self):
            data = json.loads(self.request.body)
            playlist = data['playlist']
            language = data['language']