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"https://api.github.com/repos/bwhli/brianli.com/commits/master?access_token={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)

	## BrianLi.com data
	domain = "https://brianli.com"

	## Cloudflare credentials
	cf_url = "https://api.cloudflare.com/client/v4/zones/API_KEY/purge_cache"
	
	## 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:
				cache_purge_url_list.append(changed_file_url)

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

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