Skip to content

Commit

Permalink
Adds cache busting and updating posts
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhariri committed Oct 22, 2024
1 parent 8c09161 commit e517672
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 49 deletions.
7 changes: 5 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ COPY pyproject.toml poetry.lock /usr/src/app/

# Install project dependencies
RUN poetry config virtualenvs.create false \
&& poetry install --no-interaction --no-ansi
&& poetry install --no-interaction --no-ansi --no-dev

# Copy all files
# Copy only necessary files
COPY . /usr/src/app/

# Remove cache to reduce image size
RUN rm -rf /root/.cache/pip

# Expose the application's port
EXPOSE 8000

Expand Down
13 changes: 8 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def render_not_found(_):


@app.get("/")
@cache.cached(timeout=60)
@cache.cached(timeout=3600)
def render_home():
latest_posts = get_posts()[:3]
return render_template(
Expand All @@ -41,7 +41,7 @@ def render_home():


@app.get("/blog/")
@cache.cached(timeout=60, query_string=True)
@cache.cached(timeout=3600, query_string=True)
def render_blog_index():
tag = request.args.get("tagged")
posts = get_posts()
Expand All @@ -57,7 +57,7 @@ def render_blog_index():


@app.get("/blog/<string:post_path>/")
@cache.memoize(timeout=3600)
@cache.cached(timeout=3600)
def render_blog_post(post_path: str):
try:
post = get_posts_index()[post_path]
Expand All @@ -69,7 +69,7 @@ def render_blog_post(post_path: str):

@app.get("/feed/")
@app.get("/rss/")
@cache.cached(timeout=60)
@cache.cached(timeout=3600)
def read_feed():
items = [
RSSItem(
Expand All @@ -92,7 +92,7 @@ def read_feed():


@app.get("/<string:page_path>/")
@cache.memoize(timeout=3600)
@cache.cached(timeout=3600)
def render_page(page_path: str):
try:
page = get_all_page_paths_and_pages()[page_path]
Expand Down Expand Up @@ -198,6 +198,9 @@ def micropub():
post_tweet(f"{post.description}\n\n🔗 {post_url}")
except Exception as e:
sentry_sdk.capture_exception(e)

# Clear the cache for the affected pages
cache.clear()

response = jsonify({"url": post_url})
response.status_code = 201
Expand Down
45 changes: 21 additions & 24 deletions cli.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@
import datetime
import os
import click
from werkzeug.utils import secure_filename

POST_TEMPLATE = """---
title: {title}
date: {date}
tags:
-
description:
---
"""
import requests
from config import settings

@click.command()
@click.option("--title", prompt="Enter the title of the new post", help="Title of the new post")
def create_new_post(title):
date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-5))).isoformat()
filename = secure_filename(title).replace("_", "-").lower() + ".md"
filepath = os.path.join("posts", filename)

if os.path.exists(filepath):
click.echo("A post with the same title already exists. Please choose a different title.")
return
@click.option("--content", prompt="Enter the content of the new post", help="Content of the new post")
def create_new_post(title, content):
url = f"{settings.FQD}/micropub"
headers = {
"Authorization": f"Bearer {settings.MICROPUB_SECRET}",
"Content-Type": "application/json"
}
data = {
"type": ["h-entry"],
"properties": {
"name": [title],
"content": [content]
}
}

with open(filepath, "w") as file:
file.write(POST_TEMPLATE.format(title=title, date=date))
response = requests.post(url, headers=headers, json=data)

click.echo(f"New post created at {filepath}")
if response.status_code == 201:
click.echo(f"New post created at {response.json().get('url')}")
else:
click.echo(f"Failed to create post: {response.status_code} {response.text}")

if __name__ == "__main__":
create_new_post()
48 changes: 30 additions & 18 deletions service/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,35 +79,47 @@ def create_post(title: str, content: str, tags: list[str] | None = None, descrip
messages=[
{
"role": "system",
"content": "You are a helpful assistant that generates short descriptions for blog posts."
"content": "You are a helpful assistant that replies with short, personal descriptions for blog posts. The user will provide the content in <content> tags. Keep it short, casual, first-person, and in the tone of voice of the user. For example: 'Quick notes on my interview on the Hard Part Interview podcast.' or 'I made a thing that converts your pocket saves into an rss feed'. Reply *only* with the description text and nothing else (no wrapping quotes, <description> tag etc.)."
},
{
"role": "user",
"content": f"""Generate a short description for the following blog post content:
<content>
"content": f"""<content>
{content}
</content>. For example: 'Quick notes on my interview on the Hard Part Interview podcast.' or 'I made a thing that converts your pocket saves into an rss feed'
Do not write anything else other than the description and do not wrap the description in quotes."""
</content>"""
}
],
model="gpt-4o-mini",
)
description = response.choices[0].message.content

new_post = Post(
title=title,
content=content,
url_slug=url_slug,
tags=tags,
description=description
)

post_data = new_post.model_dump()
posts_collection.insert_one(post_data)
existing_post = posts_collection.find_one({"url_slug": url_slug})

return new_post
if existing_post:
posts_collection.update_one(
{"url_slug": url_slug},
{"$set": {
"title": title,
"content": content,
"tags": tags,
"description": description,
"date_updated": _now()
}}
)
updated_post = posts_collection.find_one({"url_slug": url_slug})
return Post(**updated_post)
else:
new_post = Post(
title=title,
content=content,
url_slug=url_slug,
tags=tags,
description=description
)

post_data = new_post.model_dump()
posts_collection.insert_one(post_data)

return new_post

def delete_post(url_slug: str) -> None:
posts_collection.delete_one({"url_slug": url_slug})

0 comments on commit e517672

Please sign in to comment.