Full Web Apps with FastAPI Transcripts
Chapter: Creating our first FastAPI *site*
Lecture: Ready for running in production

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Now, before we call our little basic structure here finished. I do want to show you one quick little thing. Notice I was able to go over here,
0:09 right click and say run. And I can also press this button and everything looks golden. But the way that we actually run FastAPI in production is not to
0:19 go and say Python run this file. What we're gonna do is we're gonna say set up Gunicorn, which is going to oversee a farm of Uvicorn worker processes,
0:28 and each one of those is going to run this application. And that way, if something goes wrong with one, it can be restarted. You can do scale out.
0:36 There's all sorts of cool advantages to that. And that's generally how Python web apps run in production anyway. And when we do it in that mode,
0:45 the way we're gonna have basically implicitly behind the scenes do that chain. I talked about
0:49 what's gonna happen is, we're going to say uvicorn main thing here. What is it that we're working with? And then what is the name of this thing here,
0:58 which is app in our example. So we're gonna go to the main module and find the app instance and run it.
1:04 Watch what happens if I try to run it here. It says whoa, whoa. You're somehow like double running it. I'm not really sure what's going on here.
1:11 And that's because this is really just for testing, and we need a different way to run it in production.
1:16 So we're just gonna quickly fix that and say:only if you try to run it here in dev, do we want to do that.
1:23 So notice this, a live template is gonna expand out to if the name is main.
1:27 This is the Python convention. Say this file is being run directly rather than imported and else I don't know.
1:37 This is what we're gonna end up doing in production. There's actually some things will ultimately need to do here.
1:41 But for now, there's just nothing else happening. If I run over here through this mode, you can see it's running fine.
1:49 And if I go into the terminal now and I try to run it like this hey, look, it runs fine as well.
1:56 Okay, so you'll see that as we get this little bit more complicated. Think more things going on, like setting up the database at start up and so
2:03 on. There's gonna be some interesting balancing act that we have to do around this
2:07 but I wanted to make sure that you I focused on this specifically because it's easy to just say uvicorn run,
2:13 but then seems like it works and then it doesn't work in production. And that's why, right, this is fine when we press the run button
2:19 but in production were running through a completely different chain of events that uses uvicorn module:variable_name.
2:29 So I want to make sure we get this set up right from the start.


Talk Python's Mastodon Michael Kennedy's Mastodon