一定程度的保证源码的安全性

准备工作


  1. django项目源码(这里使用django官方教程的demo)
  2. 相关库安装:cython用于文件格式转换、autopep8用于py文件标准化(不然cython转换过程中会有报错)


django demo准备


WX20190822-095224

启动测试可用性

WX20190822-095655

WX20190822-095756


编写文件转换脚本


引用模块

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
import Cython.Compiler
import os

cython转换核心方法

files_path = "polls/*.py"
ext_modules = [Extension('*', [files_path],)]
setup(
    name="py to so",
    cmdclass={'build_ext': build_ext},
    ext_modules=cythonize(ext_modules)
)

pep8自动转换

autopep8 --in-place --aggressive --aggressive filename

这里需要写一个处理逻辑,当cython识别到py文件不规范报错时,执行pep8标准化,然后继续转换。

最终的代码

# 如果是多层目录可以这样写
# "folders/**/*.py"
files_path = "polls/*.py"

def to_so():
    try:
        ext_modules = [Extension('*', [files_path],)]
        setup(
            name="py to so",
            cmdclass={'build_ext': build_ext},
            ext_modules=cythonize(ext_modules)
        )
    except Cython.Compiler.Errors.CompileError as e:
        # 捕获异常,从报错信息的最后一行获取文件名并格式化
        filename = str(e).split('\n')[-1]
        os.popen(
            'autopep8 --in-place --aggressive --aggressive ' +
            os.getcwd() +
            "/" +
            filename)
        # 继续转换
        to_so()

to_so()

执行效果如下:(注意这里需要build,不然只会生成.c文件)

python pytoso.py build

WX20190822-102019

当前目录会自动生成build文件夹,so文件在里面

WX20190822-104151

转换的目录下还会生成.c文件

WX20190822-104325

所以我们还需要写一个脚本,将so文件移动到正确位置,并且清理掉无用的文件

import os
import glob

app_name = "polls"
dir_name = os.getcwd() + "/"
build_dir_name = os.getcwd() + "/build/lib.macosx-10.14-x86_64-3.7/"
useless_files = []

app_path = dir_name + app_name
# 如果源码为客户私有部署的,可以把.git文件也清理了
useless_files += glob.glob(app_path + "/*.py")
useless_files += glob.glob(app_path + "/*.c")
useless_files += glob.glob(app_path + "/*.so")
for useless_file in useless_files:
    try:
        os.remove(useless_file)
        print("Delete: " + useless_file)
    except BaseException:
        print(useless_file + "not exsit")

builded_app_path = build_dir_name + app_name
os.system("cp " + builded_app_path + "/* " + app_path)
print("Copy: " + builded_app_path + "/* TO " + app_path)

print("All done!")
python arrange_files.py

这样文件就整理好了WX20190822-111636


验证可用性


WX20190822-112028

完美运行

WX20190822-112048


总结