Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing form data in request

I have following code

class MyClass(restful.Resource):

    def get(self):
        headers = {'Content-Type': 'text/html'}
        return make_response(render_template('myfile.html'),200,headers)

    def post(self):
            session['CONSUMER_KEY']=request.form.get('consumer_key')
            session['CONSUMER_SECRET']=request.form.get('consumer_secret')
            render_template('myfile.html')

api.add_resource(MyClass,"/mag/",endpoint="mag")

I have written following test:

   def mytest(self):
        content_type={"Content-Type": "application / x - www - form - urlencoded","Content-Disposition": "form-data"}
        response = self.client.post(
            api.url_for(MyClass), data = json.dumps({'consumer_key':'testconsumerkey',
                        'consumer_secret':'testconsumersecret'}),
            headers=content_type
        )

The issue is form data is blank and thats the values are not getting set in session. When i debug i see that request.data is populated but request.form is an empty dictionary. Can someone suggest how I can send form data in a post request from a test

EDIT: Environment details Python 2.7, Flask web framework, self.client is . I am using flask.ext.testing

like image 383
Prim Avatar asked Apr 29 '16 11:04

Prim


1 Answers

You seem to be confused as to what the expected format for the post body should be. Should it be JSON data (which is what you send in the test case), or should it be in the application/x-www-form-urlencoded format (which is what you claim to send in the test case, and what the endpoint will read)?

If you wish to receive JSON data, you'll need to change the endpoint to read the data from request.get_json(). You'll also need to use application/json as the Content-Type header in the test case.

If you wish to receive urlencoded post data, then just simplify the test case by removing the Content-Type header and the json.dumps. Just pass the data dict to the data argument.

like image 121
Alvin Lindstam Avatar answered Oct 14 '22 15:10

Alvin Lindstam