Real Python: Model-View-Controller (MVC) in Python Web Apps: Explained With Lego

If you’re curious about web development, then you’ve likely encountered the abbreviation MVC, which stands for Model-View-Controller. You may know that it’s a common design pattern that’s fundamental to many Python web frameworks and even desktop applications.

But what exactly does it mean? If you’ve had a hard time wrapping your head around the concept, then keep on reading.

In this tutorial, you’ll:

  • Approach understanding the MVC pattern through a Lego-based analogy
  • Learn what models, views, and controllers are conceptually
  • Tie your conceptual understanding back to concrete web development examples
  • Investigate Flask code snippets to drive the point home

Maybe you built things with Lego as a kid, or maybe you’re still a Lego-aficionado today. But even if you’ve never pieced two Lego blocks together, keep on reading because the analogy might still be a good building block for your understanding.

Get Your Code: Click here to download an example Flask app that will help you understand MVC in Python web apps.

Take the Quiz: Test your knowledge with our interactive “Model-View-Controller (MVC) in Python Web Apps: Explained With Lego” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

Explaining the Model-View-Controller Pattern With Lego

Imagine that you’re ten years old and sitting on your family room floor. In front of you is a big bucket of Lego, or similar modular building blocks. There are blocks of all different shapes and sizes:

  • 🟦🟦🟦 Some are blue, tall, and long.
  • 🟥 Some are red and cube-shaped.
  • 🟨🟨 Some are yellow, big, and wide.

With all of these different Lego pieces, there’s no telling what you could build!

Just as your mind is filling with the endless possibilities, you hear something coming from the direction of the couch. It’s your older brother, voicing a specific request. He’s saying, “Hey! Build me a spaceship!”

“Alright,” you think, “that could actually be pretty cool.” A spaceship it is!

So you get to work. You start pulling out the Lego blocks that you think you’re going to need. Some big, some small. Different colors for the outside of the spaceship, different colors for the engines.

Now that you have all of your building blocks in place, it’s time to assemble the spaceship. And after a few hours of hard work, you now have in front of you—a spaceship:

                                  🟦
                                🟦🟥🟦
                              🟦🟥🟥🟥🟦
                            🟦🟥🟥🟥🟥🟥🟦
                            🟦🟥🟥🟥🟥🟥🟦
                            🟦🟥🟩🟩🟩🟥🟦
                            🟦🟥🟩🟦🟩🟥🟦
                            🟦🟥🟩🟩🟩🟥🟦
                            🟦🟥🟥🟥🟥🟥🟦
                            🟦🟥🟥🟥🟥🟥🟦
                            🟦🟥🟥🟥🟥🟥🟦
                        🟦🟥🟥🟥🟥🟥🟥🟥🟥🟥🟦
                        🟦🟥🟥🟥🟥🟥🟥🟥🟥🟥🟦
                        🟦🟥🟨🟨🟥🟥🟥🟨🟨🟥🟦
                            🟨🟨       🟨🟨

You run to find your brother and show him the finished product. “Wow, nice work!”, he says. Then he quietly adds:

Huh, I just asked for that a few hours ago, I didn’t have to do a thing, and here it is. I wish everything was that easy.

— Your Brother

What if I told you that building a web application using the MVC pattern is exactly like building something with Lego blocks?

User Sends a Request

Read the full article at https://realpython.com/lego-model-view-controller-python/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Planet Python

Database-Based Operating System ‘DBOS’ Does Things Linux Can’t

