[django]更改 request.GET 字典的键值时出现 "AttributeError: This QueryDict instance is immutable" 错误

当修改 request.GET/request.POST 时,会出现: "AttributeError: This QueryDict instance is immutable":

def foobar(request):
    #...
    request.GET['foo'] = bar  # AttributeError: This QueryDict instance is immutable
    #...

因为默认的 QueryDict 是不可修改的。解决办法就是复制一份副本,对副本进行修改:

def foobar(request):
    #...
    request.GET = request.GET.copy()  # 添加这一句
    request.GET['foo'] = bar
    #...

参考

more ...

给终端文字加点颜色和特效

这个叫做:ANSI Escape Sequences/Code 。

文字特效相关的字符格式是:ESC[#;#;....;#m ,其中 # 的取值见下表:

# 的值 功能 python 代码 截图
00 或 0 正常显示 '\033[00m' + 'hello' + '\033[0;39m'
01 或 1 粗体 '\033[01m' + 'hello' + '\033[0;39m'
02 或 2 模糊 '\033[02m' + 'hello' + '\033[0;39m'
03 或 3 斜体 '\033 ...
more ...


[git]显示单个文件变更日志

Date Category git Tags git

git log -p filename:

$ git log -p fabfile.py
commit fd792030bc0ac1db0f1f97ec701a2fd8bcb26a07
Author: username <email>
Date:   Sun Jun 23 15:36:58 2013 +0800

    commit title

diff --git a/fabfile.py b/fabfile.py
index 4ed36fa..1408118 100644
--- a/fabfile.py
+++ b/fabfile.py
@@ -9,28 +9,29 @@ from fabric.api ...
more ...

[python]统计列表中重复项的出现次数

列表项由数字、字符串组成,统计重复项:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for x in [1, 2, 3, 1, 2, 3, 1]:
...     d[x] += 1
...
>>> dict(d)
{1: 3, 2: 2, 3: 2}
>>>
>>> c = defaultdict(int)
>>> for y in ['a', 'b', 'a', 'c', 'c']:
...     c[y] += 1
...
>>> dict(c)
{'a': 2, 'c ...
more ...