Skip to content

Commit

Permalink
enh Tratamiento de las excepciones de requests
Browse files Browse the repository at this point in the history
  • Loading branch information
quique committed Nov 10, 2021
1 parent 555ab88 commit afb1eeb
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 15 deletions.
13 changes: 11 additions & 2 deletions geo/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,11 @@ def post(self, request, *args, **kwargs):

cliente = WSClient()
for asignacion in asignaciones:
cliente.matricular_profesor(asignacion.profesor, curso)
try:
cliente.matricular_profesor(asignacion.profesor, curso)
except Exception as ex:
messages.error(self.request, f'ERROR: {ex}.')
return redirect('curso_detail', curso_id)

messages.success(request, _('Se ha vuelto a matricular al profesorado del curso.'))
return redirect('curso_detail', curso_id)
Expand Down Expand Up @@ -883,7 +887,12 @@ class ProfesorCursoAnularView(
def form_valid(self, form):
# This method is called when valid form data has been POSTed. It should return an HttpResponse.
cliente = WSClient()
respuestas = cliente.desmatricular(self.object.profesor, self.object.curso)
try:
respuestas = cliente.desmatricular(self.object.profesor, self.object.curso)
except Exception as ex:
messages.error(self.request, f'ERROR: {ex}.')
return redirect('curso_detail', self.object.curso_id)

for respuesta in respuestas:
for error in respuesta.get('errors'):
messages.error(
Expand Down
45 changes: 32 additions & 13 deletions geo/wsclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,21 +209,40 @@ def matricular_alumnos(self, nips, curso):

def _request_url(self, verb, wsfunction, token, data=None):
"""Envía una petición al Web Service."""
if verb == 'POST':
resp = requests.post(
f'{self.api_url}?wstoken={token}&wsfunction={wsfunction}&moodlewsrestformat=json',
data=data,
try:
if verb == 'POST':
resp = requests.post(
f'{self.api_url}?wstoken={token}&wsfunction={wsfunction}&moodlewsrestformat=json',
data=data,
)
resp.raise_for_status()

elif verb == 'GET':
resp = requests.get(
f'{self.api_url}?wstoken={token}&wsfunction={wsfunction}&moodlewsrestformat=json',
params=data,
)
resp.raise_for_status()

else:
raise Exception('Método HTTP no soportado')

except requests.exceptions.SSLError:
raise requests.exceptions.SSLError(
'No fue posible verificar el certificado SSL de Moodle'
)
elif verb == 'GET':
resp = requests.get(
f'{self.api_url}?wstoken={token}&wsfunction={wsfunction}&moodlewsrestformat=json',
params=data,
except requests.exceptions.ConnectionError:
raise requests.exceptions.ConnectionError('No fue posible conectar con Moodle')
except requests.exceptions.HTTPError:
raise requests.exceptions.HTTPError('Moodle devolvió una respuesta HTTP no válida')
except requests.exceptions.Timeout:
raise requests.exceptions.Timeout('Moodle no respondió')
# except requests.exceptions.TooManyRedirects:
# raise requests.exceptions.TooManyRedirects('Demasiadas redirecciones')
except requests.exceptions.RequestException:
raise requests.exceptions.RequestException(
'Problema desconocido al enviar la petición a Moodle'
)
else:
raise Exception('Método HTTP no soportado')

if not resp.ok: # resp.status_code 200
resp.raise_for_status()

received_data = json.loads(resp.content.decode('utf-8'))
if isinstance(received_data, dict) and received_data.get('exception', None):
Expand Down

0 comments on commit afb1eeb

Please sign in to comment.