Yesterday, I wrote about tweaking my Cloudflare cache purge serverless function to increase my cache rate by selectively purging URLs. After publishing that post, I realized the function I wrote wouldn’t cover existing posts that were updated.

Today, I reworked the function to grab any updated content files from the latest GitHub commit. With those file names, the function builds additional URLs to purge. With this new function, the following pages will be purged from Cloudflare cache after each deployment to Netlify.

  • The home page
  • The first few index pages
  • The archive page
  • The RSS feed
  • The sitemap
  • Any existing pages that were updated.
import json
import requests

def clear_cloudflare_cache_urls(request):
	## GitHub credentials
	gh_username = "bwhli"
	gh_token = "API_KEY"
	gh_repos_url = f"{gh_token}"
	gh_session = requests.Session()
	gh_session.auth = (gh_username, gh_token)

	#Load latest GitHub commit.
	commit = json.loads(gh_session.get(gh_repos_url).text)

	## data
	domain = ""

	## Cloudflare credentials
	cf_url = ""
	## Create list of URLs to purge.
	cache_purge_url_list = [ f"{domain}/", f"{domain}/page/2/", f"{domain}/page/3/", f"{domain}/page/4/", f"{domain}/page/5/", f"{domain}/index.xml", f"{domain}/sitemap.xml" ]
	#Add changed URLs from last commit.
	for x in range(len(commit["files"])):
		changed_file = commit["files"][x]["filename"]
		if changed_file[0:7] == "content": #only match files in content folder...
			changed_file_url = f"{domain}/{changed_file[29:-3]}/"
			if requests.get(changed_file_url).status_code == 200:

	## Build curl request to purge CF cache.
	for url in cache_purge_url_list[0:2]:
		headers = {
	    	"X-Auth-Email": "[email protected]",
	    	"X-Auth-Key": "API_KEY",
	    	"Content-Type": "application/json"
		payload = "{ \"files\": [ \"" + str(url) + "\" ] }"
		r =, headers=headers, data=payload)

Let’s see how this works over the next few weeks!