[django]通过自定义 Model Field 的方式将上传的文本文件按 UTF-8 编码保存

默认情况下上传的文件都是按原始编码进行保存的,用户上传什么编码的文件就保存什么编码的文件。

下面将举例说明如何通过自定义 Model Field 的方式将文件的编码改为 UTF-8。

假设有个文件: app/fields.py

import chardet
from django.db import models
from south.modelsinspector import add_introspection_rules

class UTF8TextFileField(models.FileField):
    """上传的文本文件将按 utf8 编码保存"""

    def clean(self, *args, **kwargs):
        uploaded_file = super(UTF8TextFileField, self).clean(*args, **kwargs)
        content_raw = uploaded_file.file.read()
        # 猜测原始文件编码
        encoding = chardet.detect ...
more ...

[python]如何生成一个 Unicode 编码的文件

平时我们用记事本保存文件时,可以看到文件编码可以选择 Unicode 编码。 那么如何用 python 生成一个 Unicode 编码的文件呢?

只需知道 python 中哪个编码代表 Unicode 编码,我们就可以生成一个 Unicode 编码的文件:

Codec Aliases Languages Note
utf_16 U16, utf16 all languages Unicode(UTF-16 LE BOM)
utf_16_be UTF-16BE all languages (BMP only) Unicode(UTF-16 BE)
utf_16_le UTF-16LE all languages (BMP only) Unicode(UTF-16 LE)

上面表格中,LE ...

more ...

[git]如何删除在远程已被删除的本地分支(清理本地分支)

Date Category git Tags git

通过 git fetch -p 命令可以实现清理本地分支的功能:

$ git fetch -p
 x [deleted]         (none)     -> origin/feature-xxx
 x [deleted]         (none)     -> origin/feature-xxxx
 x [deleted]         (none)     -> origin/feature-xxxxx
 x [deleted]         (none)     -> origin/hotfix-xx

# 然后再执行
$ git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs ...
more ...