Files
flask_blog/edit_script/edit_entry.ipynb
2026-03-15 13:03:01 +01:00

6.0 KiB

In [7]:
# git entry and print
def get_entry(file_path, id):
    # 1. Import the current list to get the latest ID
    # use a namespace to avoid path issues
    namespace = {}

    with open(file_path, "r") as f:
        exec(f.read(), namespace)

        posts = namespace.get("BLOG_POSTS", [])

    for items in posts:
        if items.get("id") == id:
            content = items.get("content")
            print(content)
            return items


def update_entry(file_path, post_id, new_content):
    # 1. Load the existing data into memory
    namespace = {}
    with open(file_path, "r") as f:
        exec(f.read(), namespace)

    posts = namespace.get("BLOG_POSTS", [])

    # 2. Find and update the specific post
    found = False
    for post in posts:
        if post.get("id") == post_id:
            post["content"] = new_content
            # Optional: Update the date or add an "updated" field
            # post['subtitle'] += " (Updated)"
            found = True
            break

    if not found:
        print(f"Error: Post {post_id} not found.")
        return

    # 3. Write the entire list back to the file
    # Using repr() or a loop to format it cleanly
    with open(file_path, "w") as f:
        f.write("BLOG_POSTS = [\n")
        for p in posts:
            # Use .get() to provide a default value if the key is missing
            display_val = p.get("displayall", False)
            data_val = p.get("date", "?")
            subtitle_val = p.get("subtitle", "")

            entry = f"""    {{
                'id': {p["id"]},
                'title': "{p["title"]}",
                'subtitle': "{subtitle_val}",
                'date': "{data_val}",
                'content': \"\"\"{p["content"]}\"\"\",
                "displayall": {display_val}
            }},\n"""
            f.write(entry)
        f.write("]\n")

    print(f"Post {post_id} updated successfully.")
In [8]:
import datetime
FIELDS = ['title', 'subtitle', 'content', 'displayall']
# id is incremental
def add_entry(file_path, title, subtitle, content, display_all=False):
    # 1. Import the current list to get the latest ID
    # We use a namespace to avoid path issues
    namespace = {}
    with open(file_path, 'r') as f:
        exec(f.read(), namespace)
    
    posts = namespace.get('BLOG_POSTS', [])
    new_id = max([p['id'] for p in posts], default=0) + 1
    print("new id", new_id)
    # 2. Format the new entry string
    date_str = datetime.datetime.now().strftime("%B %d, %Y")
    
    new_post_str = f"""
    {{
        'id': {new_id},
        'title': '{title}',
        'content': \"\"\"
          {content}
\"\"\",
        'subtitle': '{subtitle}',
        'date': '{date_str}',
        "displayall": {display_all}
    }},
    """

    # 3. Append to the file
    # Note: This appends to the END of the file. 
    # If your file ends with ']', we need to strip that first.
    with open(file_path, 'r+') as f:
        content_full = f.read().strip()
        # Find the last closing bracket of the list
        if content_full.endswith(']'):
            content_full = content_full.rsplit(']', 1)[0]
        
        f.seek(0)
        f.write(content_full + new_post_str + "\n]")
        f.truncate()

    print(f"Successfully added Post #{new_id}: {title}")
In [9]:
FIEL_PATH = "../content/posts.py"
get_entry(FIEL_PATH, 10)
# update_entry(FIEL_PATH, target_id, new_text)
# add_entry(FIEL_PATH, "title", "subtitle", new_text)
text="""I have been fighting with tailwind 
& bootstrap for past two days... It was easy to write a standalone 
web page with a few lines under tailwind or bootstrap, but not with the 
combination of both. I had the nice timeline in first 2 minutes, and 
then made 60+ hopeless commits for the font and spacing behavior under 
bootstrap...
"""
#add_entry(FIEL_PATH, "test timeline", "subtitle", text)
update_entry(FIEL_PATH, 10, text)
have been fighting with tailwind & boostrap for hours...

Post 10 updated successfully.