python2与python3使用不同之处(总结)

1、from Queue import Queue---------python2

 from  queue import queque--------python3

2、udp.Socket.sendto(b"haha",("192.168.119.115",8080))----python3

  udp.Socket.sendto("haha",("192.168.119.115",8080))----python2

3、import urllib2--------python2

 ullib.request---------python3

某个django项目从python2迁移到python3的过程中,出现了以下问题: 
TypeError: __str__returned non-string (type bytes) 
经查证,是模型类中的 __str__ 方法造成的,原因是python3中 __str__ 不能接收bytes类型的数据,这和python2/3的编解码方式是有关系的。 
下面给出python2和python3的写法:

class ArticelType(models.Model):
    # 类型名称
    typename = models.CharField(max_length=50)
    # 逻辑删除
    isDelete = models.BooleanField(default=False)

    def __str__(self):
        return self.typename.encode("utf-8") # python2写法
        return self.typename                 # python3写法
    class Meta:
        verbose_name = '文章类型'
        verbose_name_plural = '文章类型'

posted on 2018-03-28 10:32  小石潭记  阅读(192)  评论(0编辑  收藏  举报

导航