“祥”龙第一掌:
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
远离 b'str' u'str'真是烦了 unicode_literals简单方便
“祥”龙第二掌:
django.utils.encoding.smart_bytes django.utils.encoding.force_text django.utils.encoding.smart_text
也不知道创造这些神功的大神砸咋么niuB
“祥”龙第三掌:
__unicode__ ==>NO==Use==>__str__
就是实体类不用__unicode__ 用__str__
“祥”龙第四掌:
from django.utils.six import iteritems
oh why?下面多清晰 因为3.4 的dict没有 很多方法了撒
Python 3.4 >>> a={} >>> dir(a) [... 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] Python 2.7.10 (default, Jul 14 2015, 19:46:27) >>> a={} >>> dir(a) [...'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
“祥”龙第五掌:
在捕获异常的时候使用as
try: article = NewsArticle.objects.get(slug="hello-world") except NewsArticle.DoesNotExist as exc: pass except NewsArticle.MultipleObjectsReturned as exc: pass”
“祥”龙第六掌:
检查变量的类型使用
from django.utils import six isinstance(val, six.string_types) # previously basestring isinstance(val, six.text_type) # previously unicode isinstance(val, bytes) # previously str isinstance(val, six.integer_types) # previously (int, long)
“祥”龙第七掌:
使用range替代xrange
from django.utils.six.moves import range for i in range(1, 11): print(i)”
“祥”龙第八掌:
弄清楚python的版本
from django.utils import six if six.PY2: print("Python2") if six.PY3: print("Python3")