> ## 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.

> Server Client + API アーキテクチャシナリオにおけるサーバー側 cron ジョブの Python 実装

# サーバーアプリ + API: cron ジョブ向け Python 実装

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) + "*****マスク済み*****";
          }
          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>;
};

[Server + API Architecture Scenario](/ja/docs/get-started/architecture-scenarios/server-application-api) の一環として、Python でサーバープロセスを実装する方法を説明します。実装するソリューションについて詳しくは、[Server + API Architecture Scenario](/ja/docs/get-started/architecture-scenarios/server-application-api) のドキュメントを参照してください。

サーバープロセスの Python 実装の完全なソースコードは、[この GitHub リポジトリ](https://github.com/auth0-samples/auth0-pnp-exampleco-timesheets/tree/master/timesheets-cron/python) で確認できます。

<div id="get-an-access-token">
  ## アクセストークンを取得する
</div>

Auth0 の `/oauth/token` API エンドポイントに HTTP リクエストを送信するには、`json`、`urllib`、`urllib2` ライブラリを使用します。

サンプル実装は次のとおりです。

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

  # 設定値
  domain = "{yourDomain}" # ご利用の Auth0 ドメイン
  api_identifier = "API_IDENTIFIER" # API の識別子
  client_id = "{yourClientId}" # Machine-to-Machine アプリケーションのクライアントID
  client_secret = "{yourClientSecret}" # Machine-to-Machine アプリケーションのクライアントシークレット
  api_url = "http://localhost:8080/timesheets/upload"
  grant_type = "client_credentials" # 使用する OAuth 2.0 フロー

  # 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']

# main() 関数を呼び出すための標準的な定型コード。
if __name__ == '__main__':
  main()`;

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

これをテストするには、`access_token` 変数を出力するようにコードを変更し、`python cron.py` を実行します。

<div id="invoke-the-api">
  ## API を呼び出す
</div>

この実装では、次の手順を実行します。

* タイムシートデータを含む JSON オブジェクトを作成し、`timesheet` 変数に代入します。
* `urllib2.Request` を使用して、API URL と `timesheet` 変数の内容をリクエスト本文に追加します。
* リクエストに `Authorization` ヘッダーを追加します。
* `Content-Type` ヘッダーを `application/json` に設定します。
* `urllib2.urlopen` を使用して API を呼び出し、基本的なエラー処理を追加します。`json.loads` を使用してレスポンスを取得し、コンソールに出力します。

以下は実装例です (一部のコードは簡潔にするため省略しています) 。

```python lines expandable theme={null}
def main():
  # ライブラリのインポート - コード省略

  # 設定値 - コード省略

  # Auth0からアクセストークンを取得 - コード省略

  #新しいタイムシートを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)

# main()関数を呼び出す定型コード - コード省略
```

これをテストするには、API が実行中であることを確認し、`python cron.py` を実行してプロセスを開始します。

以上で完了です。
