Forums

POST request to Django server

I am using the Python Requests library to make a POST request to my local Django server.

When I run post_request.py from my command line (the one installed on my machine, not a PythonAnywhere console), I receive a 200 response. When I run the same script from a PythonAnywhere console, I receive a 400 response.

# post_request.py

import requests

if __name__ == '__main__':
    s = requests.Session()

    r = s.post(
        'http://localhost:8000/trader/',
        headers={'username': 'derek', 'password': 'password'},
    )

    print(f'{r.headers}\n{r.json}')

This is the response when post_request.py is executed from my command line:

{'Date': 'Tue, 11 Oct 2022 05:07:19 GMT', 'Server': 'WSGIServer/0.2 CPython/3.9.1', 'Content-Type': 'text/html; charset=utf-8', 'X-Frame-Options': 'DENY', 'Content-Length': '40', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin'}

<bound method Response.json of <Response [200]>>

This is the response when post_request.py is executed in a PythonAnywhere console:

{'Server': 'openresty/1.15.8.3', 'Date': 'Tue, 11 Oct 2022 05:08:21 GMT', 'Content-Type': 'text/html', 'Content-Length': '261', 'Connection': 'close'}

<bound method Response.json of <Response [400]>>

I want to receive a 200 response when post_request.py is run in a PythonAnywhere console. What am I doing incorrectly?

There is no access to your local machine from the PythonAnywhere console. In the console localhost is the server your console is running on, not your local machine.