0

I have a python (flask) application that when I curl it using following command:

Request:

curl -X POST "localhost:8090/endp/" -H "Content-Type: application/json" -d @jsonExample

JsonEquals file includes:

{"idSeq":"0123","timeStamp":"15032019","source":"US","destination":"GB","content":"parcel"}

Response: Note: It will return two NEW fields which is as expected!

{
  "idSeq": "0123", 
  "routeInfo": "Good", 
  "content": "parcel", 
  "Notes": "Send fine "
}

But when I run my python unittest using command: python myTest.py

import os, sys

import json
import main
import unittest


class PublicTestCase(unittest.TestCase):
    def setUp(self):
        self.app = main.app.test_client()

    def my_first_test(self):
        headers = {
            'Content-Type': 'application/json'
        }
        data = {
            "idSeq": "0123",
            "timeStamp": "15032019",
            "source": "US",
            "destination": "GB",
            "content": "parcel"
        }

        response = self.app.post('/endp',
                                 headers=headers,
                                 data=json.dumps(data),
                                 follow_redirects=True)
        print("+++++++++++++++++++++++++++++++++++")
        print(data)
        print("+++++++++++++++++++++++++++++++++++")
        print(response)

        assert response.status_code == 200


if __name__ == '__main__':
    unittest.main()

I then get the following error:

[2020-03-05 14:00:08,093] ERROR in app: Exception on /endp/ [POST]
Traceback (most recent call last):
  File "/home/ubuntu/venvs/inference/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/ubuntu/venvs/inference/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/ubuntu/venvs/inference/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/ubuntu/venvs/inference/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/ubuntu/venvs/inference/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/ubuntu/venvs/inference/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "../src/main.py", line 72, in mypostmethod
    content = req_data['content']
TypeError: 'NoneType' object is not subscriptable
+++++++++++++++++++++++++++++++++++
{'idSeq': '0123', 'timeStamp': '15032019', 'source': 'US', 'destination': 'GB', 'content': 'parcel'}
+++++++++++++++++++++++++++++++++++
<Response streamed [500 INTERNAL SERVER ERROR]>
F
======================================================================
FAIL: my_first_test (__main__.PublicTestCase)

Any idea what I am doing wrong? Apologies if something similar was asked before but I checked and could not find a relevant answer to what I am doing with python FLASK!

main.py

@app.route("/endp/", methods=['POST'])
def mypostmethod():
    req_data  = request.get_json()

    content = req_data['content']
    timeStamp = req_data['timeStamp']
    idSeq = req_data['idSeq']
    ...
    ...
Saffik
  • 911
  • 4
  • 19
  • 45
  • Can you provide the full traceback? Given that your print() statements are happening, I'd have to assume that `self.app = main.app.test_client()` is at fault so please also provide the contents of main/app.py – FiddleStix Mar 05 '20 at 14:14
  • @FiddleStix gave more stacktrace – Saffik Mar 05 '20 at 14:18
  • The error message is on line 72 of main.py, inside of mypostmethod(). Please post the relevant code so we can see that piece. My guess is that `req_data` is actually None, and so when you try to use it as a `dict`, it won't let you `subscript` the object: i.e. `['content']` – Jon Mar 05 '20 at 14:48
  • Perhaps this is a relevant answer: https://stackoverflow.com/questions/9320766/python-math-typeerror-nonetype-object-is-not-subscriptable#answer-9320883 – Jon Mar 05 '20 at 14:51
  • @Jon, so to fix that I need to convert to json? – Saffik Mar 05 '20 at 14:53
  • 2
    `ContentType` should be `Content-Type` in `headers`. You can also use `json=your_dictionary` instead of `data=json.dumps(your_dictionary)`. See here: https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests – Reut Sharabani Mar 05 '20 at 14:54
  • @ReutSharabani if I remove json.dumps, then it puts single quotes in the request body.... and it throws 400 BAD REQUEST ERROR – Saffik Mar 05 '20 at 15:19
  • You are expected to drop the `data` argument in favor of the `json` argument if you want flask to handle the conversion. Read the link I've attached. – Reut Sharabani Mar 05 '20 at 15:31

0 Answers0