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

# Server Apps + API: cron ジョブ向け Python 実装

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

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

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

## アクセストークンを取得する

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

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

これを試すには、コードを修正して `access_token` 変数を出力するようにし、`python cron.py` を使って実行します。

## API を呼び出す

実装で行う手順は次のとおりです。

* timesheet データを含む 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` を実行してください。

以上です！これで完了です！
