2.5 依赖性

依赖性

为运行你的应用所必须用的那些库和模块就是你的项目依赖。

为什么依赖性重要?

Python web 应用常常构建与其他众多程序员的代码之上,不仅仅是开发框架,还包括爬虫、分词、分析、可视化等众多工作。

寻找库函数Finding libraries

Python函数库有一个中央存储仓库叫Python Package Index (PyPi)。PyPi可按照相关权重和相关性提供搜索功能。

除了PyPi还有其他“必备”资源:

隔离依赖性

为了预防系统版本冲突,有时候要隔离依赖性,最常用方法是 virtualenv。每一个virtualenv 有自己的一份Python解释器和依赖库,存放在自己的目录下。要使用virtualenv必须先创建并激活。

How the virtualenv separates dependencies on the server.

安装Python依赖包

先创建并激活virtualenv,然后推荐用 pip 安装依赖包。

requirements.txt

当你开发一个Python项目时应当包含一份 requirements.txt 在项目根目录下,例如:

django==1.6
bpython==0.12
django-braces==0.2.1
django-model-utils==1.1.0
logutils==0.3.3
South==0.7.6
requests==1.2.0
stripe==1.9.1
dj-database-url==0.2.1
django-oauth2-provider==0.2.4
djangorestframework==2.3.1

setup.py

There is another type of dependency specification for Python libraries known as setup.py. Setup.py is a standard for distributing and installing Python libraries. If you’re building a Python library, such as requests or underwear you must include setup.py so a dependency manager can correctly install both the library as well as additional dependencies for the library. There’s still quite a bit of confusion in the Python community over the difference between requirements.txt and setup.py, so read this well written post for further clarification.

依赖性资源

Open source app dependency projects

  • Autoenv is a tool for activating environment variables stored in a .env file in your projects’ home directories. Environment variables aren’t managed by virtualenv and although virtualenvwrapper has some hooks for handling them, it’s often easiest to use a shell script or .env file to set them in a development environment.
  • Pipreqs searches through a project for dependencies based on imports. It then generates a requirements.txt file based on the libraries necessary to run those dependencies. Note though that while this could come in handy with a legacy project, the version numbers for those libraries will not be generated with the output.

Application dependencies learning checklist

  1. Ensure the libraries your web application depends on are all captured in a requirement.txt file with pegged versions.
  2. An easy way to capture currently installed dependencies is with the pip freeze command.
  3. Create a fresh virtualenv and install the dependencies from your requirements.txt file by using the pip install -r requirements.txt command.
  4. Check that your application runs properly with the fresh virtualenv and only the installed dependencies from the requirements.txt file.

发表评论

电子邮件地址不会被公开。 必填项已用*标注