Databricks CTO Matei Zaharia "said that Databricks had to keep track of scheduling a million things," remembers adjunct MIT professor Michael Stonebraker. " He said that this can’t be done with traditional operating system scheduling, and so this was done out of a Postgres database. And then he started to whine that Postgres was too slow, and I told him we can do better than that…." This resulted in DBOS — short for "database operating system" — which they teamed up to build with teams Stanford and MIT, according to The Next Platform:
They founded a company to commercialize the idea in April 2023 and secured $8.5 million initial seed funding to start building the real DBOS. Engine Ventures and Construct Capital led the funding, along with Sinewave and GutBrain Ventures… "The state that the operating system has to keep track of — memory, files, messages, and so on — is approximately linear to the resources you have got," says Stonebraker. "So without me saying another word, keeping track of operating system state is a database problem not addressed by current operating system schedulers. Moreover, OLTP [Online Transaction Processing] database performance has gone up dramatically, and that is why we thought instead of running the database system in user space on top of the operating system, why don’t we invert our thinking 180 degrees and run the operating system on top of the database, with all of the operating services are coded in SQL…?" For now, DBOS can give the same kind of performance as that full blown Linux operating system, and thanks to the distributed database underpinnings of its kernel, it can do things that a Linux kernel just cannot do… One is provide reliable execution, which means that if a program running atop DBOS is ever interrupted, it starts where it left off and does not have to redo its work from some arbitrary earlier point and does not crash and have to start from the beginning. And because every little bit of the state of the operating system — and therefore the applications that run atop it — is preserved, you can go backwards in time in the system and restart the operating system if it experiences some sort of anomaly, such as a bad piece of application software running or a hack attack. You can use this "time travel" feature, as Stonebraker calls it, to reproduce what are called heisenbugs — ones that are very hard to reproduce precisely because there is no shared state in the distributed Linux and Kubernetes environment and that are increasingly prevalent in a world of microservices. The other benefit of the DBOS is that it presents a smaller attack surface for hackers, which boosts security, and that you analyze the metrics of the operating system in place since they are already in a NoSQL database that can be queried rather than aggregating a bunch of log files from up and down the software stack to try to figure out what is going on… There is also a custom tier for DBOS, which we presume costs money, that can use other databases and datastores for user application data, stores more than three days of log data, can have multiple users per account, that adds email and Slack support with DBOS techies, and that is available on other clouds as well as AWS. The operating system kernel/scheduler "is itself largely a database," with services written in TypeScript, according to the article. The first iteration used the FoundationDB distributed key-value store for its scheduling core (open sourced by Apple in 2018), according to the article — "a blazingly fast NoSQL database… Stonebraker says there is no reason to believe that DBOS can’t scale across 1 million cores or more and support Java, Python, and other application languages as they are needed by customers…" And the article speculates they could take things even further. "There is no reason why DBOS cannot complete the circle and not only have a database as an operating system kernel, but also have a relational database as the file system for applications."


Read more of this story at Slashdot.

Slashdot

Cognition Emerges From Stealth To Launch AI Software Engineer ‘Devin’

Longtime Slashdot reader ahbond shares a report from VentureBeat: Today, Cognition, a recently formed AI startup backed by Peter Thiel’s Founders Fund and tech industry leaders including former Twitter executive Elad Gil and Doordash co-founder Tony Xu, announced a fully autonomous AI software engineer called "Devin." While there are multiple coding assistants out there, including the famous Github Copilot, Devin is said to stand out from the crowd with its ability to handle entire development projects end-to-end, right from writing the code and fixing the bugs associated with it to final execution. This is the first offering of this kind and even capable of handling projects on Upwork, the startup has demonstrated. […]
In a blog post today on Cognition’s website, Scott Wu, the founder and CEO of Cognition and an award-winning sports coder, explained Devin can access common developer tools, including its own shell, code editor and browser, within a sandboxed compute environment to plan and execute complex engineering tasks requiring thousands of decisions. The human user simply types a natural language prompt into Devin’s chatbot style interface, and the AI software engineer takes it from there, developing a detailed, step-by-step plan to tackle the problem. It then begins the project using its developer tools, just like how a human would use them, writing its own code, fixing issues, testing and reporting on its progress in real-time, allowing the user to keep an eye on everything as it works. […]
According to demos shared by Wu, Devin is capable of handling a range of tasks in its current form. This includes common engineering projects like deploying and improving apps/websites end-to-end and finding and fixing bugs in codebases to more complex things like setting up fine-tuning for a large language model using the link to a research repository on GitHub or learning how to use unfamiliar technologies. In one case, it learned from a blog post how to run the code to produce images with concealed messages. Meanwhile, in another, it handled an Upwork project to run a computer vision model by writing and debugging the code for it. In the SWE-bench test, which challenges AI assistants with GitHub issues from real-world open-source projects, the AI software engineer was able to correctly resolve 13.86% of the cases end-to-end — without any assistance from humans. In comparison, Claude 2 could resolve just 4.80% while SWE-Llama-13b and GPT-4 could handle 3.97% and 1.74% of the issues, respectively. All these models even required assistance, where they were told which file had to be fixed. Currently, Devin is available only to a select few customers. Bloomberg journalist Ashlee Vance wrote a piece about his experience using it here.
"The Doom of Man is at hand," captions Slashdot reader ahbond. "It will start with the low-hanging Jira tickets, and in a year or two, able to handle 99% of them. In the short term, software engineers may become like bot farmers, herding 10-1000 bots writing code, etc. Welcome to the future."


