Full Web Apps with FastAPI Transcripts
Chapter: async databases with SQLAlchemy
Lecture: Async create account

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Next up is our create_account.
0:02 This one is not asynchronous yet.
0:03 So let's borrow this little bit here and make it asynchronous.
0:07 So we're gonna do that, and that makes this method require async.
0:10 We no longer need our try,
0:11 finally, because we've got our context block already.
0:15 And what else do we need to do?
0:16 We could actually do this right here,
0:18 ahead of times outside of this
0:21 async behavior. So this will run right away,
0:22 including this, which is computationally slightly expensive.
0:26 So we can do ahead and run that.
0:28 And then as soon as we've gotta talk to the database we'll go and await it.
0:31 So we begin, basically begin a transaction,
0:35 add this record to be committed.
0:37 This commit here, this is asynchronous,
0:40 this is where we're talking to the database.
0:42 So we need to say await,
0:43 you can go do other work while we're talking the database.
0:45 When it gets back with the result, we'll send it on.
0:48 We're gonna return, you could even do it like this,
0:50 we could return our user. So everything looks good.
0:53 That's pretty straightforward but remember,
0:55 wherever this was being used, we now have to go and make that
0:58 async. So that means this becomes await right there.
1:03 This one was already async because we needed that for the parsing of the form,
1:06 which is a async in and of itself.
1:08 All right, we should be able to register again.
1:10 But this time, using the async capabilities. Log out,
1:17 what do you think? time for another Sarah Jones register?
1:19 How about Sarah Jones4?
1:27 And again, let's go ahead and just verify this works, the email is taken.
1:31 But if it's 4, you can create the account.
1:37 Here we go. It looks like we created the account so, perfect.
1:40 This bit of code seems to be working great.
1:42 We can now asynchronously, create users. Super simple,
1:48 very similar to before actually,
1:49 in this one even more. This is the most similar code you'll see from anything
1:53 that we've done. We just, instead of creating the session,
1:56 adding and calling commit, we created it with the context block and we await the commit. Easy.