Home > Blockchain >  Making python requests in git pre-commit
Making python requests in git pre-commit

Time:09-30

So in my pre-commit I want to run python requests to test whether certain urls are valid before committing.

The problem I am having is the requests library is not installed.

Error

- hook id: pre-commit-py
- exit code: 1

Traceback (most recent call last):
  File "hooks/pre-commit.py", line 8, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'

I have tried setting up a virtual env with pipenv shell and installing requests there, but it doesn't seem to be relevant to the pre-commit environment.

I also tried using a different repo in .pre-commit-config.yaml

repos:
- repo: https://github.com/psf/requests.git
  hooks:
    - id: pre-commit-py
      name: pre-commit-py
      entry: python hooks/pre-commit.py
      language: python
      pass_filenames: false

Code to reproduce

hooks/pre-commit.py

import os
import sys
import requests
try:
    get = requests.get(url, timeout=5)
    if get.status_code == 200:
       print('good')
except Exception as e:
       sys.exit(1)

.pre-commit-config.yaml

repos:
- repo: local
# - repo: https://github.com/psf/requests.git
  hooks:
    - id: pre-commit-py
      name: pre-commit-py
      entry: python hooks/pre-commit.py
      language: python
      pass_filenames: false

CodePudding user response:

I'll start by saying your premise is likely a very bad idea -- making requests to arbitrary urls is bound to be very slow to the point where your contributors will be frustrated with such a hook and turn it off. you'd do better to sequester such a thing to a test rather than a pre-commit hook.

that said, it is possible and easy to do what you want within pre-commit -- but you've missed the "how do I install dependencies" part of local hooks

notably you'll use additional_dependencies to bring in the third party requirement:

        additional_dependencies: [requests]

disclaimer: I wrote pre-commit

  • Related