Read more of this story at Slashdot.

Slashdot

Why Russia’s Weapons Suck

http://img.youtube.com/vi/bKEryR7jPnQ/0.jpg

We’ve covered some of this before, but here’s a nice roundup of why Russia’s major weapons systems suck. It’s a handy tour through the world of over-promised, under-performing vaporwear.

  • “Before February 24th, 2022, the Russian Federation looked like it would deploy or soon be able to field some pretty formidable new weapons.” At least among those who hadn’t noticed Russia’s previous vaporware claims.
  • “In everything from fifth generation fighter jets to modern tanks, to new body armor and even tsunami-causing nuclear torpedoes, there was enough hype to make even informed Western national security experts worry about what they were seeing.”
  • “Little wonder that they believed Ukraine would fall in days in the months prior to the invasion. Those predictions did not turn out to be the case. And now two years later, Russia still finds itself fighting a war of attrition with no end in sight.”
  • It covers Russia’s one aircraft carrier, the Admiral Kuznetsov, how it’s been under repairs since 2018, is markedly less technologically advanced than American carriers, and how it has a history of corruption as well. It”s supposed to enter service again this year. I wouldn’t count on it.
  • Admiral Kuznetsov isn’t Russia’s only naval problem. “It is steadily retiring its Soviet-era ships and replacing them with lighter, less combat-worthy vessels.”
  • There’s the new, formidable (on paper) Lider-class destroyers, first unveiled in 2015 and capable of using a host of advanced new weapons. Tiny problem: “On paper” is the only place you can see them, since they haven’t started building them yet.
  • Then there’s “the Belgorod submarine, and particularly its Poseidon Torpedo, are two other items of hype in the Russian Navy that don’t seem to stand up to scrutiny. The Belgorod and Poseidon have often been items of fear in Western media and national security circles, which have nicknamed the former Russia’s ‘Doomsday Submarine.’”
  • “According to the Kremlin’s hype, the submarine and its arsenal of smart drone Poseidon torpedoes can unleash a 100 megaton yield capable of creating radioactive tsunamis that would inundate coastal communities and make them unlivable.”
  • “However, tests of the Poseidon have seemingly proven less than satisfactory. That shouldn’t be too surprising, because for the Poseidon torpedo to work as the Russians claim, it would need to be able to house all of the equipment needed for a nuclear reactor to convert atomic fission into electricity and propulsive force, while ensuring negligible waste heat (to avoid detection). It would also need the hardware to shield its sensitive electronics from the nuclear fission process.”
  • “Unfortunately for Moscow, the torpedo is too small to do this, meaning that it is either an object of hype or Russian engineers have come upon a technological leap enabling exotic engineering methods. We’ll let you decide which of the two scenarios is likelier.”

  • “The likeliest scenario is a yield of about one to two megatons per torpedo, which would be enough to inundate a coastal area with dangerous radioactive waters, but not to create a tsunami.” And the hundred knot speed is also bunk for numerous technical reasons.
  • “We now journey from the sea to the skies and look at the Russian answer to the American fifth generation F-22 and F-35 fighter jets – the Su-57 Felon. To be fair, the Su-57 does have some impressive features, like its 3D thrust vectoring engines, climb rate of 64,000 feet per minute, 66,000-foot service ceiling, Mach 2 speed, and range of 2,186 miles without refueling. In a plane vs. plane battle, the Su-57 should be a capable opponent against almost any fighter jet on the planet.”
  • “However, the Su-57 has a big drawback – its comparative lack of stealth. Aviation experts regard the Su-57 as being by far the least stealthy of the fifth generation fighters currently in service. For example, the F-22 Raptor is detectable at a range only under 10 miles, while the Su-57 would be detectable at a range of 35 miles.”
  • “Its stealth features are also concentrated in the front of the plane, meaning that if it turns or maneuvers, it is far more detectable.” Good thing fighter aircraft never need to turn or maneuver…
  • “Some aviation experts are even less kind and believe the Su-57’s radar cross section is similar to that of the F/A-18 Super Hornet, which is 1,000 times less stealthy than the F-35 Lightning II.”
  • “The Su-57 has played little part in the war in Ukraine, as the Russian aerospace forces have refused to field it in Ukrainian airspace. Instead, it has only attacked targets at long range from within Russian airspace.”
  • Then there’s the ridiculously low production rate. “The Kremlin ordered 76 Su-57s in 2019. 22 are in service as of December 2023, after several years of delays.” And we only have Russia’s word that they’ve produced that many. The real total could be lower. By contrast, Lockheed Martin has produced over 1,000 F-35s.
  • Next it’s a familiar punching bag, the T-14 Armata. “To be fair, the T-14 Armata does have significant improvements over the tanks Russia has usually fielded in Ukraine – the T-72, T-80, and T-90. These tanks have been lost in their thousands during the fighting in Ukraine, thanks to bad doctrine and their own design flaws. Because they do not segregate their ammunition magazines in a sealed compartment, they have often suffered from complete destruction with jack-in-the-box explosions.”
  • “The T-14 Armata mitigates this flaw with a protective capsule isolating the crew from their vehicle’s ammunition magazine.”
  • Unfortunately, the video goes on to say the T-14 has a low profile, which simply isn’t true. As I’ve noted before, the T-14 is 3.3 meters high vs. 2.44 meters for the M1A2, 3 meters for the Leopard 2, and 2.49 for the Challenger 2. 3.3 meters is higher even than the World War II M3 Lee tank the Soviets (who got them via Lend-Lease) called “a coffin for seven brothers.”
  • “The Armata’s main weapon is a 125mm 2A82-1M smoothbore gun which can fire related rounds and laser-guided missiles. This weapon would be a significant threat to the Western main battle tanks that Ukraine began fielding in larger numbers last year.” The “large numbers” are pretty small numbers.
  • “Unfortunately for Russia, this gun is not backward-compatible with its older tanks, which means only the Armata can field it, and that’s a problem, because there has never been a confirmed sighting of the T-14 in Ukraine. Russia has even fewer T-14 Armata tanks than it does Su-57 fighter jets.”
  • There follows a discussion of the T-14’s X-shaped engine that has evidently engendered a lively debate online, so I’m not going to get into it here.
  • “Meanwhile, the electronics for the Armata’s sensory and fire control systems are no longer as widely available due to the sanctions put in place as a result of its invasion of Ukraine. Indeed, there has not even been an assembly line built for the Armata and all of the prototypes have been made by hand. Given all of these problems, don’t expect to see the Armata fielded in large numbers, if at all, anytime soon.”
  • “Russia’s body armor has also been a subject of embarrassment. Many of Russia’s soldiers, especially the conscripts Putin mobilized in the autumn of 2022, have lacked proper protection. Infamously, some Russian troops were issued airsoft versions of the Ratnik body armor. Despite its problems in this area, Russia has made bold claims about what it has coming down the pike – its next-generation Sotnik body armor, which it says will be able to stop a .50 caliber Browning Machine Gun round.” Yeah, no.
  • We’re not even going to bother with the MiG-41, which doesn’t exist yet. Vaporware all the way down.
  • It’s always safest to assume that the latest Russian wunderwaffen is vaporware unless proven otherwise.

    Lawrence Person’s BattleSwarm Blog

    Meet BFA at Open Seasons Sportsman’s Expo March 15-17

    https://www.buckeyefirearms.org/sites/buckeyefirearms.org/files/styles/slideshow/public/field/image/sportsman-expo.jpg?itok=IlX0PfyA

    Leaders of the Buckeye Firearms Association will be on hand this weekend at the Open Seasons Sportsman’s Expo.

    The weekend-long expo, to be held inside the Bricker Building at the Ohio Expo Center & State Fair, will feature the latest in outdoor gear from national and regional exhibitors, hands-on demonstration opportunities, numerous entertainment and educational seminars with industry experts, and special guests.

    Other attractions include deer exhibits, archery trick shooting, field-to-fork cooking demos, and a 3D archery competition.

    Look for BFA leaders at booth 514, between Benning Distributing and Deer IQ.

    Event hours are 2 to 7 p.m. Friday, 9 a.m. to 6 p.m. Saturday, and 9 a.m. to 3 p.m. Sunday. The expo center is at 717 E. 17th Ave. in Columbus.

    For ticket and other information, visit openseasonsportsmansexpo.com/ohio.

    Buckeye Firearms Association

    Blue lasers/Camera pocket guide/Earth in real time

    Sign up here to get Recomendo a week early in your inbox.


    Blue lasers

    I spend too many hours a day watching YouTubes. Many of the channels I subscribe to produce content as good as or better than anything produced by PBS, cable TV, and your average documentary. For free. For a fantastic example of world class content on YouTube watch this Veritasium episode on Blue Lasers. Turns out blue lasers were “impossible” to create, but after decades of an insane amount of work by one crazy guy in Japan, they are now possible and all the cheap screens we have in our lives now are due to him. Veritasium tells this amazing human story, with heaps of illuminating technical detail on why blue lasers were nearly impossible and how they work, all in a brilliant 33 minutes. — KK

    Pocket guide to understanding a camera

    I gave my wife a camera for Christmas. It has an auto-setting, but she wanted to learn how to operate it manually. We were initially puzzled by terms like ISO, shutter speed, and aperture. Then I stumbled upon a PDF guide from Humburger Fotospots that demystifies these concepts with simple icons and explanations. I printed it out and stored it in the camera case. — MF

    View images of Earth in real time

    The GOES Image Viewer hosts the most up-to-date real time images of Earth available to the public. You can view and download satellite images that capture the entire visible disk of Earth and are updated every 10 to 15 minutes. I don’t know much about meteorology or geoscience, but I am an Earth lover, and it’s fascinating to be able to visualize weather patterns on a global scale. — CD 

    Galactic compass

    If you train yourself to pay attention to your surroundings you should be able to immediately point north without too much thinking. The next-level awareness is to point to the center of the galaxy at any time. Because the earth rotates during the day and orbits during the year, this direction changes constantly. You’ll need an app to help you. Galactic Compass is a free iPhone app that does only one thing: points toward the center of the galaxy. — KK

    Typography Guide 

    If you’re like me and would like to know more about fonts than just serif and san-serif, here is a cool guide to check out: The Logo Company’s Guide to Typography and Fonts. It breaks down the entire anatomy of fonts. — CD 

    Ryan Holiday’s career wisdom

    Writer and entrepreneur Ryan Holiday has had a varied career, from Hollywood agent assistant to marketing director for American Apparel. He’s put together a list of 37 pieces of hard-fought career advice that’s useful for anyone who works. Examples:

    • Find what nobody else wants to do and do it. Find inefficiency and waste and redundancies. Identify leaks and patches to free up resources for new areas. Produce more than everyone else and give your ideas away.
    • Always say less than necessary. Saying less than necessary, not interjecting at every chance we get — this is actually the mark not just of a self-disciplined person, but also a very smart and wise person.
    • Your creative output, your personal relationships, and your social life—balancing all three is impossible. You can excel in two if you say no to one. If you can’t, you’ll have none.
    • When people compete, somebody loses. So go where you’re the only one. Do what only you can do. Run a race with yourself.

    — MF


    Cool Tools

    Lifesaving Skills Every Gun Owner Should Know

    https://www.recoilweb.com/wp-content/uploads/2024/03/RECP-202405-SKILLS-ICT28851.jpg

    Ask anyone who carries an IFAK and a gun every day what they use more often — the IFAK always wins. What other skills do you need? Find out.Recoil