python django API身份验证发布请求 - 输出变量在浏览器中显示json字符串,但在打印时不显示

标签 python django urllib2

def test(request):
    u="username"
    p= 'password'
    url='url'
    req = urllib2.Request(url)
    base64string = base64.encodestring('%s:%s' % (u , p )).replace('\n', '')
    d = {}
    req.add_data(d)  //while authentication i dont send any data, but it is treated as POST request only if data is sent, so sending empty data
    req.add_header("Authorization", "Basic %s" % base64string) 
    req.add_header('Accept', 'application/json')  
    result = urllib2.urlopen(req)

    print result
    return HttpResponse(result) 

在浏览器中,响应为(HttpResponse 的 bcoz)

{"token":"abcdef"}  //means correct

但是命令“打印结果”给出了类似这样的内容:

<addinfourl at 140585554707088 whose fp = <socket._fileobject object at 0x7fdca009e5d0>>

所以,我无法对该变量进行任何操作。我想要的只是字符串中的“ token ”值。我尝试过:

type(result) // error
json.dumps(result)  //error 
json.loads(result)  //error 
token = result.token     //error

最佳答案

你应该使用

result.read()

result 是结果对象。

关于python django API身份验证发布请求 - 输出变量在浏览器中显示json字符串,但在打印时不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277024/

相关文章:

python - 使用套接字 : address already in use 监听 ip 地址

python - Python 中使用 Condition 对象的线程间通信

javascript - Django:Crispy 表单的 Ajax 验证

Python:需要附加额外的 header ,在 urllib2 添加隐藏默认值之后,在发送请求之前

python - Python中如何区分超时错误和其他 `URLError`?

python - pytest-bdd : Importing common steps

python - 如何重载 `__eq__` 来比较 pandas DataFrames 和 Series?

django - django ModelMultipleChoiceField设置初始值

django - 指定现有 ManyToMany "through table"关系之一的最佳方法?

Python urllib2.urlopen : Read site-body even though there is an HTTP header error