7.3. Callback

  • EN: Callback

  • PL: Wyzwalacz

7.3.1. Solution

from typing import Any, Callable
from urllib.request import urlopen


def fetch(url: str,
          *,
          on_success: Callable[[str], Any] = lambda response: ...,
          on_error: Callable[[Exception], Any] = lambda exception: ...,
          ) -> None:
    try:
        response = urlopen(url).read().decode('utf-8')
    except Exception as error:
        on_error(error)
    else:
        on_success(response)

Usage:

def ok(response: str):
    print(response[:100])

def err(exception: Exception):
    print(exception)

fetch(url='https://python3.info', on_success=ok, on_error=err)


<!DOCTYPE html>
<html class="writer-html5" lang="en" data-content_root="./">
<head>
  <meta charse

7.3.2. Object

import requests
from http import HTTPStatus


def http(obj):
    response = requests.request(
        method=obj.method,
        data=obj.data,
        path=obj.path)

    if response == HTTPStatus.OK:
        return obj.on_success(response)
    else:
        return obj.on_error(response)


class Request:
    method = 'GET'
    path = '/index'
    data = None

    def on_success(self, response):
        print('Success!')

    def on_error(self, response):
        print('Error')

http(Request())