{"id":13538698,"url":"https://github.com/cloudflare/python-cloudflare","last_synced_at":"2025-04-02T05:31:38.650Z","repository":{"id":38206495,"uuid":"57865095","full_name":"cloudflare/python-cloudflare","owner":"cloudflare","description":"Python wrapper for the Cloudflare Client API v4","archived":false,"fork":true,"pushed_at":"2024-05-02T02:55:09.000Z","size":921,"stargazers_count":668,"open_issues_count":6,"forks_count":157,"subscribers_count":25,"default_branch":"master","last_synced_at":"2024-05-02T06:17:59.791Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"cloudflare-api/python-cloudflare-v4","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cloudflare.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2016-05-02T04:03:10.000Z","updated_at":"2024-05-01T15:54:45.000Z","dependencies_parsed_at":"2023-01-21T14:04:53.916Z","dependency_job_id":null,"html_url":"https://github.com/cloudflare/python-cloudflare","commit_stats":{"total_commits":583,"total_committers":38,"mean_commits":"15.342105263157896","dds":0.2864493996569468,"last_synced_commit":"a8872852966b4ff4674cf3c9682adf209417d48f"},"previous_names":[],"tags_count":102,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudflare%2Fpython-cloudflare","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudflare%2Fpython-cloudflare/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudflare%2Fpython-cloudflare/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudflare%2Fpython-cloudflare/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cloudflare","download_url":"https://codeload.github.com/cloudflare/python-cloudflare/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246763805,"owners_count":20829795,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T09:01:14.928Z","updated_at":"2025-04-02T05:31:33.638Z","avatar_url":"https://github.com/cloudflare.png","language":"Python","funding_links":[],"categories":["Python","\u003ca id=\"9eee96404f868f372a6cbc6769ccb7f8\"\u003e\u003c/a\u003e工具"],"sub_categories":["\u003ca id=\"31185b925d5152c7469b963809ceb22d\"\u003e\u003c/a\u003e新添加的"],"readme":"# cloudflare-python\n\n\u003e [!WARNING]\n\u003e Soon there will be two Python packages for accessing Cloudflare's API.\n\u003e\n\u003e 1. This original [package](https://github.com/cloudflare/python-cloudflare), which was initially introduced [here](https://blog.cloudflare.com/python-cloudflare/).\n\u003e 2. A ground-up rewrite of the SDK, released under `3.*`, at some point in the future. See [here](https://github.com/cloudflare/python-cloudflare/discussions/191)\n\u003e\n\u003e If you like using this package in it's present form, it is highly recommended that you pin to the `2.*` releases now.\n\u003e\n\u003e ```bash\n\u003e $ cat ${YOUR_PROJECT}/requirements.txt\n\u003e cloudflare==2.19.*\n\u003e $\n\u003e ```\n\u003e\n\u003e For manual upgrades; the following will work cleanly:\n\u003e ```bash\n\u003e $ pip install --upgrade cloudflare==2.19.*\n\u003e ...\n\u003e Successfully installed cloudflare-2.19.4\n\u003e $\n\n\u003e [!WARNING]\n\u003e Release `2.20.*` is now available and it will produce a warning message explaining all this via stderr (the standard error output).\n\u003e This messages does not stop the program from operating, it's just a warning.\n\u003e If you wish to surpress this message (which is a bad idea because pinning to `2.19.*` is the right thing to do), then do the following in your code:\n\u003e ```python\n\u003e     cf = CloudFlare.CloudFlare(..., warnings=False)\n\u003e ```\n\u003e Or, if you use `cli4`, then the following.\n\u003e ```bash\n\u003e $ cli4 -w False ...\n\u003e```\n\n\u003e [!WARNING]\n\u003e Release `3.*` will not be code-compatible/call-compatible with previous releases (i.e. release `1.*` and `2.*`).\n\nWhen you see this README complete change you will know that `3.*` has been released; however, until then, this code will be released under a `2.19.*` release number.\n\n## Package stats\n\n[![Downloads](https://static.pepy.tech/badge/cloudflare)](https://pepy.tech/project/cloudflare)\n[![Downloads](https://static.pepy.tech/badge/cloudflare/month)](https://pepy.tech/project/cloudflare)\n[![Downloads](https://static.pepy.tech/badge/cloudflare/week)](https://pepy.tech/project/cloudflare)\n[![Downloads](https://static.pepy.tech/badge/cloudflare/week)](https://pepy.tech/project/cloudflare)\n[![Downloads](https://img.shields.io/pypi/pyversions/cloudflare.svg)](https://pepy.tech/project/cloudflare)\n\n## Instant how-to-use example\n\nIf you want to call the following API call:\n```\n    https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{dns_record_id}\n```\n\nIt would translates to the following Python code:\n```python\n    results = cf.zones.dns_records(zone_id, dns_record_id)\n```\n\nMany more examples are below and/or in the `examples` folder.\n\n## Installation\n\nTwo methods are provided to install this software.\nUse PyPi (see [package](https://pypi.python.org/pypi/cloudflare) details) or GitHub (see [package](https://github.com/cloudflare/python-cloudflare) details).\n\n### Via PyPI\n\n```bash\n$ sudo pip install cloudflare\n$\n```\n\nYes - that simple! (the sudo may not be needed in some cases).\n\n### Via github\n\n```bash\n$ git clone https://github.com/cloudflare/python-cloudflare\n$ cd python-cloudflare\n$ ./setup.py build\n$ sudo ./setup.py install\n$\n```\n\nOr whatever variance of that you want to use.\nThere is a Makefile included.\n\n## Cloudflare name change - dropping the capital F\n\nIn Sepember/October 2016 the company modified its company name and dropped the capital F.\nHowever, for now (and for backward compatibility reasons) the class name stays the same.\n\n## Cloudflare API version 4\n\nThe Cloudflare API can be found [here](https://api.cloudflare.com/).\nEach API call is provided via a similarly named function within the **CloudFlare** class.\nA full list is provided below.\n\n## Example code\n\nAll example code is available on GitHub (see [package](https://github.com/cloudflare/python-cloudflare) in the [examples](https://github.com/cloudflare/python-cloudflare/tree/master/examples) folder).\n\n## Blog\n\nThis package was initially introduced [here](https://blog.cloudflare.com/python-cloudflare/) via Cloudflare's [blog](https://blog.cloudflare.com/).\n\n## Getting Started\n\nA very simple listing of zones within your account; including the IPv6 status of the zone.\n\n```python\nimport CloudFlare\n\ndef main():\n    cf = CloudFlare.CloudFlare()\n    zones = cf.zones.get()\n    for zone in zones:\n        zone_id = zone['id']\n        zone_name = zone['name']\n        print(\"zone_id=%s zone_name=%s\" % (zone_id, zone_name))\n\nif __name__ == '__main__':\n    main()\n```\n\nThis example works when there are less than 50 zones (50 is the default number of values returned from a query like this).\n\nNow lets expand on that and add code to show the IPv6 and SSL status of the zones. Lets also query 100 zones.\n\n```python\nimport CloudFlare\n\ndef main():\n    cf = CloudFlare.CloudFlare()\n    zones = cf.zones.get(params = {'per_page':100})\n    for zone in zones:\n        zone_id = zone['id']\n        zone_name = zone['name']\n\n        settings_ssl = cf.zones.settings.ssl.get(zone_id)\n        ssl_status = settings_ssl['value']\n\n        settings_ipv6 = cf.zones.settings.ipv6.get(zone_id)\n        ipv6_status = settings_ipv6['value']\n\n        print(\"zone_id=%s zone_name=%s\" % (zone_id, zone_name))\n        print(\"ssl_status=%s ipv6_status=%s\" % (ssl_status, ipv6_status))\n\nif __name__ == '__main__':\n    main()\n```\n\nIn order to query more than a single page of zones, we would have to use the raw mode (described more below).\nWe can loop over many get calls and pass the page parameter to facilitate the paging.\n\nRaw mode is only needed when a get request has the possibility of returning many items.\n\n```python\nimport CloudFlare\n\ndef main():\n    cf = CloudFlare.CloudFlare(raw=True)\n    page_number = 0\n    while True:\n        page_number += 1\n        raw_results = cf.zones.get(params={'per_page':5,'page':page_number})\n        zones = raw_results['result']\n\n        for zone in zones:\n            zone_id = zone['id']\n            zone_name = zone['name']\n            print(\"zone_id=%s zone_name=%s\" % (zone_id, zone_name))\n\n        total_pages = raw_results['result_info']['total_pages']\n        if page_number == total_pages:\n            break\n\nif __name__ == '__main__':\n    main()\n```\n\nA more complex example follows.\n\n```python\nimport CloudFlare\n\ndef main():\n    zone_name = 'example.com'\n\n    cf = CloudFlare.CloudFlare()\n\n    # query for the zone name and expect only one value back\n    try:\n        zones = cf.zones.get(params = {'name':zone_name,'per_page':1})\n    except CloudFlare.exceptions.CloudFlareAPIError as e:\n        exit('/zones.get %d %s - api call failed' % (e, e))\n    except Exception as e:\n        exit('/zones.get - %s - api call failed' % (e))\n\n    if len(zones) == 0:\n        exit('No zones found')\n\n    # extract the zone_id which is needed to process that zone\n    zone_id = zones[0]['id']\n\n    # request the DNS records from that zone\n    try:\n        dns_records = cf.zones.dns_records.get(zone_id)\n    except CloudFlare.exceptions.CloudFlareAPIError as e:\n        exit('/zones/dns_records.get %d %s - api call failed' % (e, e))\n\n    # print the results - first the zone name\n    print(\"zone_id=%s zone_name=%s\" % (zone_id, zone_name))\n\n    # then all the DNS records for that zone\n    for dns_record in dns_records:\n        r_name = dns_record['name']\n        r_type = dns_record['type']\n        r_value = dns_record['content']\n        r_id = dns_record['id']\n        print('\\t', r_id, r_name, r_type, r_value)\n\n    exit(0)\n\nif __name__ == '__main__':\n    main()\n```\n\n## Providing Cloudflare Username and API Key\n\nWhen you create a **CloudFlare** class you can pass some combination of these four core parameters.\n\n * `email` - The account email (only if an API Key is being used)\n * `api` - The API Key (if coding prior to Issue-114 being merged)\n * `token` - The API Token (if coding after to Issue-114)\n * `certtoken` - Optional Origin-CA Certificate Token\n\nThis parameter controls how the data is returned from a successful call (see notes below).\n\n * `raw` - An optional Raw flag (True/False) - defaults to False\n\nTimeouts (10s) and Retries (5) are configured by default. Should you wish to override them, use these settings:\n* `global_request_timeout` - How long before each API call to Cloudflare should time out (in seconds)\n* `max_requests_retries` - How many times to retry an API call when DNS lookups, socket connections, or connect timeouts occur.\n\n\u003e NOTE: `max_request_retries` is only available when `use_sessions` is not disabled.\n\nThe following paramaters are for debug and/or development usage\n\n * `debug` - An optional Debug flag (True/False) - defaults to False\n * `use_sessions` - An optional Use-Sessions flag (True/False) - defaults to True\n * `profile` - An optional Profile name (the default is `Cloudflare`)\n * `base_url` - An optional Base URL (only used for development)\n\nemail=None, key=None, token=None, certtoken=None, debug=False, raw=False, use_sessions=True, profile=None, base_url=None):\n\n### Issue-114\n\nAfter [Issue-114](https://github.com/cloudflare/python-cloudflare/issues/114) was coded and merged, the use of `token` and `key` changed; however, is backward compatible (amazingly!).\n\nIf you are using only the API Token, then don't include the API Email. If you are coding prior to Issue-114, then the API Key can also be used as an API Token if the API Email is not used.\n\n### Python code to create class\n\n```python\nimport CloudFlare\n\n# A minimal call - reading values from environment variables or configuration file\ncf = CloudFlare.CloudFlare()\n\n# A minimal call with debug enabled\ncf = CloudFlare.CloudFlare(debug=True)\n\n# An authenticated call using an API Token (note the missing email)\ncf = CloudFlare.CloudFlare(token='00000000000000000000000000000000')\n\n# An authenticated call using an API Email and API Key\ncf = CloudFlare.CloudFlare(email='user@example.com', key='00000000000000000000000000000000')\n\n# An authenticated call using an API Token and CA-Origin info\ncf = CloudFlare.CloudFlare(token='00000000000000000000000000000000', certtoken='v1.0-...')\n\n# An authenticated call using an API Email, API Key, and CA-Origin info\ncf = CloudFlare.CloudFlare(email='user@example.com', key='00000000000000000000000000000000', certtoken='v1.0-...')\n\n# An authenticated call using using a stored profile (see below)\ncf = CloudFlare.CloudFlare(profile=\"CompanyX\"))\n```\n\nIf the account email and API key are not passed when you create the class, then they are retrieved from either the users exported shell environment variables or the .cloudflare.cfg or ~/.cloudflare.cfg or ~/.cloudflare/cloudflare.cfg files, in that order.\n\nIf you're using an API Token, any `cloudflare.cfg` file must either not contain an `email` and `key` attribute (or they can be zero length strings) and the `CLOUDFLARE_EMAIL` `CLOUDFLARE_API_KEY` environment variable must be unset (or zero length strings), otherwise the token (`CLOUDFLARE_API_TOKEN` or `token` attribute) will not be used.\n\nThere is one call that presently doesn't need any email or token certification (the */ips* call); hence you can test without any values saved away.\n\n### Using shell environment variables\n\nNote (for latest version of code):\n\n * `CLOUDFLARE_EMAIL` has replaced `CF_API_EMAIL`.\n * `CLOUDFLARE_API_KEY` has replaced `CF_API_KEY`.\n * `CLOUDFLARE_API_TOKEN` has replaced `CF_API_TOKEN`.\n * `CLOUDFLARE_API_CERTKEY` has replaced `CF_API_CERTKEY`.\n\nAdditionally, these two variables are available for testing purposes:\n\n * `CLOUDFLARE_API_EXTRAS` has replaced `CF_API_EXTRAS`.\n * `CLOUDFLARE_API_URL` has replaced `CF_API_URL`.\n\nThe older environment variable names can still be used.\n\n```bash\n$ export CLOUDFLARE_EMAIL='user@example.com'\n$ export CLOUDFLARE_API_KEY='00000000000000000000000000000000'\n$ export CLOUDFLARE_API_CERTKEY='v1.0-...'\n$\n```\n\nOr if using API Token.\n\n```bash\n$ export CLOUDFLARE_API_TOKEN='00000000000000000000000000000000'\n$ export CLOUDFLARE_API_CERTKEY='v1.0-...'\n$\n```\nThese are optional environment variables; however, they do override the values set within a configuration file.\n\n### Using configuration file to store email and keys\n\nThe default profile name is `Cloudflare` for obvious reasons.\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n[Cloudflare]\nemail = user@example.com # Do not set if using an API Token\nkey = 00000000000000000000000000000000\ncerttoken = v1.0-...\nextras =\n$\n```\n\nMore than one profile can be stored within that file.\nHere's an example for a work and home setup (in this example work has an API Token and home uses email/key).\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n[Work]\ntoken = 00000000000000000000000000000000\n[Home]\nemail = home@example.com\nkey = 00000000000000000000000000000000\n$\n```\n\nTo select a profile, use the `--profile profile-name` option for `cli4` command or use `profile=\"profile-name\"` in the library call.\n\n```bash\n$ cli4 --profile Work /zones | jq '.[]|.name' | wc -l\n      13\n$\n\n$ cli4 --profile Home /zones | jq '.[]|.name' | wc -l\n       1\n$\n```\n\nHere is the same in code.\n\n```python\n#!/usr/bin/env python\n\nimport CloudFlare\n\ndef main():\n    cf = CloudFlare.CloudFlare(profile=\"Work\")\n    ...\n```\n\n### Passing your own HTTP headers to API calls\n\nThere are very specific case where a user of the library needs to add custom headers to all HTTP calls.\nThis is rarly needed.\n\nThe addition headers can be passed via the confuration file as follows:\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n...\nhttp_headers =\n        X-Header1:value\n        X-Header2: value1 value2 value3\n        X-Header3: \"this is life as we know it\"\n        X-Header4: 'two single quotes'\n        X-Header5:\n...\n$\n```\nEach line should have a header noun, a colon, and a verb.\n\nYou can also pass these via Python calls.\n```python\n    import CloudFlare\n\n    http_headers = [\n        'X-Header1:value',\n        'X-Header2: value1 value2 value3',\n        'X-Header3: \"this is life as we know it\"',\n        'X-Header4: \\'two single quotes\\'',\n        'X-Header5:',\n    ]\n    cf = CloudFlare.CloudFlare(http_headers=http_headers)\n...\n```\n\nThese header values can also be passed via `cli4` command (many times) - use the `-v` option to see the debug messages:\n```\n$ cli4 -v --header 'X-something:' --header 'X-whatever:whatever' /zones \u003e /tmp/results.json\n...\n            --header \"X-something: \" \\\n            --header \"X-whatever: whatever \" \\\n...\n$\n```\n\n### Advanced use of configuration file for authentication based on method\n\nThe configuration file can have values that are both generic and specific to the method.\nHere's an example where a project has a different API Token for reading and writing values.\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n[Work]\ntoken = 0000000000000000000000000000000000000000\ntoken.get = 0123456789012345678901234567890123456789\n$\n```\n\nWhen a GET call is processed then the second token is used. For all other calls the first token is used.\nHere's a more explict verion of that config:\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n[Work]\ntoken.delete = 0000000000000000000000000000000000000000\ntoken.get = 0123456789012345678901234567890123456789\ntoken.patch = 0000000000000000000000000000000000000000\ntoken.post = 0000000000000000000000000000000000000000\ntoken.put = 0000000000000000000000000000000000000000\n$\n```\n\nThis can be used with email values also.\n\n### About /certificates and certtoken\n\nThe *CLOUDFLARE_API_CERTKEY* or *certtoken* values are used for the Origin-CA */certificates* API calls.\nYou can leave *certtoken* in the configuration with a blank value (or omit the option variable fully).\n\nThe *extras* values are used when adding API calls outside of the core codebase.\nTechnically, this is only useful for internal testing within Cloudflare.\nYou can leave *extras* in the configuration with a blank value (or omit the option variable fully).\n\n## Exceptions and return values\n\n### Response data\n\nThe response is build from the JSON in the API call.\nIt contains the **results** values; but does not contain the paging values.\n\nYou can return all the paging values by calling the class with raw=True. Here's an example without paging.\n\n```python\n#!/usr/bin/env python\n\nimport json\nimport CloudFlare\n\ndef main():\n    cf = CloudFlare.CloudFlare()\n    zones = cf.zones.get(params={'per_page':5})\n    print(\"len=%d\" % (zones.length()))\n\nif __name__ == '__main__':\n    main()\n```\n\nThe results are as follows.\n\n```\n5\n```\n\nWhen you add the raw option; the APIs full structure is returned. This means the paging values can be seen.\n\n```python\n#!/usr/bin/env python\n\nimport json\nimport CloudFlare\n\ndef main():\n    cf = CloudFlare.CloudFlare(raw=True)\n    zones = cf.zones.get(params={'per_page':5})\n    print(\"len=%d\" % (zones.length()))\n    print(json.dumps(zones, indent=4, sort_keys=True))\n\nif __name__ == '__main__':\n    main()\n```\n\nThis produces.\n\n```\n5\n{\n    \"result\": [\n        ...\n    ],\n    \"result_info\": {\n        \"count\": 5,\n        \"page\": 1,\n        \"per_page\": 5,\n        \"total_count\": 31,\n        \"total_pages\": 7\n    }\n}\n```\n\nA full example of paging is provided below.\n\n### Exceptions\n\nThe library will raise **CloudFlareAPIError** when the API call fails.\nThe exception returns both an integer and textual message in one value.\n\n```python\nimport CloudFlare\n\n    ...\n    try\n        r = ...\n    except CloudFlare.exceptions.CloudFlareAPIError as e:\n        exit('api error: %d %s' % (e, e))\n    ...\n```\n\nThe other raised response is **CloudFlareInternalError** which can happen when calling an invalid method.\n\nIn some cases more than one error is returned. In this case the return value `e` is also an array.\nYou can iterate over that array to see the additional error.\n\n```python\nimport sys\nimport CloudFlare\n\n    ...\n    try\n        r = ...\n    except CloudFlare.exceptions.CloudFlareAPIError as e:\n        if len(e) \u003e 0:\n            sys.stderr.write('api error - more than one error value returned!\\n')\n            for x in e:\n                sys.stderr.write('api error: %d %s\\n' % (x, x))\n        exit('api error: %d %s' % (e, e))\n    ...\n```\n\n### Exception handling\n\nHere's code using the CLI command `cli4` of the responses passed back in exceptions.\n\nFirst a simple get with a clean (non-error) response.\n\n```bash\n$ cli4 /zones/:example.com/dns_records | jq -c '.[]|{\"name\":.name,\"type\":.type,\"content\":.content}'\n{\"name\":\"example.com\",\"type\":\"MX\",\"content\":\"something.example.com\"}\n{\"name\":\"something.example.com\",\"type\":\"A\",\"content\":\"10.10.10.10\"}\n$\n```\n\nNext a simple/single error response.\nThis is simulated by providing incorrect authentication information.\n\n```bash\n$ CLOUDFLARE_EMAIL='someone@example.com' cli4 /zones/\ncli4: /zones - 9103 Unknown X-Auth-Key or X-Auth-Email\n$\n```\n\nMore than one call can be done on the same command line. In this mode, the connection is preserved between calls.\n\n```bash\n$ cli4 /user/organizations /user/invites\n...\n$\n```\nNote that the output is presently two JSON structures one after the other - so less useful that you may think.\n\nFinally, a command that provides more than one error response.\nThis is simulated by passing an invalid IPv4 address to a DNS record creation.\n\n```bash\n$ cli4 --post name='foo' type=A content=\"NOT-A-VALID-IP-ADDRESS\" /zones/:example.com/dns_records\ncli4: /zones/:example.com/dns_records - 9005 Content for A record is invalid. Must be a valid IPv4 address\ncli4: /zones/:example.com/dns_records - 1004 DNS Validation Error\n$\n```\n\n## Included example code\n\nThe [examples](https://github.com/cloudflare/python-cloudflare/tree/master/examples) folder contains many examples in both simple and verbose formats.\n\nYou can see the installed path of these files directly via `cli4 -e` (or `cli4 --examples`) command.\n\n```bash\n$ cli4 -e\nPython .py files:\n\t...\n\t/opt/homebrew/lib/python3.11/site-packages/examples/example_always_use_https.py\n\t...\nBash .sh files:\n\t...\n\t/opt/homebrew/lib/python3.11/site-packages/examples/example_paging_thru_zones.sh\n\t...\n$\n```\n\nThe exact path will vary depending on your system.\nThe above example is MacOS and Python 3.9 hence the `/opt/homebrew/lib/python3.11/site-packages/` path.\nOne Linux, the Python pip command may install the code is a system location like `/usr/lib/python3/dist-packages` or `~/.local/lib/python3.9/site-packages/` or something different.\nThe `cli4 -e` command will try to decode the location and display the example files.\n\nIf you are running release before Python 3.9 then you will be asked to install the following:\n\n```bash\n$ pip install importlib_resources\n...\n$\n```\n\nIt will show up if you are running on an older system. For example, this is the results from running on Win7:\n\n```bash\nU:\\Users\\Bobby\u003ecli4 -e\nModule \"importlib_resources\" missing - please \"pip install importlib_resources\" as your Python version is lower than 3.9\n\nU:\\Users\\Bobby\u003epython -V\nPython 3.8.3\n\nU:\\Users\\Bobby\u003e\n```\n\nUpgrading from an older version of Python is always recommended. Upgrading from Win7 is by-default even more important!\n\n## A DNS zone code example\n\n```python\n#!/usr/bin/env python\n\nimport sys\nimport CloudFlare\n\ndef main():\n    zone_name = sys.argv[1]\n    cf = CloudFlare.CloudFlare()\n    zone_info = cf.zones.post(data={'jump_start':False, 'name': zone_name})\n    zone_id = zone_info['id']\n\n    dns_records = [\n        {'name':'foo', 'type':'AAAA', 'content':'2001:d8b::1'},\n        {'name':'foo', 'type':'A', 'content':'192.168.0.1'},\n        {'name':'duh', 'type':'A', 'content':'10.0.0.1', 'ttl':120},\n        {'name':'bar', 'type':'CNAME', 'content':'foo'},\n        {'name':'shakespeare', 'type':'TXT', 'content':\"What's in a name? That which we call a rose by any other name ...\"}\n    ]\n\n    for dns_record in dns_records:\n        r = cf.zones.dns_records.post(zone_id, data=dns_record)\n    exit(0)\n\nif __name__ == '__main__':\n    main()\n```\n\n## A DNS zone delete code example (be careful)\n\n```python\n#!/usr/bin/env python\n\nimport sys\nimport CloudFlare\n\ndef main():\n    zone_name = sys.argv[1]\n    cf = CloudFlare.CloudFlare()\n    zone_info = cf.zones.get(params={'name': zone_name})\n    zone_id = zone_info[0]['id']\n\n    dns_name = sys.argv[2]\n    dns_records = cf.zones.dns_records.get(zone_id, params={'name':dns_name + '.' + zone_name})\n    for dns_record in dns_records:\n        dns_record_id = dns_record['id']\n        r = cf.zones.dns_records.delete(zone_id, dns_record_id)\n    exit(0)\n\nif __name__ == '__main__':\n    main()\n```\n\n## CLI\n\nAll API calls can be called from the command line via the `cli4` command.\nAdditionally, the `cli4` command will convert domain name or account name prefixed with a colon (`:`) into the correct identifier.\ne.g. to view `example.com` you can use `cli4 /zones/:example.com`.\nYou can pass the zone identifier (or account identifier or any identifier) with a colon followed by the identifier as a hex number 32 characters long.\n\n```bash\n$ cli4 [-V|--version] [-h|--help] [-v|--verbose] \\\n    [-e|--examples] \\\n    [-q|--quiet] \\\n    [-j|--json] [-y|--yaml] [-n|--ndjson] [-i|--image] \\\n    [-r|--raw] \\\n    [-d|--dump] \\\n    [-A|--openapi url] \\\n    [-b|--binary] \\\n    [-p|--profile profile-name] \\\n    [-h|--header additional-header] \\\n    [-w|--warnings [True|False]] \\\n    [--get|--patch|--post|--put|--delete] \\\n    [item=value|item=@filename|@filename ...] /command ...\n```\n\n### CLI parameters for POST/PUT/PATCH\n\nFor API calls that need to pass data or parameters there is various formats to use.\n\nThe simplest form is `item=value`. This passes the value as a string within the APIs JSON data.\n\nIf you need a numeric value passed then `==` can be used to force the value to be treated as a numeric value within the APIs JSON data.\nFor example: `item==value`.\n\nif you need to pass a list of items; then `[]` can be used. For example:\n\n```bash\npool_id1=\"11111111111111111111111111111111\"\npool_id2=\"22222222222222222222222222222222\"\npool_id3=\"33333333333333333333333333333333\"\ncli4 --post global_pools=\"[ ${pool_id1}, ${pool_id2}, ${pool_id3} ]\" region_pools=\"[ ]\" /user/load_balancers/maps\n```\n\nData or parameters can be either named or unnamed.\nIt can not be both.\nNamed is the majority format; as described above.\nUnnamed parameters simply don't have anything before the `=` sign, as in `=value`.\nThis format is presently only used by the Cloudflare Load Balancer API calls.\nFor example:\n\n```bash\ncli4 --put =\"00000000000000000000000000000000\" /user/load_balancers/maps/:00000000000000000000000000000000/region/:WNAM\n```\n\nData can also be uploaded from file contents. Using the `item=@filename` format will open the file and the contents uploaded in the POST.\n\n### CLI output\n\nThe default output from the CLI command is in JSON.\nIt can also output YAML format (i.e. human readable).\nThis is controled by the `--yaml` or `--json` flags (JSON is the default).\nThere is also a `--ndjson` flag for use with line based JSON data - this is mainly used for log data.\n\nAdditonally the output can be plain text or binary image format depending on the results from the API call (some calls results in non JSON results).\nThe `--image` flag will return the data in the same format as the API's results.\n\n### Simple CLI calls\n\n * `cli4 /user/billing/profile`\n * `cli4 /user/invites`\n\n * `cli4 /zones/:example.com`\n * `cli4 /zones/:example.com/dnssec`\n * `cli4 /zones/:example.com/settings/ipv6`\n * `cli4 --put /zones/:example.com/activation_check`\n * `cli4 /zones/:example.com/keyless_certificates`\n\n * `cli4 /zones/:example.com/analytics/dashboard`\n\n### More complex CLI calls\n\nHere is the creation of a DNS entry, followed by a listing of that entry and then the deletion of that entry.\n\n```bash\n$ $ cli4 --post name=\"test\" type=\"A\" content=\"10.0.0.1\" /zones/:example.com/dns_records\n{\n    \"id\": \"00000000000000000000000000000000\",\n    \"name\": \"test.example.com\",\n    \"type\": \"A\",\n    \"content\": \"10.0.0.1\",\n    ...\n}\n$\n\n$ cli4 /zones/:example.com/dns_records/:test.example.com | jq '{\"id\":.id,\"name\":.name,\"type\":.type,\"content\":.content}'\n{\n  \"id\": \"00000000000000000000000000000000\",\n  \"name\": \"test.example.com\",\n  \"type\": \"A\",\n  \"content\": \"10.0.0.1\"\n}\n\n$ cli4 --delete /zones/:example.com/dns_records/:test.example.com | jq -c .\n{\"id\":\"00000000000000000000000000000000\"}\n$\n```\n\nThere's the ability to handle dns entries with multiple values.\nThis produces more than one API call within the command.\n\n```bash\n$ cli4 /zones/:example.com/dns_records/:test.example.com | jq -c '.[]|{\"id\":.id,\"name\":.name,\"type\":.type,\"content\":.content}'\n{\"id\":\"00000000000000000000000000000000\",\"name\":\"test.example.com\",\"type\":\"A\",\"content\":\"192.168.0.1\"}\n{\"id\":\"00000000000000000000000000000000\",\"name\":\"test.example.com\",\"type\":\"AAAA\",\"content\":\"2001:d8b::1\"}\n$\n```\n\nHere are the cache purging commands.\n\n```bash\n$ cli4 --delete purge_everything=true /zones/:example.com/purge_cache | jq -c .\n{\"id\":\"00000000000000000000000000000000\"}\n$\n\n$ cli4 --delete files='[http://example.com/css/styles.css]' /zones/:example.com/purge_cache | jq -c .\n{\"id\":\"00000000000000000000000000000000\"}\n$\n\n$ cli4 --delete files='[http://example.com/css/styles.css,http://example.com/js/script.js]' /zones/:example.com/purge_cache | jq -c .\n{\"id\":\"00000000000000000000000000000000\"}\n$\n\n$ cli4 --delete tags='[tag1,tag2,tag3]' /zones/:example.com/purge_cache | jq -c .\ncli4: /zones/:example.com/purge_cache - 1107 Only enterprise zones can purge by tag.\n$\n```\n\nA somewhat useful listing of available plans for a specific zone.\n\n```bash\n$ cli4 /zones/:example.com/available_plans | jq -c '.[]|{\"id\":.id,\"name\":.name}'\n{\"id\":\"00000000000000000000000000000000\",\"name\":\"Pro Website\"}\n{\"id\":\"00000000000000000000000000000000\",\"name\":\"Business Website\"}\n{\"id\":\"00000000000000000000000000000000\",\"name\":\"Enterprise Website\"}\n{\"id\":\"0feeeeeeeeeeeeeeeeeeeeeeeeeeeeee\",\"name\":\"Free Website\"}\n$\n```\n\n### Cloudflare CA CLI calls\n\nHere's some Cloudflare CA calls. Note the need of the `zone_id=` parameter with the basic `/certificates` call.\n\n```bash\n$ cli4 /zones/:example.com | jq -c '.|{\"id\":.id,\"name\":.name}'\n{\"id\":\"12345678901234567890123456789012\",\"name\":\"example.com\"}\n$\n\n$ cli4 zone_id=12345678901234567890123456789012 /certificates | jq -c '.[]|{\"id\":.id,\"expires_on\":.expires_on,\"hostnames\":.hostnames,\"certificate\":.certificate}'\n{\"id\":\"123456789012345678901234567890123456789012345678\",\"expires_on\":\"2032-01-29 22:36:00 +0000 UTC\",\"hostnames\":[\"*.example.com\",\"example.com\"],\"certificate\":\"-----BEGIN CERTIFICATE-----\\n ... \"}\n{\"id\":\"123456789012345678901234567890123456789012345678\",\"expires_on\":\"2032-01-28 23:23:00 +0000 UTC\",\"hostnames\":[\"*.example.com\",\"example.com\"],\"certificate\":\"-----BEGIN CERTIFICATE-----\\n ... \"}\n{\"id\":\"123456789012345678901234567890123456789012345678\",\"expires_on\":\"2032-01-28 23:20:00 +0000 UTC\",\"hostnames\":[\"*.example.com\",\"example.com\"],\"certificate\":\"-----BEGIN CERTIFICATE-----\\n ... \"}\n$\n```\n\nA certificate can be viewed via a simple GET request.\n\n```bash\n$ cli4 /certificates/:123456789012345678901234567890123456789012345678\n{\n    \"certificate\": \"-----BEGIN CERTIFICATE-----\\n ... \",\n    \"expires_on\": \"2032-01-29 22:36:00 +0000 UTC\",\n    \"hostnames\": [\n        \"*.example.com\",\n        \"example.com\"\n    ],\n    \"id\": \"123456789012345678901234567890123456789012345678\",\n    \"request_type\": \"origin-rsa\"\n}\n$\n```\n\nCreating a certificate. This is done with a `POST` request. Note the use of `==` in order to pass a decimal number (vs. string) in JSON. The CSR is not shown for simplicity sake.\n\n```bash\n$ CSR=`cat example.com.csr`\n$ cli4 --post hostnames='[\"example.com\",\"*.example.com\"]' requested_validity==365 request_type=\"origin-ecc\" csr=\"$CSR\" /certificates\n{\n    \"certificate\": \"-----BEGIN CERTIFICATE-----\\n ... \",\n    \"csr\": \"-----BEGIN CERTIFICATE REQUEST-----\\n ... \",\n    \"expires_on\": \"2018-09-27 21:47:00 +0000 UTC\",\n    \"hostnames\": [\n        \"*.example.com\",\n        \"example.com\"\n    ],\n    \"id\": \"123456789012345678901234567890123456789012345678\",\n    \"request_type\": \"origin-ecc\",\n    \"requested_validity\": 365\n}\n$\n```\n\nDeleting a certificate can be done with a `DELETE` call.\n\n```bash\n$ cli4 --delete /certificates/:123456789012345678901234567890123456789012345678\n{\n    \"id\": \"123456789012345678901234567890123456789012345678\",\n    \"revoked_at\": \"0000-00-00T00:00:00Z\"\n}\n$\n```\n\n### Paging CLI calls\n\nThe `--raw` command provides access to the paging returned values.\nSee the API documentation for all the info.\nHere's an example of how to page thru a list of zones (it's included in the examples folder as `example_paging_thru_zones.sh`).\nNote the use of `==` to pass a number vs a string as paramater.\n\n```bash\n:\ntmp=/tmp/$$_\ntrap \"rm ${tmp}; exit 0\" 0 1 2 15\nPAGE=0\nwhile true\ndo\n        cli4 --raw per_page==5 page==${PAGE} /zones \u003e ${tmp}\n        domains=`jq -c '.|.result|.[]|.name' \u003c ${tmp} | tr -d '\"'`\n        result_info=`jq -c '.|.result_info' \u003c ${tmp}`\n        COUNT=`      echo \"${result_info}\" | jq .count`\n        PAGE=`       echo \"${result_info}\" | jq .page`\n        PER_PAGE=`   echo \"${result_info}\" | jq .per_page`\n        TOTAL_COUNT=`echo \"${result_info}\" | jq .total_count`\n        TOTAL_PAGES=`echo \"${result_info}\" | jq .total_pages`\n        echo COUNT=${COUNT} PAGE=${PAGE} PER_PAGE=${PER_PAGE} TOTAL_COUNT=${TOTAL_COUNT} TOTAL_PAGES=${TOTAL_PAGES} -- ${domains}\n        if [ \"${PAGE}\" == \"${TOTAL_PAGES}\" ]\n        then\n                ## last section\n                break\n        fi\n        # grab the next page\n        PAGE=`expr ${PAGE} + 1`\ndone\n```\n\nIt produces the following results.\n\n```bash\nCOUNT=5 PAGE=1 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- accumsan.example auctor.example consectetur.example dapibus.example elementum.example\nCOUNT=5 PAGE=2 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- felis.example iaculis.example ipsum.example justo.example lacus.example\nCOUNT=5 PAGE=3 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- lectus.example lobortis.example maximus.example morbi.example pharetra.example\nCOUNT=5 PAGE=4 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- porttitor.example potenti.example pretium.example purus.example quisque.example\nCOUNT=5 PAGE=5 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- sagittis.example semper.example sollicitudin.example suspendisse.example tortor.example\nCOUNT=1 PAGE=7 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- varius.example vehicula.example velit.example velit.example vitae.example\nCOUNT=5 PAGE=6 PER_PAGE=5 TOTAL_COUNT=31 TOTAL_PAGES=7 -- vivamus.example\n```\n\n### Paging thru lists (using cursors)\n\nSome API calls use cursors to read beyond the initally returned values. See the API page in order to see which API calls do this.\n\n```bash\n$ ACCOUNT_ID=\"00000000000000000000000000000000\"\n$ LIST_ID=\"00000000000000000000000000000000\"\n$\n$ cli4 --raw /accounts/::${ACCOUNT_ID}/rules/lists/::${LIST_ID}/items \u003e /tmp/page1.json\n$ after=`jq -r '.result_info.cursors.after' \u003c /tmp/page1.json`\n$ echo \"after=$after\"\nafter=Mxm4GVmKjYbFjy2VxMPipnJigm1M_s6lCS9ABR9wx-RM2A\n$\n```\n\nOnce we have the `after` value, we can pass it along in order to read the next hunk of values. We finish when `after` returns as null (or isn't present).\n\n```bash\n$ cli4 --raw cursor=\"$after\" /accounts/::${ACCOUNT_ID}/rules/lists/::${LIST_ID}/items \u003e /tmp/page2.json\n$ after=`jq -r '.result_info.cursors.after' \u003c /tmp/page2.json`\n$ echo \"after=$after\"\nafter=null\n$\n```\n\nWe can see the results now in two files.\n\n```bash\n$ jq -c '.result[]' \u003c /tmp/page1.json | wc -l\n      25\n$\n\n$ jq -c '.result[]' \u003c /tmp/page2.json | wc -l\n       5\n$\n\n$ for f in /tmp/page?.json ; do jq -r '.result[]|.id,.ip,.comment' \u003c $f | paste - - - ; done | column -s'   ' -t\n0fe44928258549feb47126a966fbf4a0  0.0.0.0           all zero\n2e1e02120f5e466f8c0e26375e4cf4c8  1.0.0.1           Cloudflare DNS a\n9ca5fd0ac6f54fdbb9dedd3fb72ce2da  1.1.1.1           Cloudflare DNS b\nb3654987446743738c782f36ebe074f5  10.0.0.0/8        RFC1918 space\n90bec8ce37d242faa2e27d1e78c1d8e2  103.21.244.0/22   Cloudflare IP\n970a3c810cda41af9bef2c36a1892f7e  103.22.200.0/22   Cloudflare IP\n3ec8516158bf4f3cac18210f611ee541  103.31.4.0/22     Cloudflare IP\nee9d268367204e6bb8e5e4c907f22de8  104.16.0.0/12     Cloudflare IP\n93ae02eda9774c45840af367a02fe529  108.162.192.0/18  Cloudflare IP\n62891ebf6db44aa494d79a6401af185e  131.0.72.0/22     Cloudflare IP\ncac40cd940cc470582b8c912a8a12bea  141.101.64.0/18   Cloudflare IP\nf6d5eacd81a2407f8e0d81caee21e7f8  162.158.0.0/15    Cloudflare IP\n3d538dfc38ab471d9d3fe78332acfa4e  172.16.0.0/12     RFC1918 space\nf353cb8f98424837ad35382a22b9debe  172.64.0.0/13     Cloudflare IP\n78f3e1a0bafc41f88d4d40ad49a642e0  173.245.48.0/20   Cloudflare IP\nc23a545475c54c32a7681c6b508d3e80  188.114.96.0/20   Cloudflare IP\nf693237c9e294fe481221cbc2d7c20ef  190.93.240.0/20   Cloudflare IP\n6d465ab3a0994c07827ebdcf8f34d977  192.168.0.0/16    RFC1918 space\n1ad1e634b3664bac939086185c62faf7  197.234.240.0/22  Cloudflare IP\n5d2968e7b3114d8e869a379d71c8ba86  198.41.128.0/17   Cloudflare IP\n6a69de60b31448fa864f0a3ac5abe8d0  224.0.0.0/24      Multicast\n30749cce89af4ab3a80e308294f46a46  240.0.0.0/4       Class E\n2b32c67ea4d044628abe39f28662d8f0  255.255.255.255   all ones\ncc7cd828b2fb4bcfb9391c2d3ef8d068  2400:cb00::/32    Cloudflare IP\nb30d4cbd7dcd48729e8ebeda552e48a8  2405:8100::/32    Cloudflare IP\n49db60758c8344959c338a74afc9748a  2405:b500::/32    Cloudflare IP\n96e9eca1923c40d5a84865145f5a5d6a  2606:4700::/32    Cloudflare IP\n21bc52a26e10405d89b7180ddcf49302  2803:f800::/32    Cloudflare IP\nff78f842188e4b869eb5389ae9ab8f41  2a06:98c0::/29    Cloudflare IP\n0880cdfc40b14f6fa0639522a728859d  2c0f:f248::/32    Cloudflare IP\n$\n```\n\nThe `result_info.cursors` area also contains a `before` value for reverse scrolling.\n\nAs with `per_page` scrolling, raw mode is used.\n\n### DNSSEC CLI calls\n\n```bash\n$ cli4 /zones/:example.com/dnssec | jq -c '{\"status\":.status}'\n{\"status\":\"disabled\"}\n$\n\n$ cli4 --patch status=active /zones/:example.com/dnssec | jq -c '{\"status\":.status}'\n{\"status\":\"pending\"}\n$\n\n$ cli4 /zones/:example.com/dnssec\n{\n    \"algorithm\": \"13\",\n    \"digest\": \"41600621c65065b09230ebc9556ced937eb7fd86e31635d0025326ccf09a7194\",\n    \"digest_algorithm\": \"SHA256\",\n    \"digest_type\": \"2\",\n    \"ds\": \"example.com. 3600 IN DS 2371 13 2 41600621c65065b09230ebc9556ced937eb7fd86e31635d0025326ccf09a7194\",\n    \"flags\": 257,\n    \"key_tag\": 2371,\n    \"key_type\": \"ECDSAP256SHA256\",\n    \"modified_on\": \"2016-05-01T22:42:15.591158Z\",\n    \"public_key\": \"mdsswUyr3DPW132mOi8V9xESWE8jTo0dxCjjnopKl+GqJxpVXckHAeF+KkxLbxILfDLUT0rAK9iUzy1L53eKGQ==\",\n    \"status\": \"pending\"\n}\n$\n```\n\n### Zone file upload (i.e. import) CLI calls (uses BIND format files)\n\nRefer to [Import DNS records](https://api.cloudflare.com/#dns-records-for-a-zone-import-dns-records) on API documentation for this feature.\n\n```bash\n$ cat zone.txt\nexample.com.            IN      SOA     somewhere.example.com. someone.example.com. (\n                                2017010101\n                                3H\n                                15\n                                1w\n                                3h\n                        )\n\nrecord1.example.com.    IN      A       10.0.0.1\nrecord2.example.com.    IN      AAAA    2001:d8b::2\nrecord3.example.com.    IN      CNAME   record1.example.com.\nrecord4.example.com.    IN      TXT     \"some text\"\n$\n\n$ cli4 --post file=@zone.txt /zones/:example.com/dns_records/import\n{\n    \"recs_added\": 4,\n    \"total_records_parsed\": 4\n}\n$\n```\n\n### Zone file upload (i.e. import) Python calls (uses BIND format files)\n\nBecause `import` is a keyword (or reserved word) in Python we append a `_` (underscore) to the verb in order to use.\nThe `cli4` command does not need this edit.\n\n```python\n    #\n    # \"import\" is a reserved word and hence we add '_' to the end of verb.\n    #\n    r = cf.zones.dns_records.import_.post(zone_id, files={'file':fd})\n```\n\nSee [examples/example_dns_import.py](https://github.com/cloudflare/python-cloudflare/tree/master/examples/example_dns_import.py) for working code.\n\n### Zone file download (i.e. export) CLI calls (uses BIND format files)\n\nThe following is documented within the **Advanced** option of the DNS page within the Cloudflare portal.\n\n```bash\n$ cli4 /zones/:example.com/dns_records/export | egrep -v '^;;|^$'\n$ORIGIN .\n@       3600    IN      SOA     example.com.    root.example.com.       (\n                2025552311      ; serial\n                7200            ; refresh\n                3600            ; retry\n                86400           ; expire\n                3600)           ; minimum\nexample.com.    300     IN      NS      REPLACE\u0026ME$WITH^YOUR@NAMESERVER.\nrecord4.example.com.    300     IN      TXT     \"some text\"\nrecord3.example.com.    300     IN      CNAME   record1.example.com.\nrecord1.example.com.    300     IN      A       10.0.0.1\nrecord2.example.com.    300     IN      AAAA    2001:d8b::2\n$\n```\n\nThe egrep is used for documentation brevity.\n\nThis can also be done via Python code with the following example.\n\n```python\n#!/usr/bin/env python\nimport sys\nimport CloudFlare\n\ndef main():\n    zone_name = sys.argv[1]\n    cf = CloudFlare.CloudFlare()\n\n    zones = cf.zones.get(params={'name': zone_name})\n    zone_id = zones[0]['id']\n\n    dns_records = cf.zones.dns_records.export.get(zone_id)\n    for l in dns_records.splitlines():\n        if len(l) == 0 or l[0] == ';':\n            continue\n        print(l)\n    exit(0)\n\nif __name__ == '__main__':\n    main()\n```\n\n### Cloudflare Workers\n\nCloudflare Workers are described on the Cloudflare blog at\n[here](https://blog.cloudflare.com/introducing-cloudflare-workers/) and\n[here](https://blog.cloudflare.com/code-everywhere-cloudflare-workers/), with the beta release announced\n[here](https://blog.cloudflare.com/cloudflare-workers-is-now-on-open-beta/).\n\nThe Python libraries now support the Cloudflare Workers API calls. The following javascript is lifted from [https://cloudflareworkers.com/](https://cloudflareworkers.com/) and slightly modified.\n\n```bash\n$ cat modify-body.js\naddEventListener(\"fetch\", event =\u003e {\n  event.respondWith(fetchAndModify(event.request));\n});\n\nasync function fetchAndModify(request) {\n  console.log(\"got a request:\", request);\n\n  // Send the request on to the origin server.\n  const response = await fetch(request);\n\n  // Read response body.\n  const text = await response.text();\n\n  // Modify it.\n  const modified = text.replace(\n  \"\u003cbody\u003e\",\n  \"\u003cbody style=\\\"background: #ff0;\\\"\u003e\");\n\n  // Return modified response.\n  return new Response(modified, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers\n  });\n}\n$\n```\n\nHere's the website with it's simple `\u003cbody\u003e` statement\n\n```bash\n$ curl -sS https://example.com/ | fgrep '\u003cbody'\n  \u003cbody\u003e\n$\n```\n\nNow lets add the script. Looking above, you will see that it's simple action is to modify the `\u003cbody\u003e` statement and make the background yellow.\n\n```bash\n$ cli4 --put @- /zones/:example.com/workers/script \u003c modify-body.js\n{\n    \"etag\": \"1234567890123456789012345678901234567890123456789012345678901234\",\n    \"id\": \"example-com\",\n    \"modified_on\": \"2018-02-15T00:00:00.000000Z\",\n    \"script\": \"addEventListener(\\\"fetch\\\", event =\u003e {\\n  event.respondWith(fetchAndModify(event.request));\\n});\\n\\nasync function fetchAndModify(request) {\\n  console.log(\\\"got a request:\\\", request);\\n\\n  // Send the request on to the origin server.\\n  const response = await fetch(request);\\n\\n  // Read response body.\\n  const text = await response.text();\\n\\n  // Modify it.\\n  const modified = text.replace(\\n  \\\"\u003cbody\u003e\\\",\\n  \\\"\u003cbody style=\\\\\\\"background: #ff0;\\\\\\\"\u003e\\\");\\n\\n  // Return modified response.\\n  return new Response(modified, {\\n    status: response.status,\\n    statusText: response.statusText,\\n    headers: response.headers\\n  });\\n}\\n\",\n    \"size\": 603\n}\n$\n```\n\nThe following call checks that the script is associated with the zone. In this case, it's the only script added by this user.\n\n```bash\n$ cli4 /user/workers/scripts\n[\n    {\n        \"created_on\": \"2018-02-15T00:00:00.000000Z\",\n        \"etag\": \"1234567890123456789012345678901234567890123456789012345678901234\",\n        \"id\": \"example-com\",\n        \"modified_on\": \"2018-02-15T00:00:00.000000Z\"\n    }\n]\n$\n```\n\nNext step is to make sure a route is added for that script on that zone.\n\n```bash\n$ cli4 --post pattern=\"example.com/*\" script=\"example-com\" /zones/:example.com/workers/routes\n{\n    \"id\": \"12345678901234567890123456789012\"\n}\n$\n\n$ cli4 /zones/:example.com/workers/routes\n[\n    {\n        \"id\": \"12345678901234567890123456789012\",\n        \"pattern\": \"example.com/*\",\n        \"script\": \"example-com\"\n    }\n]\n$\n```\n\nWith that script added to the zone and the route added, we can now see the website has been modified because of the Cloudflare Worker.\n\n```bash\n$ curl -sS https://example.com/ | fgrep '\u003cbody'\n  \u003cbody style=\"background: #ff0;\"\u003e\n$\n```\n\nAll this can be removed; hence bringing the website back to its initial state.\n\n```bash\n$ cli4 --delete /zones/:example.com/workers/script\n12345678901234567890123456789012\n$ cli4 --delete /zones/:example.com/workers/routes/:12345678901234567890123456789012\ntrue\n$\n\n$ curl -sS https://example.com/ | fgrep '\u003cbody'\n  \u003cbody\u003e\n$\n```\n\nRefer to the Cloudflare Workers API documentation for more information.\n\n## Cloudflare Instant Logs\n\nPlease see https://developers.cloudflare.com/logs/instant-logs for all the information on how to use this feature.\nThe `cli4` command along with the Python libaries can be used to control the instant logs; however, the websocket reading is outside the scope of this library.\n\nTo query the states of the instant logs:\n\n```bash\n$ cli4 /zones/:example.com/logpush/edge/jobs | jq .\n[]\n$\n```\n\nTo add monitoring:\n\n```bash\n$ cli4 --post \\\n        ='{\n                \"fields\": \"ClientIP,ClientRequestHost,ClientRequestMethod,ClientRequestURI,EdgeEndTimestamp,EdgeResponseBytes,EdgeResponseStatus,EdgeStartTimestamp,RayID\",\n                \"sample\": 1,\n                \"filter\": \"\",\n                \"kind\": \"instant-logs\"\n        }' \\\n        /zones/:example.com/logpush/edge/jobs | jq .\n{\n  \"destination_conf\": \"wss://logs.cloudflare.com/instant-logs/ws/sessions/00000000000000000000000000000000\",\n  \"fields\": \"ClientIP,ClientRequestHost,ClientRequestMethod,ClientRequestURI,EdgeEndTimestamp,EdgeResponseBytes,EdgeResponseStatus,EdgeStartTimestamp,RayID\",\n  \"filter\": \"\",\n  \"kind\": \"instant-logs\",\n  \"sample\": 1,\n  \"session_id\": \"00000000000000000000000000000000\"\n}\n$\n```\n\nTo see the results:\n\n```bash\n$ cli4 /zones/:example.com/logpush/edge/jobs | jq .\n[\n  {\n    \"fields\": \"ClientIP,ClientRequestHost,ClientRequestMethod,ClientRequestURI,EdgeEndTimestamp,EdgeResponseBytes,EdgeResponseStatus,EdgeStartTimestamp,RayID\",\n    \"filter\": \"\",\n    \"kind\": \"instant-logs\",\n    \"sample\": 1,\n    \"session_id\": \"00000000000000000000000000000000\"\n  }\n]\n$\n```\n\n## Cloudflare GraphQL\n\nThe GraphQL interface can be accessed via the command line or via Python.\n\n```\n    query=\"\"\"\n      query {\n        viewer {\n            zones(filter: {zoneTag: \"%s\"} ) {\n            httpRequests1dGroups(limit:40, filter:{date_lt: \"%s\", date_gt: \"%s\"}) {\n              sum { countryMap { bytes, requests, clientCountryName } }\n              dimensions { date }\n            }\n          }\n        }\n      }\n    \"\"\" % (zone_id, date_before[0:10], date_after[0:10])\n\n    r = cf.graphql.post(data={'query':query})\n\n    httpRequests1dGroups = zone_info = r['data']['viewer']['zones'][0]['httpRequests1dGroups']\n```\n\nSee the [examples/example_graphql.sh](examples/example_graphql.sh) and [examples/example_graphql.py](https://github.com/cloudflare/python-cloudflare/tree/master/examples/example_graphql.py) files for working examples.\nHere is the working example of the shell version:\n\n```bash\n$ examples/example_graphql.sh example.com\n2020-07-14T02:00:00Z    34880\n2020-07-14T03:00:00Z    18953\n2020-07-14T04:00:00Z    28700\n2020-07-14T05:00:00Z    2358\n2020-07-14T06:00:00Z    34905\n2020-07-14T07:00:00Z    779\n2020-07-14T08:00:00Z    35450\n2020-07-14T10:00:00Z    17803\n2020-07-14T11:00:00Z    32678\n2020-07-14T12:00:00Z    19947\n2020-07-14T13:00:00Z    4956\n2020-07-14T14:00:00Z    34585\n2020-07-14T15:00:00Z    3022\n2020-07-14T16:00:00Z    5224\n2020-07-14T18:00:00Z    79482\n2020-07-14T21:00:00Z    10609\n2020-07-14T22:00:00Z    5740\n2020-07-14T23:00:00Z    2545\n2020-07-15T01:00:00Z    10777\n$\n```\n\nFor more information on how to use GraphQL at Cloudflare, refer to the [Cloudflare GraphQL Analytics API](https://developers.cloudflare.com/analytics/graphql-api).\nIt contains a full overview of Cloudflare's GraphQL features and keywords.\n\n## Cloudflare AI\n\nSee https://blog.cloudflare.com/workers-ai-update-stable-diffusion-code-llama-workers-ai-in-100-cities/ for the introduction,\nalong with https://developers.cloudflare.com/workers-ai/models/ for the nitty gritty details.\n\nThere are three AI calls included within the example folder.\n\n### Image creation.\n\n```bash\n$ python examples/example_ai_images.py A happy llama running through an orange cloud \u003e /tmp/image.png\n$\n$ file /tmp/image.png\n/tmp/image.png: PNG image data, 1024 x 1024, 8-bit/color RGB, non-interlaced\n$\n```\n\n### Translation.\n\n```bash\n$ python examples/example_ai_translate.py I\\'ll have an order of the moule frites\nJe vais avoir une commande des frites de moule\n$\n```\n\n### Speech Recognition with the openai/whisper model.\n\nThe following downloads a speech as an mp3 file and passes it to the AI API.\nIt does a very good job transcribing; however, there's a good chance these mp3 files were use for training.\nThat said, the example code is here to show how the API works vs testing the AI/ML quality.\n\n```bash\n$ python examples/example_ai_speechrecognition.py\nmp3 received: length=700367\nMy fellow Americans, Michelle and I have been so touched by all the well wishes that we've received over the past few weeks. But tonight, tonight it's my turn to say thanks.\n$\n```\n\nThis is presently work-in-progress because of the non-Python calling method. The syntax could change in the future.\n\nThey can also be called via `cli4`.\n\n```bash\n$ cli4 --image --post text=\"I'll have an order of the moule frites\" source_lang=english target_lang=french /accounts/:AccountID/ai/run/@cf/meta/m2m100-1.2b\n{'translated_text': 'Je vais avoir une commande des frites de moule'}\n$\n```\n\nPresently you will need the following in your `cloudflare.cfg` file.\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n[CloudFlare]\nglobal_request_timeout = 120\nmax_request_retries = 1\nextras =\n    /accounts/:id/ai/run/@cf/meta/llama-2-7b-chat-fp16\n    /accounts/:id/ai/run/@cf/meta/llama-2-7b-chat-int8\n    /accounts/:id/ai/run/@cf/mistral/mistral-7b-instruct-v0.1\n    /accounts/:id/ai/run/@cf/openai/whisper\n    /accounts/:id/ai/run/@cf/meta/m2m100-1.2b\n    /accounts/:id/ai/run/@cf/huggingface/distilbert-sst-2-int8\n    /accounts/:id/ai/run/@cf/microsoft/resnet-50\n    /accounts/:id/ai/run/@cf/stabilityai/stable-diffusion-xl-base-1.0\n    /accounts/:id/ai/run/@cf/baai/bge-base-en-v1.5\n    /accounts/:id/ai/run/@cf/baai/bge-large-en-v1.5\n    /accounts/:id/ai/run/@cf/baai/bge-small-en-v1.5\n\n$\n```\n\nAs the `@` (at) symbol and the `.` (dot) symbol aren't allowed in python variable names; you'll have the replace `@cf` with `at_cf` and `.` with `_`.\nThere's already notes above that state that `-` (dash) is replaced with `_` in the code.\nThat will be needed with some model names.\n\nThe `cli4` command does not need this edit. It is done on the fly!\n\nFor example, the following code is valid:\n```python\n    r = cf.accounts.ai.run.at_cf.openai.whisper.post(account_id, data=audio_data)\n    r = cf.accounts.ai.run.at_cf.meta.m2m100_1_2b.post(account_id, data=translate_data)\n    r = cf.accounts.ai.run.at_cf.stabilityai.stable_diffusion_xl_base_1_0.post(account_id, data=image_create_data)\n```\n\nOr you can use the `find()` call can will do this conversion for you.\n```python\n    translate_data = {'text':\"I'll have an order of the moule frites\", 'source_lang':'english', 'target_lang':'french'}\n\n    m = cf.find('/accounts/:id/ai/run/@cf/meta/m2m100-1.2b')\n    r = m.post(account_id, data=translate_data)\n    print(r['translated_text'])\n```\n\nYou will also have to run with a version of the library above `2.18.2`.\n\n## Implemented API calls\n\nThe `--dump` argument to cli4 will produce a list of all the call implemented within the library.\n\n```bash\n$ cli4 --dump\n/certificates\n/ips\n/organizations\n...\n/zones/ssl/analyze\n/zones/ssl/certificate_packs\n/zones/ssl/verification\n$\n```\n\n### Table of commands\n\nAn automatically generated table of commands is provided [here](TABLE-OF-COMMANDS.md).\n\n## Adding extra API calls manually\n\nExtra API calls can be added via the configuration file\n\n```bash\n$ cat ~/.cloudflare/cloudflare.cfg\n[Cloudflare]\nextras =\n    /client/v4/command\n    /client/v4/command/:command_identifier\n    /client/v4/command/:command_identifier/settings\n$\n```\n\nWhile it's easy to call anything within Cloudflare's API, it's not very useful to add items in here as they will simply return API URL errors.\nTechnically, this is only useful for internal testing within Cloudflare.\n\n## Issues\n\nThe following error can be caused by an out of date SSL/TLS library and/or out of date Python.\n\n```bash\n/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.\n  SNIMissingWarning\n/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.\n  InsecurePlatformWarning\n```\n\nThe solution can be found [here](https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning) and/or [here](http://stackoverflow.com/questions/35144550/how-to-install-cryptography-on-ubuntu).\n\n## Python 2.x vs 3.x support\n\nAs of May/June 2016 the code is now tested against pylint.\nThis was required in order to move the codebase into Python 3.x.\nThe motivation for this came from [Danielle Madeley (danni)](https://github.com/danni).\n\n~~While the codebase has been edited to run on Python 3.x, there's not been enough Python 3.x testing performed.~~\n~~If you can help in this regard; please contact the maintainers.~~\n\nAs of January 2020 the code is Python3 clean.\n\nAs of January 2020 the code is shipped up to pypi with Python2 support removed.\n\nAs of January 2020 the code is Python3.8 clean. The new `SyntaxWarning` messages (i.e. `SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?`) meant minor edits were needed.\n\nAs of late 2023 the code is Python3.11 clean.\n\nAs of April 2024 the code is officially marked as 3.x only (3.6 and above to be specific) such that it can become PEP561 specific.\n\n## pypi and GitHub signed releases\n\nAs of October/2022, the code is signed by the maintainers personal email address: `mahtin@mahtin.com` `7EA1 39C4 0C1C 842F 9D41 AAF9 4A34 925D 0517 2859`\n\n## Credit\n\nThis is based on work by [Felix Wong (gnowxilef)](https://github.com/gnowxilef) found [here](https://github.com/cloudflare-api/python-cloudflare-v4).\nIt has been seriously expanded upon.\n\n## Changelog\n\nAn automatically generated CHANGELOG is provided [here](CHANGELOG.md).\n\n## Copyright\n\nCopyright (c) 2016 thru 2024, Cloudflare. All rights reserved.\nPrevious portions copyright [Felix Wong (gnowxilef)](https://github.com/gnowxilef).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcloudflare%2Fpython-cloudflare","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcloudflare%2Fpython-cloudflare","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcloudflare%2Fpython-cloudflare/lists"}