推薦一些維護大型 Python 專案的工具
github 地址: github.com/pypa/pipenv
介紹 pipenv
的文章很多了,我就不多細說了,可以參考下面這篇優秀的文章:

style & linting : flake8
github 地址: github.com/PyCQA/flake…
文件地址: flake8.pycqa.org/en/latest/i…
基本使用方法:
檢查整個專案:
flake8 path/to/your_project/ 複製程式碼
檢查單個檔案:
flake8 path/to/your_file.py 複製程式碼
檢測某個特定型別的 flag,比如我想檢查一下哪些 try except
沒有指定具體的 Exception
型別:
flake8 --select E722 . | more 複製程式碼

詳細的有哪些 flag 可以在這裡檢視: flake8.pycqa.org/en/latest/u… 。
flake8配置檔案
文件在: flake8.pycqa.org/en/latest/u…
可以新增在專案根目錄的 tox.ini
、 setup.cfg
、 .flake8
檔案。
[flake8] ignore = D203 exclude = # No need to traverse our git directory .git, # There's no value in checking cache directories __pycache__, # The conf file is mostly autogenerated, ignore it docs/source/conf.py, # The old directory contains Flake8 2.0 old, # This contains our built documentation build, # This contains builds of flake8 that we don't want to check dist max-complexity = 10 複製程式碼
就等價於:
flake8 --ignore D203 \ --exclude .git,__pycache__,docs/source/conf.py,old,build,dist \ --max-complexity 10 複製程式碼
pre-commit hooks
pre-commit 的文件可見: pre-commit.com/#pre-commit…
示例:把下面這個配置新增到 .pre-commit-config.yaml
:
-repo: https://gitlab.com/pycqa/flake8 rev: ''# pick a git hash / tag to point to hooks: -id: flake8 複製程式碼
code coverage : coverage.py
github 地址: github.com/nedbat/cove…
簡單介紹一下什麼是 code coverage
:
Code coverage is a measurement of how many lines/blocks/arcs of your code are executed while the automated tests are running.來源於此。
就是你執行自動化測試的時候,哪些程式碼行、塊真正被執行了,哪些沒有。是衡量 unittest 全面程度的一個重要指標。
直接用 pip就能安裝: pip install coverage
。
比如在 django 中:
coverage run --source='.' manage.py test coverage html 複製程式碼
就會在專案根目錄的 htmlcov/
目錄生成很多 HTML 檔案,在 htmldov/
目錄下執行http-server (or whatever you like),就能看到所有檔案的統計結果了:

點開某個檔案,就能看到具體哪些行在 ./manage.py test
的時候被執行了:

如果你只是想看一下簡要的資訊,可以用 coverage report
。
區分線上線下環境配置:python-dotenv
github 地址: github.com/theskumar/p…
簡單來說就是把配置資訊放到一個單獨的配置檔案裡面(比如 .env
),和程式碼解耦。
這個我在上一篇文章中詳細說到過,只不過用的是 python-decouple
,但是思想都是一樣的。這裡就不講了。

安全漏洞檢測:bandit
github 地址: github.com/PyCQA/bandi…
基本用法(-r表示檢查當前目錄下所有檔案):
bandit -r . | more 複製程式碼

能夠定位到具體的那一行,還有最有的文件連結。比如這裡檢測到了 pseudo-random generators
,它給出了對應的文件地址: bandit.readthedocs.io/en/latest/b…
最後面還有一個總結情況:

bandit 還有一個特定的配置檔案,請看官方文件。
第三方依賴漏洞檢測 : safety
github 地址: github.com/pyupio/safe…
bindit 檢查的是你自己的程式碼,而 safety 檢查的是按照的第三方依賴。
safety check 複製程式碼

這裡檢測出了 django
有一個編號ID為 36769
的安全漏洞。
該編號對應的詳情可以在 這個檔案 裡面檢視。CVE 編號可以在這個網站查到。

對應的 django 官方說明位於: www.djangoproject.com/weblog/2019… 。指的是 django.views.defaults.page_not_found()
這個方法,攻擊者有可能會在404頁面插入特定內容。
比如一個預設的404頁面,之前是這樣的:會把path /hello
顯示出來。

如果攻擊者把 /hello
改一下:

就有可能誘導使用者點選釣魚網站。
上訴兩張圖片來源於: 關於Django漏洞CVE-2019-3498的評論
pre-commit
pre-commit 就是一些鉤子 bash 指令碼,在執行特定 git 操作的時候可以執行這些指令碼。比如你可以在 commit或者 push之前執行一下 flake8
、 bandit
和 safety
這些工具。
