为什么我不能获取此http_response的状态代码?

时间:2017-07-22 21:16:18

标签: python multithreading http

为什么我会收到此错误:

using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.IO;
using System.Linq;

namespace ConsoleApp6
{

    public class Company
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime dtEstablished { get; set; }

        [NotMapped]
        public Car[] CarsManufactured
        {
            get
            {
                var ser = new JsonSerializer();
                var jr = new JsonTextReader(new StringReader(CarsManufacturedJSON));

                return ser.Deserialize<Car[]>(jr);
            }
            set
            {
                var ser = new JsonSerializer();
                var sw = new StringWriter();
                ser.Serialize(sw,value);
                CarsManufacturedJSON = sw.ToString();
            }
        }

        [Column("CarsManufactured")]
        public string CarsManufacturedJSON { get; set; }


    }

    public class Car
    {

        public string Name { get; set; }
        public string Model { get; set; }
        public DateTime MfgDate { get; set; }
        public string Type { get; set; }
    }
    class Db: DbContext
    {
        public DbSet<Company> Companies { get; set; }

    }
    class Program
    {

        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {
                db.Database.Log = m => Console.WriteLine(m);

                var company = db.Companies.Create();
                company.Name = "Acme";
                company.dtEstablished = new DateTime(2000, 2, 2);

                var cars = new Car[5];
                for (int i = 0; i<cars.Length; i++)
                {
                    var c = new Car()
                    {
                        MfgDate = new DateTime(2010 + i, 1, 1),
                        Model = $"Model{i}",
                        Name = $"ModelName{i}",
                        Type = $"Type{i}"

                    };
                    cars[i] = c;
                }

                company.CarsManufactured = cars;

                db.Companies.Add(company);
                db.SaveChanges();

            }
            using (var db = new Db())
            {
                var company = db.Companies.First();
                Console.WriteLine(company.CarsManufacturedJSON);

            }
            Console.ReadKey();

        }
    }
}
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib/python2.7/urllib2.py", line 435, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
    code, msg, hdrs = response.code, response.msg, response.info()
AttributeError: 'str' object has no attribute 'code'

2 个答案:

答案 0 :(得分:1)

在您的处理程序中,您应该返回response

import urllib2
import threading

class MyHandler(urllib2.HTTPHandler):
    def http_response(self, req, response):
        return response

o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=o.open, args=('http://www.google.com/',))
t.start()
t.join()

因为,正如错误所述,http_response应返回三个值:code, msg, hdrs

  File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
    code, msg, hdrs = response.code, response.msg, response.info()

但是你要覆盖它只返回response.getcode()

的一个值

获取HTTP响应代码

要获取响应代码,您需要处理从Thread获取返回结果。 This SO讨论提出了几种方法。

以下是更改代码以使用队列的方法:

import urllib2
import threading
import Queue


class MyHandler(urllib2.HTTPHandler):
    def http_response(self, req, response):
        return response

que = Queue.Queue()
o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=lambda q, arg1: q.put(o.open(arg1)), args=(que, 'http://www.google.com/'))
t.start()
t.join()
result = que.get()
print result.code

代码打印200

答案 1 :(得分:0)

错误消息的含义是responsestrcode中没有str属性。我怀疑需要解析response来提取代码。