A craftsman is forging glowing souls into eternal crystals in a workshop filled with stardust and energy.
Python Lesson 8: From Portal Architect to Soul Forger
As a "Portal Architect," you have successfully connected two dimensions. But you soon discover a cruel truth: your backend world suffers from "Amnesia." Every time the portal restarts, all visitors, messages, and history vanish, and the world returns to chaos. Today, you will achieve ultimate professional ascension, becoming a Soul Forger. Your mission is to build a "Memory Core" (database) for this world, learning to forge fleeting "data souls" (Python objects) into eternal, indestructible "memory crystals" (database records).
ORM and Data Models
Communicating with the database directly using SQL, this "ancient dragon language," is not only obscure and difficult to understand but also prone to errors. Soul Forgers do not speak dragon language. We use a more advanced magic—ORM (Object-Relational Mapper).
ORM is your "Soul Translation Altar." It can automatically translate your familiar, vibrant "Python souls" (class
objects) into structured "ancient tablets" (SQL tables) that the database can understand. SQLAlchemy is one of the most powerful altars in existence.
Every class
you define becomes a "soul's" "DNA Blueprint." It precisely describes what "attributes" (name, age, message content) this soul possesses; these attributes will be forged into "inscriptions" (columns of the data table) on the memory crystal.
Engine & Session
To begin forging, you need two essential artifacts. The first is the database Engine. It is the "energy conduit" connecting your magic workshop to the "World Memory Core" (database file). It is responsible for establishing a stable and efficient connection.
The second, and most important, is the Session. This is your "alchemy forge." All soul operations—creation, modification, query, deletion—will not immediately affect the World Memory Core. They will first take place on this safe, temporary forge. This gives you the opportunity to change your mind. Only when you are satisfied with all operations and utter the final spell, session.commit()
, will all changes on the forge be written to the World Memory Core atomically and at once, becoming eternal. This "transactional" operation is the ultimate rule for ensuring data consistency.
CRUD
As a Soul Forger, you must master four basic forging rituals:
- Create: You summon a new Python soul (create a
class
instance), then usesession.add()
to place it on the forge, ready to be forged. - Read: Using specific spells (such as
session.query().all()
orsession.get()
), you "summon" one or more memory crystals from the World Memory Core and restore them into living Python souls for your use. - Update: You summon a soul to the forge, directly modify its attributes (
user.name = "New Name"
), and then utter thecommit
spell, and its memory crystal will be recast. - Delete: You place a soul on the forge, utter the
session.delete()
spell, and its memory crystal will turn to dust after yourcommit
, being completely erased from the World Memory.
Injecting a Memory Core into the "Time-Space Message Board"
We will upgrade the message board from Lesson 7 to give it eternal memory.
Core Spells (app.py
):
from flask import Flask, render_template, request, redirect, url_for
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.orm import sessionmaker, DeclarativeBase
import datetime
# --- Soul's DNA Blueprint ---
class Base(DeclarativeBase):
pass
class Message(Base):
__tablename__ = 'messages' # Memory crystal storage (table name)
id = Column(Integer, primary_key=True)
author = Column(String(50))
content = Column(String(200))
timestamp = Column(DateTime, default=datetime.datetime.now)
# --- Forge Construction ---
# Establish the energy conduit to the World Memory Core (a file named 'guestbook.db')
engine = create_engine('sqlite:///guestbook.db')
Base.metadata.create_all(engine) # Automatically create if the storage does not exist
# Create the "mold" for the alchemy forge
Session = sessionmaker(bind=engine)
app = Flask(__name__)
# --- Combining Portal and Forging Rituals ---
@app.route('/')
def index():
session = Session() # Use a new forge for each request
# Read ritual: Summon all memory crystals and sort them in reverse chronological order
all_messages = session.query(Message).order_by(Message.timestamp.desc()).all()
session.close() # Ritual ends, close the forge
return render_template('index.html', messages=all_messages)
@app.route('/post', methods=['POST'])
def post():
session = Session()
# Creation ritual: Summon a new "message" soul based on visitor input
new_message = Message(
author=request.form['author'],
content=request.form['content']
)
session.add(new_message) # Place it on the forge
session.commit() # Utter the spell, forge it into eternity!
session.close()
return redirect(url_for('index'))
# index.html template needs corresponding modification to loop and display all_messages
# if __name__ == '__main__': ... (omitted)
Your "Persistent State Mindset"
Soul Forger, congratulations! You have mastered the ultimate secret to building dynamic, stateful, memorable applications. Your thinking has leaped from creating "disposable tools" to building "living beings that can record their own history."
You have mastered the core mental model in backend development: Persistent State Mindset. You no longer create ephemeral services, but digital lives that can transcend time and accumulate value.
Now, go forge those immortal souls that can traverse the torrent of time!
Top comments (0)