2

I have written a Flask application. In that, I am using basic auth to restrict certain POST API views. From Python requests, I can access those views as -

print post(url, json=data, auth=('username', 'password'))

And from curl,

curl -a username:password -d "data" url

How to do the same in app.post ? I tried auth, authorization etc as parameters to post but they were invalid.

response = self.app.post(
            url,
            data=data,
            headers={
            'content-type': 'application/json'
            },
            follow_redirects=True
        )
Avi
  • 1,341
  • 1
  • 18
  • 28

2 Answers2

5

Basic authorization credentials are stored in header as follows -

"Authorization": "Basic username:password"

However the username:password part is base64 encoded. So one can use the base64 module to do the same.

import base64

headers={
   'content-type': 'application/json',
   'Authorization': 'Basic %s' % base64.b64encode('username:password')
}

In the above case, the Authorization will be set to Basic dXNlcm5hbWU6cGFzc3dvcmQ=

This will allow you to use basic authorization from Flask testing framework. Cheers !!

Avi
  • 1,341
  • 1
  • 18
  • 28
0

I find the above method right for sending the post request in unit testing. But for doing so you should have to keep in mind that you should have to disable the CSRF protection in the testing configuration.

class TestingConfig(Config):

WTF_CSRF_ENABLED = False

and best of luck for GSOC 16.

Vivek Singh
  • 169
  • 1
  • 4