Browse Source

feat: Client can download files

feat/download
Michaël Costa 2 months ago
parent
commit
d0b66edfdf
3 changed files with 53 additions and 0 deletions
  1. +12
    -0
      README.md
  2. +30
    -0
      scrippy_api/api/client.py
  3. +11
    -0
      tests/test_basic_url.py

+ 12
- 0
README.md View File

@ -151,3 +151,15 @@ response = client.request(method="PATCH",
params=params,
data=data)
```
##### Téléchargement de fichiers
```python
from scrippy_api.api import Client
url = "https://monthy.python/inquisition.zip"
local_dir = "/home/luiggi.vercotti"
local_filename = "spanish_inquisition.zip"
client = Client()
if client.download(url, local_dir, local_filename):
print("No one expects the Spanish inquisition")
```

+ 30
- 0
scrippy_api/api/client.py View File

@ -1,5 +1,6 @@
"""Module facilitant l'utilisation d'API ReST."""
import os
import logging
import requests
from scrippy_api import ScrippyApiError as ScrippyApiError
@ -24,6 +25,35 @@ class Client:
self.verify = verify
self.session = requests.Session()
def download(self, url, local_path, filename=''):
"""
Permet le téléchargement d'un fichier.
:param url: L'UrL à partir de laquelle télécharger le fichier
:param local_path: Le répertoire dans lequel sauvegarder le fichier
:param filename: Le nom du fichier local
"""
if len(filename) == 0:
filename = url.split('/')[-1]
filename = os.path.join(local_path, filename)
logging.info("[+] Téléchargement du fichier")
logging.info(f" '-> Depuis: {url}")
logging.info(f" '-> Vers: {filename}")
try:
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return True
except Exception as e:
if self.exit_on_error:
err_msg = "Erreur lors de la requete: [{}] {}".format(e.__class__.__name__, e)
raise ScrippyApiError(err_msg)
else:
logging.warning("Erreur lors de la requete: [{}] {}".format(e.__class__.__name__, e))
return response
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, proxies=None, json=None):
"""
Permet d'exécuter une requète HTTP.


+ 11
- 0
tests/test_basic_url.py View File

@ -1,4 +1,5 @@
"""Test de base du client d'API."""
import os
import pytest
from scrippy_api.api import Client
from scrippy_api import ScrippyApiError
@ -31,3 +32,13 @@ def test_get_unknown_user():
with pytest.raises(ScrippyApiError) as err:
response = client.request(method="GET", url=url, params=params)
assert "Erreur lors de la requete: [HTTPError] 404 Client Error: Not Found for url: http://gunicorn:8080/user?first_name=Luiggi&last_name=Vercotti&password=SP4N1SH1NQU1S1T10N" in str(err.value)
def test_download():
"""Test de téléchargement. """
url = "https://www.mcos.nc/user/pages/01.home/_sliders/01.illustration/banner.jpg"
local_dir = "./"
local_path = os.path.join(local_dir, url.split('/')[-1])
client = Client()
assert client.download(url, local_dir)
assert os.path.isfile(local_path)

Loading…
Cancel
Save