响应后concat.getvalue()上的python变量为空
(python新增) 我正在尝试对一个文件进行简单的身份验证。。。所以我做了两个卷发,第一个进行身份验证(按照预期打印令牌),但当我使用相同的变量(令牌)将其添加到头中(“授权:承载者%s”%str(令牌))时,令牌为空。我在这儿做错什么了响应后concat.getvalue()上的python变量为空,python,file-upload,pycurl,Python,File Upload,Pycurl,(python新增) 我正在尝试对一个文件进行简单的身份验证。。。所以我做了两个卷发,第一个进行身份验证(按照预期打印令牌),但当我使用相同的变量(令牌)将其添加到头中(“授权:承载者%s”%str(令牌))时,令牌为空。我在这儿做错什么了 import urllib import cStringIO import pycurl import requests from urllib import urlencode import os.path # declarations filename
import urllib
import cStringIO
import pycurl
import requests
from urllib import urlencode
import os.path
# declarations
filename = "./profile.jpg"
response = cStringIO.StringIO()
c = pycurl.Curl()
# formdata
post_data = {'username': '...', 'password':'...'}
# Form data must be provided already urlencoded.
postfields = urlencode(post_data)
# Sets request method to POST,
# Content-Type header to application/x-www-form-urlencoded
# and data to send in request body.
print "*****************************************************"
# authenticate
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.URL, "https://.../auth")
c.setopt(c.POSTFIELDS, postfields)
c.setopt(c.SSL_VERIFYPEER, 0)
c.setopt(c.SSL_VERIFYHOST, 0)
c.setopt(c.VERBOSE, 1)
c.perform()
c.close()
token = response.getvalue()
print token
print "*****************************************************"
# upload file
filesize = os.path.getsize(filename)
fin = open(filename, 'rb')
c = pycurl.Curl()
c.setopt(c.PUT, 1)
c.setopt(c.URL, "https://.../avatar")
c.setopt(c.HTTPPOST, [("file", (c.FORM_FILE, filename))])
c.setopt(c.HTTPHEADER, [
"Authorization: Bearer %s" % str(token),
"Content-Type: image/jpeg"
])
c.setopt(c.READFUNCTION, fin.read)
c.setopt(c.POSTFIELDSIZE, filesize)
c.setopt(c.SSL_VERIFYPEER, 0)
c.setopt(c.SSL_VERIFYHOST, 0)
c.setopt(c.VERBOSE, 1)
c.setopt(c.WRITEFUNCTION, response.write),
c.perform()
c.close()
print response.getvalue()
print "*****************************************************"
请求:
> PUT ../avatar HTTP/1.1
User-Agent: PycURL/7.19.3 libcurl/7.35.0 GnuTLS/2.12.23 zlib/1.2.8 libidn/1.28 librtmp/2.3
Host: 127.0.0.1:8080
Accept: */*
Transfer-Encoding: chunked
Authorization: Bearer
Expect: 100-continue
答复:
< HTTP/1.1 100 Continue
< HTTP/1.1 401 Unauthorized
< content-type: application/json; charset=utf-8
< cache-control: no-cache
< content-length: 86
< Date: Tue, 02 Jun 2015 19:09:29 GMT
< Connection: keep-alive
<
* Connection #1 to host 127.0.0.1 left intact
{"statusCode":401,"error":"Unauthorized","message":"Incorrect Token or Token Expired"}
我认为存在编码问题。print
函数可以输出一些内容,而无需考虑编码。看看这本书,它提到了这个问题。我会尝试在这一行中操纵编码:
"Authorization: Bearer %s" % str(token)
试着这样做:
"Authorization: Bearer %s" % token.decode('iso-8859-1')
(我也会尝试.decode(“utf-8”)
,这取决于编码方式)
您可能需要将response=cStringIO.StringIO()
更改为response=BytesIO()
。我不能给出一个明确的答案,因为我不确定你的设置
编辑:我对编码的怀疑是肯定的,因为它说Unicode不受支持。您得到的确切错误是什么?401未经授权。。。但输出标题显示:。。。授权:持证人。。。银行里没有代币header@James-这实际上不是一个错误-如果授权头中没有令牌,我会期望401。问题是令牌似乎是空的,但是,在
打印令牌
行,令牌正在打印到控制台。