Search code examples
sslpython-requestspyopenssl

"hostname doesn't match" when using requests in PythonAnywhere


EDIT: I fixed the problem, see links in the answer.

I'm using the XMLHttpRequest AJAX API to send data from different websites to our server in PythonAnywhere. Something odd happens: depending on the website, either we send successfully or we get this error

POST https://canecto.pythonanywhere.com/api/ 500 (Internal Server Error)

even though the same code is loaded. I tried to manually open the request and send data via JavaScript console in Chrome but nothing changes.

Here is how the snippet looks like:

var url = "https://canecto.pythonanywhere.com/api/";
var xmlHttpPost = new XMLHttpRequest();
xmlHttpPost.open("POST", url, true);
xmlHttpPost.setRequestHeader("Content-type", "application/json");

var postData = {
    page_url: window.location.href,
    time_on_page: activeTime,
    cookie: cookie,
    /* some variables */
};
xmlHttpPost.onreadystatechange = function() {
    if (xmlHttpPost.readyState == 4 && XMLHttpRequest.DONE) {
            console.log('');
    }
};

/* send data */
xmlHttpPost.send(JSON.stringify(postData));

I read here that the problem should not be the client-side JavaScript.

If I inspect on the server side, for the line requests.get(page_url, headers=HEADER, timeout=10)(where I try to access the page) I get this log:

enter image description here

I read on the Python request library that it may be something related to the SSL verification, but I have very little clue about it. I tried to check other similar questions but I have not found the answer.

Has anybody experienced anything similar and successfully solved it?


Solution

  • To whom it still uses Python < 2.7.9: this answer worked for me. SNI is not supported in Python 2, that means you should follow such answer and these requirements to make requests work with SSL certificate verification.