Full Web Apps with FastAPI Transcripts
Chapter: async databases with SQLAlchemy
Lecture: Async create account
0:00 Next up is our create_account. This one is not asynchronous yet. So let's borrow this little bit here and make it asynchronous.
0:08 So we're gonna do that, and that makes this method require async. We no longer need our try, finally, because we've got our context block already.
0:16 And what else do we need to do? We could actually do this right here, ahead of times outside of this async behavior. So this will run right away,
0:23 including this, which is computationally slightly expensive. So we can do ahead and run that.
0:29 And then as soon as we've gotta talk to the database we'll go and await it. So we begin, basically begin a transaction,
0:36 add this record to be committed. This commit here, this is asynchronous, this is where we're talking to the database. So we need to say await,
0:44 you can go do other work while we're talking the database. When it gets back with the result, we'll send it on.
0:49 We're gonna return, you could even do it like this, we could return our user. So everything looks good. That's pretty straightforward but remember,
0:56 wherever this was being used, we now have to go and make that async. So that means this becomes await right there.
1:04 This one was already async because we needed that for the parsing of the form, which is a async in and of itself.
1:09 All right, we should be able to register again. But this time, using the async capabilities. Log out,
1:18 what do you think? time for another Sarah Jones register? How about Sarah Jones4?
1:28 And again, let's go ahead and just verify this works, the email is taken. But if it's 4, you can create the account.
1:38 Here we go. It looks like we created the account so, perfect. This bit of code seems to be working great.
1:43 We can now asynchronously, create users. Super simple, very similar to before actually,
1:50 in this one even more. This is the most similar code you'll see from anything that we've done. We just, instead of creating the session,
1:57 adding and calling commit, we created it with the context block and we await the commit. Easy.