urllib response.read()无法按预期工作

时间:2017-01-25 07:21:46

标签: python urllib2 urllib

我目前正在尝试从urllib返回帖子回复。当我使用它打印的response.read()打印它时,响应很好。但是,如果我将其分配给变量d然后打印或返回它。它是空的。如何解决这个问题。

def update_cancel_job(self,userid,apiKey,secret,source,server,jobtids):
    rv = RequestValidation()
    hsh = rv.CreateAPISecret(str(userid), str(apiKey), str(secret)) 
    getVars ={'id':str(userid),'key':str(apiKey),'jobs':int(jobtids),'source':source,'hsh':hsh}
    url=server+"/api/outsource/job/cancel/?"
    data= urllib.urlencode(getVars)
    response_from_executor=urllib2.urlopen(url,data)
    #the below line prints fine
    print response_from_executor.read()
    print type(response_from_executor)
    #the below line however does not. It prints empty
    d = response_from_executor.read()
    print d
    #the reuturn is also empty
    return d    

2 个答案:

答案 0 :(得分:0)

服务器正在向您发送字节流;没有办法“倒带” 没有发出另一个请求。

答案 1 :(得分:0)

现在,如果你调用update_Cancel_job(),它将打印响应,然后将响应返回给你调用函数的任何内容。关键是首先将值保存在变量中,以便您可以使用它们。此外,如果您需要在该功能之外访问 private static void SendMessages() { topicClient = TopicClient.Create(TopicName); List<BrokeredMessage> messageList = new List<BrokeredMessage> { CreateSampleMessage("1", "First message information"), CreateSampleMessage("2", "Second message information"), CreateSampleMessage("3", "Third message information") }; Console.WriteLine("Sending messages to topic..."); foreach (BrokeredMessage message in messageList) { while (true) { try { topicClient.Send(message); } catch (MessagingException e) { if (!e.IsTransient) { Console.WriteLine(e.Message); throw; } } Console.WriteLine($"Message sent: Id = {message.MessageId}, Body = {message.GetBody<string>()}"); break; } } topicClient.Close(); } ,您可以将其设置为d

global