как вы обновляете requirements.txt?
Возникла задача обновить requirements.txt . А проблема в том что он содержит как прямые зависимости проекта, так и зависимости зависимостей. Мне бы хотелось обновить прямые зависимости до конкретных версий, а все остальные поставить самые последние (чтобы, скажем, получить все security fixes и прочее). Как бы это сделать?
Ну или поделитесь своим опытом обновления requirements.txt . Я пока не придумал ничего лучше как начать с пустого virtualenv и добавлять пакеты пока проект не станет запускаться. Но мне этот подход не нравится, например, тем что
1) это ручная работа
2) иногда import попадается в середине кода. А покрытие тестами пока хромает чтобы надёжно выявить такие дурацкие проблемы (но мы над этим работаем).
How to Update Requirements Files¶
The different requirements files introduced in Software Process section are the following:
- requirements.txt
- requirements-dev.txt
- requirements-doc.txt
- requirements-min.txt
requirements.txt¶
requirements.txt of the project can be created or updated and then captured using the following script:
mkvirtualenv pynwb-requirements cd pynwb pip install . pip check # check for package conflicts pip freeze > requirements.txt deactivate rmvirtualenv pynwb-requirements
requirements-(dev|doc).txt¶
Any of these requirements files can be updated using the following scripts:
cd pynwb # Set the requirements file to update: requirements-dev.txt or requirements-doc.txt target_requirements=requirements-dev.txt mkvirtualenv pynwb-requirements # Install updated requirements pip install -U -r $target_requirements # If relevant, you could pip install new requirements now # pip install -U # Check for any conflicts in installed packages pip check # Update list of pinned requirements pip freeze > $target_requirements deactivate rmvirtualenv pynwb-requirements
requirements-min.txt¶
Minimum requirements should be updated manually if a new feature or bug fix is added in a dependency that is required for proper running of PyNWB. Minimum requirements should also be updated if a user requests that PyNWB be installable with an older version of a dependency, all tests pass using the older version, and there is no valid reason for the minimum version to be as high as it is.
© Copyright 2017-2023, Neurodata Without Borders. Revision 68c4f564 .
Все требования в одном месте – requirements.txt
Обычно для запуска проекта требуется несколько внешних пакетов.
Чтобы каждый раз с болью в сердце не собирать их, список этих пакетов принято поставлять вместе с исходным кодом. Принято селить весь список необходимых пакетов в файле requirements.txt в корне проекта. Формат этого файла простой: по одному пакету на строку.
Заморозка пакетов
У одного пакета обычно много версий. Когда мы просим пип установить пакет, он устанавливает самую свежую из доступных.
Это может привести к проблемам: скажем, проект разрабатывался на версии 1.2. Через полгода потребовалось развернуть его заново, пип установил последнюю версию – 1.5. Эта версия может быть не совместима со старой, тогда код сломается.
Например, такая история была с модулем vk : в версии 1.5 нужно было использовать класс vk.api.APISession , а в версии 2.0 – vk.OAuthAPI . Понятное дело, программа, которая использует не ту версию модуля, ломалась – старого класса-то нет.
Чтобы такого не происходило, пакеты принято замораживать – указывать версию пакета вместе с названием. Пип поддерживает такой синтаксис: модуль==версия .
Вот часть requirements.txt из Девмана:
django==1.10.2 pillow==3.3.0 gunicorn==19.6.0 sorl-thumbnail==12.3 ptpython==0.35
Получить все версии пакетов, установленных на вашем компьютере, можно командой pip freeze :
$ pip freeze django==1.10.2 pillow==3.3.0 gunicorn==19.6.0 sorl-thumbnail==12.3 ptpython==0.35 .
Все зависимости заморозить и в requirements.txt
Установка
Все пакеты из requirements.txt можно установить одним махом, пип такое умеет: pip install -r requirements.txt .
Зависимости зависимостей
К сожалению, правильное заполнение requirements.txt не решает все проблемы с зависимостями и версиями.
Дело в том, что у перечисленных в файле зависимостей есть свои зависимости. Например, модуль vk для своей установки требует модуль requests . Пип установит его сам, незаметно для нас.
Проблема в том, что если модуль requests не заморожен в исходниках модуля vk , через полгода всё опять может сломаться: версия vk будет правильная, а requests – нет.
Эта проблема свойственна большим проектам, у которых десятки зависимостей и сотни неявных зависимостей.
Решение этой проблемы рассмотрим в другой раз. Главное – быть начеку.
Попробуйте бесплатные уроки по Python
Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.
Переходите на страницу учебных модулей «Девмана» и выбирайте тему.
How to keep your requirements.txt updated
Package management in Python is considered excellent, compared to other programming languages. And I agree with this popular opinion.
The problem that these package managers solve is the dependencies issue. What they don’t solve though is how to keep those dependencies updated regularly. While developing your web app, when you decide that you will use a new library you will most probably install the latest version at the time. But over the app’s lifetime, those libraries you decided to use must remain updated to ensure that the web app is working properly and securely.
Most Python apps, keep a requirements.txt file to keep track of all the dependencies. This is a good practice in general. The next step is to keep the dependencies mentioned in requiements.txt to their latest version.
The manual way
The most obvious way is to go through each one of your dependencies and check PyPI for the latest version. This is a slow process but gives you complete control over what is updated and what stays the same (for instance libraries that have a high risk of breaking the app).
An alternative way in case you using an IDE is if they have a built-in mechanism to indicate which libraries are outdated. For instance, in PyCharm you can update to the latest version using a one-click (per library) approach.
The automated way
There’s a Python utility, called Pur, that offers to bring all the dependencies listed in requirements.txt to their latest version. Just pip install pur and you are ready to get started!
After installing, just run:
pur -r requirements.txt
The utility will list the changes that have been made for you to review:
Updated whitenoise: 5.1.0 -> 6.3.0 Updated stripe: 2.50.0 -> 5.0.0 Updated sentry-sdk: 1.5.12 -> 1.13.0 All requirements up-to-date.
The utility offers a few more interesting options for common use cases. For instance, if you use an LTS (long-term support) version of a package, you can use the —minor MY_PACKAGE argument to ensure that only the minor version will be updated. Additionally, you can use the —interactive argument for the utility to ask for each dependency whether to update to the latest version (instead of reviewing the changes afterward). Check the official website for a full list of arguments available.
Now there’s no excuse to keep your Python web app out-of-date. With a single command, you can use the latest versions of your dependencies. Of course, whether the app breaks due to the usage of a newer library is a different story. Having excellent test coverage mitigates this issue but discussing this is outside of the scope of this post.
Hopefully, you can now easily and quickly keep your Python projects fresh.
