> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> L’implémentation Python de la tâche cron du serveur dans le scénario d’architecture Applications serveur + API

# Applications serveur + API : implémentation Python pour la tâche cron

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Dans le cadre du [Scénario d’architecture serveur + API](/fr-CA/docs/get-started/architecture-scenarios/server-application-api), nous expliquerons comment mettre en œuvre le processus serveur en Python. Veuillez consulter le document [Scénario d’architecture serveur + API](/fr-CA/docs/get-started/architecture-scenarios/server-application-api) pour en savoir plus sur la solution mise en œuvre.

Le code source complet de l’implémentation Python du processus serveur est disponible dans [ce dépôt GitHub](https://github.com/auth0-samples/auth0-pnp-exampleco-timesheets/tree/master/timesheets-cron/python).

<div id="get-an-access-token">
  ## Obtenir un jeton d’accès
</div>

Pour effectuer la requête HTTP vers le point de terminaison d’API Auth0 `/oauth/token`, nous utiliserons les bibliothèques `json`, `urllib` et `urllib2`.

Voici notre exemple d’implémentation :

export const codeExample = `def main():
  import json, urllib, urllib2, httplib

  # Valeurs de configuration
  domain = "{yourDomain}" # Votre domaine Auth0
  api_identifier = "API_IDENTIFIER" # Identifiant API de votre API
  client_id = "{yourClientId}" # ID client de votre Machine to Machine Application
  client_secret = "{yourClientSecret}" # Secret client de votre Machine to Machine Application
  api_url = "http://localhost:8080/timesheets/upload"
  grant_type = "client_credentials" # flux OAuth 2.0 à utiliser

  # Récupérer un jeton d’accès auprès d’Auth0
  base_url = "https://{domain}".format(domain=domain)
  data = urllib.urlencode({'client_id': client_id,
                            'client_secret': client_secret,
                            'audience': api_identifier,
                            'grant_type': grant_type})
  req = urllib2.Request(base_url + "/oauth/token", data, headers={"Accept": "application/x-www-form-urlencoded"})
  response = urllib2.urlopen(req)
  resp_body = response.read()
  oauth = json.loads(resp_body)
  access_token = oauth['access_token']

# Code standard pour appeler la fonction main().
if __name__ == '__main__':
  main()`;

<AuthCodeBlock children={codeExample} language="python" />

Pour tester cela, modifiez votre code pour afficher la variable `access_token`, puis exécutez la commande `python cron.py`.

<div id="invoke-the-api">
  ## Appeler l’API
</div>

Les étapes de notre implémentation sont les suivantes :

* Construire un objet JSON contenant les données de la feuille de temps et l’affecter à une variable `timesheet`.
* Ajouter l’URL de l’API et le contenu de la variable `timesheet` au corps de la requête à l’aide de `urllib2.Request`.
* Ajouter l’en-tête `Authorization` à la requête.
* Définir l’en-tête `Content-Type` sur `application/json`.
* Appeler l’API à l’aide de `urllib2.urlopen` et prévoir une gestion des erreurs. Récupérer la réponse à l’aide de `json.loads` et l’afficher dans la console.

Voici notre exemple d’implémentation (une partie du code est omise par souci de concision) :

```python lines expandable theme={null}
def main():
  # importer les bibliothèques - code omis

  # Valeurs de configuration - code omis

  # Obtenir un jeton d'accès depuis Auth0 - code omis

  #Soumettre une nouvelle feuille de temps à l'API
  timesheet = {'user_id': '007',
                          'date': '2017-05-10T17:40:20.095Z',
                          'project': 'StoreZero',
                          'hours': 5}
  req = urllib2.Request(api_url, data = json.dumps(timesheet))
  req.add_header('Authorization', 'Bearer ' + access_token)
  req.add_header('Content-Type', 'application/json')

  try:
    response = urllib2.urlopen(req)
    res = json.loads(response.read())
    print 'Created timesheet ' + str(res['id']) + ' for employee ' + str(res['user_id'])
  except urllib2.HTTPError, e:
    print 'HTTPError = ' + str(e.code) + ' ' + str(e.reason)
  except urllib2.URLError, e:
    print 'URLError = ' + str(e.reason)
  except httplib.HTTPException, e:
    print 'HTTPException'
  except Exception, e:
    print 'Generic Exception' + str(e)

# Code standard pour appeler la fonction main() - code omis
```

Pour tester ceci, assurez-vous que votre API est en cours d’exécution, puis lancez le processus à l’aide de `python cron.py`.

C'est tout ! Vous avez terminé !
