10

這是我在Flask-RESTful中的單元測試的一部分。如何發送用戶名:密碼unittest的app.get()請求?

self.app = application.app.test_client() 
rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp)) 
eq_(rv.status_code,200) 

在命令行中,我可以使用curl發送用戶名:密碼服務:

curl -d username:password http://localhost:5000/api/v1.0/1234567 

如何實現我的單元測試的get內相同的()?

由於我的get/put/post需要驗證,否則測試會失敗。

回答

15

RFC 1945, Hypertext Transfer Protocol -- HTTP/1.0

11.1 Basic Authentication Scheme

...

要接收授權,則客戶端發送所述用戶ID和口令, 由單個冒號( 「:」)分隔字符,在credentials.string的base64 [5] 編碼字符串內。

...

如果用戶代理希望發送用戶ID「阿拉丁」和密碼 芝麻開門」,它將使用下列頭字段:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== 

所以如果你真的使用http基本認證,你可以像下面的解決方案,雖然你curl使用建議一些其他的認證方案。

from base64 import b64encode 

headers = { 
    'Authorization': 'Basic ' + b64encode("{0}:{1}".format(username, password)) 
} 

rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp), headers=headers) 
+0

作品,謝謝一堆。 – Houman

2

另一種解決方案 - 一切歸功於道格·黑

def request(self, method, url, auth=None, **kwargs): 
    headers = kwargs.get('headers', {}) 
    if auth: 
     headers['Authorization'] = 'Basic ' + base64.b64encode(auth[0] + ':' + auth[1]) 

    kwargs['headers'] = headers 

    return self.app.open(url, method=method, **kwargs) 

,然後使用你的測試這種方法:

resp = self.request('GET', 'api/v1.0/{0}'.format(ios_sync_timestamp), auth=(username, password)) 
2

對於Python 3,請嘗試以下例子:

from base64 import b64encode 
headers = { 
    'Authorization': 'Basic %s' % b64encode(b"username:password").decode("ascii") 
} 

self.app.get("foo/", headers=headers) 

如果您想使用動態變量作爲用戶名和密碼,請嘗試如下所示:

'Basic %s' % b64encode(bytes(username + ':' + password, "utf-8")).decode("ascii") 

另請參閱:Python, HTTPS GET with basic authentication

相關問題