[PYWEB] Dictionary to dataclass model

routes.py
@pages.route("/add", methods=["GET", "POST"])
def add_movie():
    form = MovieForm()

    if form.validate_on_submit():
        movie = {
            "_id", uuid.uuid4().hex,
            "title", form.title.data,
            "director", form.director.data,
            "year", form.year.data,
        }

        current_app.db.movie.insert_one(movie)

        return redirect(url_for(".index"))

    return render_template(
        "new_movie.html", title="Movies Watchlist - Add Movie", form=form
    )
routes.py
@pages.route("/add", methods=["GET", "POST"])
def add_movie():
    form = MovieForm()

    if form.validate_on_submit():
        movie = Movie(
            _id=uuid.uuid4().hex,
            title=form.title.data,
            director=form.director.data,
            year=form.year.data,
        )

        current_app.db.movie.insert_one(asdict(movie))

        return redirect(url_for(".index"))

    return render_template(
        "new_movie.html", title="Movies Watchlist - Add Movie", form=form
    )
models.py
from dataclasses import dataclass, field
from datetime import datetime


@dataclass
class Movie:
    _id: str
    title: str
    director: str
    year: int
    cast: list[str] = field(default_factory=list)
    series: list[str] = field(default_factory=list)
    last_watched: datetime = None
    rating: int = 0
    tags: list[str] = field(default_factory=list)
    description: str = None
    video_link: str = None

To add data to MongoDB, create a dictionary from form data and insert it directly

Using a model (here with dataclass) makes it easy to add default values.

Just use the Movie constructor and remember to call asdict() to turn it to a dictionary!

Potential problems:

1. Difficult to add default values for fields.

2. Changing the dictionary may require changes in multiple places (e.g. if you have more endpoints handling them).

3. Later on if you want to add methods to movies, you can only do it with a class.

Here using Flask-WTF

powered byLogosnappify