介紹 pipenv 的文章很多了,我就不多細說了,可以參考下面這篇優秀的文章:
- pipenv 更優雅的管理你的python開發環境
Python學習交流群:1004391443,這裡是python學習者聚集地,有大牛答疑,有資源共享!小編也準備了一份python學習資料,有想學習python編程的,或是轉行,或是大學生,還有工作中想提升自己能力的,正在學習的小夥伴歡迎加入學習。
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 這些工具。