Flask – Lecture 2 – CS50’s Web Programming with Python and JavaScript 2018

BRIAN YU: OK, welcome backeveryone to Web Programming with Python and JavaScript. So in the past couple of weeks,we’ve been looking at HTML and CSS, learning about how we can write codethat decides how our website ultimately looks by describing thestructure of the code and by using CSS todescribe the style the code to determine how our web page is styled. Today what we’re going to do iswe’re going to take the next step and start building some dynamic webapplications using a programming language called Python in order to buildweb applications that are a little more powerful than what we can have justby describing the contents of a web page using HTML, for instance.But before we can get the Flask,we should talk a little bit about the languagethat we’re going to be using in order to createthose web applications, and that language is Python. And so Python has come in anumber of different versions. We’re going to be in this classusing the latest version of Python, as of now, which is Python 3.6. And so Python is aprogramming language that is an interpreted programming language. Meaning what we’ll do is we’ll bewriting code in the Python programming language. And then we’ll run itthrough what’s called a Python interpreter, a program thatreads in Python code line by line, and interprets it, tries to parsethe Python, understand what it means, and then execute that code.And so what we’ll do first beforewe dive into the web programming part of this is take a look atPython, just the language itself, get a feel for how the language worksand what the different components and features of the language are. And after that, we’ll usethose skills using the tools that we can use in Python in orderto use that language to generate dynamic web applications of our own. So let’s dive right in and takea look at our first example of a program written in Python.And this program is Hello.py. The dot p-y extension isjust a common extension for names of files that arefiles that contain Python code. So this piece of codeis called Hello.py. And it’s just got one line. And that line is a print, andthen in parentheses and then in quotation marks,the words hello world. And so this is a verysimple Python program. And let’s try running this Pythonprogram just to see what happens. And then we’ll take a look athow this is actually working. So in order to run a Pythonprogram on the command line, I’ll type the word Python to runthe Python interpreter, followed by the name of the Pythonfile that I want to run. So in this case, the name ofthe Python file is hello dot py. And so if I type hello dot py andpress Return, just to say run hello dot py in Python, what I get is justthe words Hello World printed out to the terminal screen.And so that’s all it does. A fairly simple program thatjust prints out hello world. And if we take a lookat hello dot py, we can start to break downwhat’s happening here. This word print, this is afunction, just a word in Python that represents doing Something, In thiscase printing something to the screen. And inside the parentheses is what’scalled the function’s argument, information we giveto the print function, in this case telling the print functionwhat it is that we want to print out. And so in this case, we have in theparentheses in the “string”, which is just a sequence of text “helloworld” meaning print out the words hello world to thescreen, and therefore when we ran hello dot py byrunning Python, the result was that we got the words thehello world printed to the screen.And so that was a fairlystraightforward Python program, just one line long that printssomething to the screen. Let’s take a look at somethinga little more sophisticated. So inside of a namedot py, now here I have a Python program that’s got two lines. And so let’s break downthese lines one by one and get a sense for what’s happening. Here line one, we definea name, where name is just a variable, some name that we’regoing to give it to a place where we can store data or informationinside of our Python program. And name is going to be set equal tothe result of this input function. And so input is a functionthat in Python asks the user to type in input at the command line. And when they press Return,whatever it is that they typed in, gets returned from the function. It’s information that’spassed back from the function. And if you’re familiar withother programming languages, it’s much the same idea. And so we ask the user totype in their name presumably.That gets stored inside ofthis variable called name. And now let’s take a look at line two. What’s happening here? Again, we’re callingthat print function, the same function that wecalled in hello dot py. But in particular what’sinside the parentheses is slightly different notation. So the first thing that’s slightlydifferent is that the string– the text enclosed indouble quotation marks– begins with the letter F. This is anew feature of Python version 3.6– the latest version– called the formatstrings, which let us take a string, take text and substitute informationby filling in blanks in the string wherever we want to put a placeholderfor some other value, for instance. And so what that’sgoing to allow us to do is say something like print hello comma. And then these curlybraces surrounding the word name mean take thevariable name and plug it into this format string inserted here.So whatever name getstyped in, that gets saved into this variable called name. And then when I print something out,I’m printing out the word hello comma, and then here, we’re going toinsert whatever that name was that was passed in via the input. So if I try to run this programnow by running Python name dot py– because that’s the nameof this Python file– and I press Return,nothing appears to happen. And the reason for thatis that on line one it’s waiting for me toprovide some sort of input. Recall that line one, I havename equals input this function. And so if I type in my name, forexample, Brian, then on the next line it says hello Brian. So name was my name. And then inside of the format string,inside the print statement on line two, it substituted my name in wherethese double curly braces were. And if I were to run this again, typingin someone else’s name like David, then the next line says helloDavid, plugging in that new name into that format string as well.So that was an exampleof variables in Python as well as format strings, which area special type of string in Python. Questions about that we’ve seen so far? Yeah? AUDIENCE: [INAUDIBLE]? BRIAN YU: Yes. So the question was can we also passin a name via command line argument? And yes, Python does have ways ofinterpreting command line arguments. You’ll have to use a separatepackage in Python that allows you to deal with that. It’s called the sys package, s-y-s. And using that package, you caninterpret command line arguments and do things with thosecommand line arguments. We won’t explore those tooheavily in this course, because our focus is going to be toquickly move away from the command line and start moving towards buildingweb applications in Python.But yes, you can in Python use commandline arguments to get information from the user as well. Other questions before we keep going on? So this name on line onewas the first example of what we’re going tocall a variable in Python. Just a place in our Python code wherewe can store data of different types. And so let’s take a look at thedifferent types of information that we can store insideof a Python variable, and just look at a coupleof examples of that.So right here what we have is a Pythonprogram called variables dot py. And what this does is it definesfour different Python variables. And these variables allhave different types. And so on line one, I’ve definedthe variable i to be equal to 28. And now i is going to be avariable that stores the number 28. But in particular, it’s storinga particular type of information. The number 28 is an integer,where integers are 0, 1, 2, 3, 4, and the negative 1, negative2, negative 3, et cetera.And so i in this case isjust an integer value. And so we see here that Pythoncan store integers as variables. And then we’re going to print out thati is 28, for instance in this case. And then on line four, I’mdefining a new variable called f, which is equal to 2.8. And so this shows you that Pythoncan store not only integers, but floating point values as well,values that have a decimal in it. And so this is a differenttype of variable altogether. And so that will printout f is 2.8, for example. But it’s not just numbers thatPython can store as variables. We saw in name dot py– theexample from just a moment ago– that we can use variablesto store strings as well, text that can be used in orderto store a name, for example, inside of a variable. And we can store other types as well. Down here line seven, wesee that b is set to true.So Python has a specialtype called bool, which stands for Boolean values,where a Boolean value is just a value that is either true or false. It represents where the something ispositive or negative, for instance. And Python has a special keywordcalled True with a capital T that represents the Boolean value true. And likewise there’s also a falsevalue that represents a false Boolean value as well. And finally, Python alsohas a particular type called the None type, which only hasone possible value, just called a None. And a none type is just a wayin Python to represent the idea that a variable has no value. So if we want a variable thatdoesn’t have value for some reason, and we might see exampleslater of when that could be useful or helpfulor practical, you’ll often see capital NNone used to represent a kind of variable that just isn’tstoring any information whatsoever.So if I were to run variables dot py,what I get is that i is 28, f is 2.8, b is false, N is None. Note that I never told my programthat i is going to be an integer, or f is going to be afloating point number, or b is going to be a Boolean value. Python figures this out for itself. When I say i equals 28, Python knowsthat if I’m assigning the number 28 to i, then i must be in integer value.And so if you’re familiar withother languages like C or Java, where you’re used to havingto explicitly write out the name of the type forany particular variable, know that Python doesn’trequire you to do that, and just lets you take a variableand assign it to any given value without needing to specify explicitlywhat the type of that value actually is. Questions about that so far? So let’s take a look atsome of the other constructs that we can begin to build up byusing Python and its various language features. Let’s take a look at conditions dot py. And so what we’regoing to do here is say that we have a variable called x that’sset equal to some number, for example. Maybe the number 28,just to take an example. And what we have here on linethree are conditional statements, if statements, which areeffectively branches in the code where depending upon whether ornot something is true or false, we can decide which codeyou want to execute.So let’s take a look atwhat’s happening here. We say on line threeif x is greater than 0, then anything indented underneath thisif statement, as we would call it, is code that will only runif x is greater than 0. So if x is greater than 0, thenhere’s what’s going to happen. All of these indented lines, inwhich case now there’s only one, we’re going to print outthe string x is positive. Meanwhile, el if is short for else if. In other words, else otherwiseif x wasn’t greater than 0, if x is less than 0, then let’srun this indented line here, print x is negative. Else otherwise, if it was neithergreater than 0, nor less than 0, there’s only one remaining possibility. We can print out the fact that x is 0. And this indentation in Pythonis something you’ll see a lot.The indentation in Pythonis actually required. Unlike several otherprogramming languages where indentation isa style thing, where it’s nice and helpful from a readabilityperspective to include indentation, but it’s not strictly necessary, inPython this indentation is necessary. This is how you tellthe Python interpreter this is the code that is containedinside of this if statement. This is the code that should runif this if statement is true. So if I had multiple lines that Iwanted to run, if x were greater than 0 for instance, I would have multiplelines all indented inside of that if statement as well.So if I were to go over here and runthis program now, rather than print out three things, because Ihave three different print statements, if I run in conditionsdot py, I just see x is positive. Because it caught on that first ifcondition, if x is greater than 0. And it printed out that x is positive. If x were negative 28 instead, and I ranthat same program, now x is negative.And likewise, if I had replacedx with just 0 for instance, and run that again, now I justsee that x is 0, for instance. And so depending upon thevalue of x, I can conditionally determine which way to go in the code. Questions about that so far? Let’s keep going then. So thus far we’ve seenexamples of variables in Python that are able to storesingle values, effectively, a single number, whether it’sinteger or floating point number or a single Booleanvalue, like true or false. But Python is verygood at also supporting storing sequences of data wherewe have multiple values that are combined together under one name. And there are a bunch ofdifferent ways to do that. So I’ll show you sequences dot py now. And so in sequencesdot py, I’ve given you three examples of variablesof different types that are all sequencesof data in some form.So on line one, I havea variable called name, which is just storing the string Alice. This is somethingwe’ve seen before where we have a string, whichis just text that’s being stored inside of a variable. But one helpful way to thinkabout a string like the word Alice is that it’s really justa sequence of characters. It’s the character capital A,followed by the character lowercase, l followed by lowercasei, c, e. et cetera. And this way of thinkingabout a variable makes it easy to say whatif I wanted to just get the second character of the name,or the third character of the name, for instance? You can treat that longstring as just a sequence of the individual constituentparts that make it up. On line two you’re lookingat an example of what’s called a Python tuple, which is away of grouping a couple of values together in a single name. So if I wanted to store in Pythonan xy coordinate, for example, like, on a graph if I wanted to storea particular point on that graph, I might store it as follows,where I say the coordinates are, and then in parentheses 10.0, 20.0.And so now both of those valuesare stored as a single name, coordinates, as opposedto needing to store two variables like a coordinates xvariable and a coordinates y variable, I can group them together and juststore them under a single name as well. And then finally on linethree, we see an example of what’s called a Python list. And this is a very powerfuldata type in Python. And a list is a data type that letsus store a bunch of different values all together in one. And so here I have a list ofindividual people’s names. And so a list in Python isdenoted by the square brackets.So I open the square bracketand then have the first thing in the list, which is the name Alice. And each of the elements in thelist are separated by commas. So Alice is the firstthing in this list, Bob is the second thing in the list,Charlie is the third thing in the list. And so this is an exampleof a list in Python that is all stored underthe variable name names.So using those lists we can beginto perform operations on them. And one nice feature of Python is thatI don’t just have to write a Python file and then run that Python file. And that’s the onlyway to run Python code. Python has a sort of a liveinterpreter that lets me type code and see the result of ithappening in real time. So if I just type Pythoninstead of Python space, the name of a Python fileI want to run, what happens is that I’ve opened up thePython interpreter, which is a place where I can line at atime type of line of Python code and immediately see the result. And for our purposes this isgoing to be pretty helpful. So you can do the exact same thingsyou could do in a Python file. I can say x equals 28, forexample and press Return. And now that line of Python is executed. And now if I were tojust type x, for example, it will show me thatthe value of x is 28. And I can add any otherPython code that I want here.So if x is greater than 0,then print x is positive. And now that prints out thefact that x is positive. And so I’m able to runPython code just like this. And the reason I’m doingthis is that we can begin to see some of the featuresof Python data types like sequences by using the Python interpreter. So if I had a name equalsAlice, like I had before, the way that you access individualelements of a Python sequence whether it’s a string representinga bunch of different characters or a tuple representing acouple of different values or a list of even more values,is that I can do name it, and then in squarebrackets, the index that I want to access, where the firstthing in the sequence is index 0. So if I did name, square bracket0, what is that going to be? Capital A. That’s the firstthing in the string Alice. The very first characteris just that capital A. And likewise, name,square bracket 1, that’s going to be the secondcharacter of Alice’s name, where l is the second character.So it’s sort of what we calla zero index system, whereby the first thing in the string Aliceis number 0 and the second thing is number 1. And so that’s a typicalcomputer science convention. It’s true in otherprogramming languages as well. But know that square bracket 0 getsyou at the first thing in the sequence. Square bracket 1 is the secondthing, so on and so forth. And so if I had coordinatesequals 10.0, 20.0 for instance, I could use thecoordinates square brackets 0 to get it just the firstcoordinate, and likewise, I could do coordinate square bracket 1to get it just the second coordinate.And similarly, if I had a list of namesthat was Alice and Bob and Charlie, then I could do names, squarebrackets 0 to get at the first name, name square bracket 1 to get thesecond name, and name square bracket 2 get at the third name. And what would happen if Itried name square bracket 3? AUDIENCE: [INAUDIBLE]. BRIAN YU: So what I get is aPython exception, effectively an error of some sort that tellsme that something went wrong. And in this case, the type ofthe exception is index error.And it says index listsindex out of range. And so the interpretation of thatis that this index that I provided, this number, name square bracket3 is out of the range of the list. There is no item in the nameslist that has index number 3, and therefore Pythoncan’t access it for me. And so if I’m trying to ask Pythonor do something that it can’t do, oftentimes I’ll get anexception of this form. And learning to becomefamiliar with these exceptions as you begin to see them as youwork with Python programming will help you to figure out wherethe cause of the source of the area is, which can then help youto then go back and debug and figure out what went wrong. So those were variables and differenttypes of data and conditions in Python. Let’s take a look at someof the other constructs that we can have in the Pythonprogramming language, in particular, let’s take a look at loops and howwe might repeat code multiple times. And so here in loops 0 dotpy i have just two lines. So on line one I say for i in range 5.And then on line two,I’m printing out i. And so what this program iseffectively doing is on line one I’m saying let’s take this variablei and run it through this loop. This what we call a for loopthrough a range of five numbers, ranging from 0 all the way up tobut not including the number 5, such that if I run theloops 0 dot py what I get is that I get five numbers printed out,0, and then 1, and then 2, and then 3, and then 4. Because this loop, thisloop happened five times. And each time the value of i changed.The first time it was 0. That it incremented to 1, andthen 2, and then 3, and then 4. And then it doesn’tinclude the final number 5. It goes up to, but not including the 5. And as a result I get numbersprinted out five times. If I wanted to print out10 numbers, for instance, I could change range to range 10. And now running loop 0 dot py printsout 0 all the way up through 9, for example. So that’s an example ofa simple loop in Python. But Python supports othertypes of loops as well, in particular, forlooping over a sequence.So we saw in the last example that wehave a bunch of different data types for representing sequences of data. We have strings that arejust individual characters. We have lists that are abunch of different values that are grouped together. And so if I look at loops1 dot py now, you’ll see what we have here is on line oneI had a final list, the same list as before. Names is equal to Alice, Bob, andCharlie, a list of three strings. And then on line two, I havea different style of for loop.I’m saying for name in names,where the intuition here is that I’m going to be looping overthis names variable one at a time. And each time I’m going to calleach item in that list name. And that’s just going to be thename that I give to that variable. And then I’m going to print outthat name inside of the for loop.And notice that everything insidethe for loop, just like everything inside of my if condition needs tobe indented so that Python knows what code is containedinside my for loop and what code isoutside of the for loop. And so if I now run Pythonloops 1 dot py, what I get is Alice and then Bob and then Charlie,one name at a time, one line at a time.Question? AUDIENCE: Do sequences needto be all the same data type? BRIAN YU: Great question. So the question is, do sequencesneed to be all of the same data type? The short answer is no. So in a list for example, I could havea list, I’ll just call it l for a list. That could be the number28, and then the name Alice, and then the Boolean value true. That is technically a valid list. And I can say l square bracket 0 toget it the first thing in the list.And 1 to get it the second, and 2to get to the third, for instance. But generally speaking,especially with lists, it’s a good idea if different thingsin the list are of the same type. It’s often good design to have elementsof the list to be of the same type, because generally our lists are goingto have some sort of semantic meaning. It’s going to be a list of names,where all of the elements in the list should be strings. Or a list of numbers, whereall of the elements in the list should be integers. And it’s helpful to be able to treateach item in the list the same way. And we can only do that if itemsin the list are of the same type. So while not strictlynecessary to have all the items in a list be of the same type,it’s often a good design idea to do so. Good question. Other questions before we move on? AUDIENCE: Could you skip the print[INAUDIBLE] In the interpreted version, you don’t have [INAUDIBLE].BRIAN YU: So the questionis– great question. The question is in theinterpreted version when I’m trying to display avalue, I didn’t need the print. I just typed l0 insteadof print l0 in order to get the first thing in the list. This is something uniqueto the Python interpreter that the interpreter ifI just type in a value, Python will tell me what’scurrently stored in that value.But if I’m running aPython program, then I do explicitly need thatprint function in order to say this is a value that Iwant to print out to the screen. So it’s a slight difference betweenthe way the interpreter works live, versus when I’m running itjust through a Python file. I could equivalently typeprint l0 in the interpreter. And that would produce the same results. But if I’m running it in a Python file,like, a file that ends with dot py, then I need to havethe print line there.Good question. We’ll take a quick look at some ofthe other more advanced data types that exist in Python,and then we’ll move on to taking a look at acouple of other things. So in addition tosupporting lists, which are an ordered sequenceof data where we have a first item and a seconditem and a third item, Python also has support for othercollections of data as well. And so one of thoseexamples is a set where a set is just a collection ofitems where no item shows up twice. And in particular, a set doesn’thave any particular order to it. So the only thing we care aboutis a particular value in the set, or is a particular value not in the set? And so line one here, I’vesaid s is equal to set, where set is just a functionthat creates an empty set for me. On line two, I’ve addedthe number 1 to the set.On line three, I’ve addedthe number 3 to the set. On line four, I’ve addedthe number 5 to the set. And on line five, just for the fun ofit, I’ve added the number 3 to the set again. But the rules for a set is thatitems in the set are unique. So if I try to add a number or a valuethat’s already in the set to the set again, then the result of that isgoing to be no change to the set. And so if I print theset out on the last line, and I run sets dot py,what I get is just a set 1, 3, and 5, because those arethe only three numbers that are actually inside of that set. And so if ever you don’t really careabout the order of the information, because sets doesn’tpreserve which thing came first, second, third, fourth– and I just care about which things areinside of the set or not in the set– then I can use this notation inorder to describe that as well.And one final data type we’ll takea look at are Python dictionaries. So dictionaries are yet anotherdata structure in Python which are used in order to mapcertain values on to other values. And they’re often used whenwe want to try and indicate some sort of relationship betweena former value and a latter value. And so what we see indictionaries dot py here is an example where Iin my Python program might want to store theages of different people that I’m keeping track of. And so what I have here line oneis I’ve created a Python dictionary that maps what arecalled keys to values. And in the case of myages dictionary, the key are all going to be the names of people. So in this case, I have the key Alice,which is mapped to the value 22. And the semantic interpretation ofthis is that Alice is 22 years old and Bob is 27 years old.And so what you’ll noticeis that the syntax for that is that a dictionary is definedby curly braces on either end. And then the key, which is somevalue, followed by a colon, followed by what its value is. So Alice colon 22 means I’m goingto put Alice in my ages dictionary, and then set its value to be 22. And likewise, I’m puttingBob into the dictionary and setting its value to be 27. And if I wanted to add somethingto the dictionary later, I could do it like this on line two. I’m adding Charlie tomy ages dictionary. And Charlie is 30. That is the value that it is mapped to. And if I wanted to edit the valueof one of the variables later on, a line like this, agesAlice plus equals 1 is a shorthand way of saying takewhatever Alice maps to in my age dictionary and increase its value by 1. It was formerly 22, now it should be 23.If I wanted to write thisout in a longer form, I could say ages Aliceequals ages Alice plus 1 to say update the value of agesAlice, and set it equal to whatever ages Alice was a plus 1. But often a shorthand conventionfor that is plus equals 1, meaning increase its value by 1. Those two lines are identical. And then finally at the end I’mprinting out this ages dictionary. And so if I run thedictionaries dot py, what I get is this dictionary where Alice’sname is mapped to the number 23, Bob’s name is mapped to the number 27,Charlie’s name is not to the number 30. And so that’s an exampleof a dictionary in Python that lets us map keysand values together. And so these are all just a wholebunch of different data types that exist in Python.Python is a large language with a bunchof different features and data types that are built into the language. But these are some of themost common data types, ones that will likelyfrequently come up as you begin to work on programming in Python. Totally OK if you haven’tinternalized all of what each one of those data structures isand what’s different about all of them just yet. But as we begin to designweb applications in Python, you’ll hopefully start toget a sense for when might it be appropriate to use a dictionaryin order to represent data, or use a list to represent data whenwe’re designing our web applications.So we’ve looked at data types in Python. Now let’s take a lookat functions in Python. So here we’ll open up functions dotpy and see what’s going on here. So line one, I’ve defineda new function in Python. We’ve seen built in functions likethe print function that prints things to the screen, or the input functionthat gets input from the user. I’m now defining my ownfunction called square. So on line one I say def, meaningI want to define a new function. This function is goingto be called square. And it’s going to take one argument thatI’m arbitrarily just going to call x. Now just like in if statements,we indented everything inside the if statement,and in for loops we indented everything inside the loop. Inside of this definitionof my square function, I’m likewise, going to indent everythingand say that all the square function is going to do is that ifyou hand me a number x, I am going to return back to you xtimes x, the square of the number x, by taking the input value andjust multiplying it by itself.So this function, giventhe number two will give me four, if I give it number three itwill give me nine, so on and so forth. And now on line four,I’m running a for loop. I’m running a loop for i in range 10. And if we recall what numbersis that going to range from? How many times will that loop runfrom what number to what other number? 0 to 9, exactly. I start at 0, and it’s going togo up to, but not including 10. So it’ll end up stopping at 9. And here’s what we’regoing to print out. We’re going to print out somethingsquared is something else. And here, I’m using thisspecial dot format syntax. This is just a different way ofplugging in numbers into this string, in particular I’m saying this is goingto be a placeholder for the value i, and this is going to be aplaceholder for the square of i. So whatever i’s valueis I want to plug it in to this first thing in the string.And the square of i is going to beplugged in to this part of the string. And this is a slightly older way ofplugging in values into Python strings. And I’m showing it you here in caseyou ever use a version of Python older than 3.6 where the formattedstrings, where we started strings with the letter f isn’t supported. You can use this notation as well andit will effectively do the same thing.So in this case we’re loopingover the numbers from 0 to 9 and saying somethingsquared is something else. And I’m calling my squarefunction, the square function that I’ve defined up there. And so when I run this programby running Python functions do py, what I get is a loop that runs 10times 0 squared is 0, 1 squared is 1, 2 squared is 4, all theway down to 9 squared is 81, where each time I tookthis input value i and called my square function, which gave meback a number like 81, for example. And this was the code to do that. Questions about functions oranything we’ve seen so far in the Python programming language? Yeah? AUDIENCE: Do you have to definefunction before you use it? Does it always have to go first? BRIAN YU: Great question.So the question is, do I need todefine the function before I use it? And in general, Python needs to knowabout the existence of some name before you use it. So in this case, if I wereto take the square function and move it underneaththe for loop, for example, watch what will happen when I tryand run functions do py again. It gives me a name error. This is another exception. We saw the index errorbefore where I was trying to access some particular partof the list that wasn’t supported. And in this case, I’m getting a nameerror saying square is not defined, meaning Python doesn’tknow what square is.And the reason is thatI’ve hit line two, where I’m trying to call this square functionbut Python’s reading my file from top to bottom. And so square as a functiondoesn’t get defined until later on. So we do need it earlier, but we’ll seein just a moment how we can actually get around that issue and actually havethe square function underneath if we wanted to. So those are functions in Python. And the nice thing aboutfunctions in Python is that once you write them once in onefile, you can use them in other files as well. And so you can use Python functions thatyou’ve written yourself in other files, and you can also use functionsthat other people have written in their own files in your own filesby referring to a function that exists in some other file.So I’ll show you anexample of how that works. And this is going to be ina file called modules do py. And so in modules dot pywhat I’m doing is on line one I’m saying from functions import square. In other words, from thisfunctions do py file that I have, I want to import into the file thename square, which in this case is a function back to modules dot py.From functions import a square functionand then print out the square of 10. So I didn’t explicitly define the squarefunction inside of modules dot py, but I’m using it because I wasable to import it from functions. So any guesses as to what will happenif I now run Python modules dot py? Where modules the pie isimporting square from functions and then printing outthe square root of 10? We wanted to print out 100. That’s what we would like to happen. What actually happens is thatit prints out 0 squared is 0, 1 squared is 1, so on and so forth. And only after all of that, thenit prints out the number 100.So the number 100 is what we wanted,but why did the rest of the stuff get printed out? AUDIENCE: It executes still. BRIAN YU: Yeah, it executed this codethat was originally inside of functions do py, this for loop that I definedalongside the square function. And the reason why is that when I triedto import from this function’s file, it went through the function’sfile going through each line. And when it hit thatfor loop, it decided to just run that for loop for me.And so that’s probably notquite what I want to happen. I would like for someone to beable to import the square function from my functions filewithout them needing to then run all of the code insideof the main part of my functions file automatically. And so one common solution to thisin Python is to put all of the code that I want to run only when Iactually run this functions file inside of its own function. And this is generallycalled a main function, which will be just themain function that runs when I try and run functions dot py. I’ve taken everythingand I’ve indented it to say this is all code that’s goingto be inside of the main function. And then the last thing I needis a bit of special syntax that you don’t need toworry about too much. But effectively what I’m sayinghere is if name equals main– in other words, if I am currentlyrunning this particular file, that’s how you shouldinterpret that line– then run the main function.And so it’s a littlebit of added complexity. But the reason for thisadded complexity is that now when I runthe functions dot py, I still get 0 through 9 printedout just as normal like I want to. But if I run modules dot py, the onethat was importing the square function and then just callingthe square root of 10– oops. Python modules dot py– then what I get is justthe number 100 because that is the result of callingsquare on the number 10. And it didn’t call any of this code. It didn’t run any of the code thatwas only inside of the main function. It only ran the code that was explicitlyasked to be run, which in this case, was calling for the square of 10. So that was an example of how we canimport functions from other places in order to use them. And we’ll soon see when westart moving to web development and writing web applicationsin Python, that this will be really important for us,that there are functions that do things in web applications that otherpeople have written that we would like to use, that we canimport from other people that they have written withoutneeding to write it ourselves.And we can take advantageof those functions and effectively stand on theshoulders of others in order to build web applications that takeadvantage of those existing features. Questions about anything else beforewe look at one last feature of Python, before diving back into web programming? Last thing we’ll take alook at is Python classes. And so this is something that willbecome more relevant next week.But we’re going to take a look at itnow just to get a preview and a taste for what it’s like. Python classes are a way of definingentirely new types in Python. So Python has a built intype for representing lists. It has a built in type for strings. It has a built in typefor Boolean values, but it doesn’t have a built in typefor representing a point in space. We could use a tuple, ofcourse, like we saw before, just some number comma some other value. But here is a way ofme explicitly creating a new type in Python called a point. And here’s the way it works. So on line one I’m saying I’m defininga new class of things called points. And on line two I havethis special init function. And the init function inPython is a way of saying when I create a new point,what information do I need? And in particular, Ineed self, which is just going to be a variable thatrepresents the point itself, the object that I’m creating, andthen I need an x value and a y value.And so when I create a newpoint, what should I do? Self dot x equals x ismy way of saying self is that name, referring to thepoint object that I’ve just created. And dot x is my way ofsaying, I want to access a particular attribute of the self,of the point that I’ve created. In particular, I want to setself x attribute to whatever this x value is that’s being passed in. That way, when I create a new point,I’m storing that x value inside of self dot x.And likewise, I’m storing the y valueof the point inside of self dot y. And so when I actually use this is onsomething like line six where I say p is equal to point 3,5. That is going to createa brand new point, calling this init function that getscalled anytime it create a new point. And it’s going to set p’sx value to be whatever get passed in at x, which is 3, and setp’s y value to be whatever was passed in as the y value, in this case 5. And now if I print outp.x and p.y, that’s going to take this point to objectand access whatever its x attribute is and whatever its y’s attributeis and print out those values. And so we’ll take a look at that. If I run the classes dot pyand press Return, what I get is 3 on the first line andthen 5 on the next line. Because I first decided to printout the x value of my point p.And after that, decided to print outthe y value of my point p as well. And so that printed out 3 as thex value and 5 as the y value. And so that would be how we would createclasses entirely new types in Python as well. And so that was a lot of overviewof the Python programming language. It’s a big language. There’s a lot of stuff going on. We looked at different typesof variables and data types and conditions and loopsand functions and classes. Totally OK if this is all new to you,but hopefully some of the concepts seem familiar or reminiscentof programming languages that you may have used before.But we’ll take a short break now. And after we come backfrom the break, we’ll talk about how to begin to usesome of these language features in order to actually buildweb applications that are living on the internet. So we’ll take a short breakand then we’ll come back. Welcome back. So we just got a whirlwind tour ofthe Python programming language. And now what we’re going todo is use Python to begin to build some dynamic web applications. And so before we get there, Ijust want to take a brief moment to talk about HTTP. HTTP, hypertext transferprotocol, which is the system that we’re going to be usingthat the website and the internet uses in order tointeract and communicate between computers and servers. And so the general idea orthe model to get in your head is that when you type in a websiteand press Return, what that’s doing is sending an HTTPrequest to some server. If I type google.comand press Return, I’m sending an HTTP requestto Google’s server. Google’s server receives thatrequest, needs to figure out some way to interpret that request.What am I asking for? What am I searching for? Am I searching for news orimages or something else? It figures out what’sgoing on in that request. Figures out what informationto give back to me, and then sends me back and HTTP response thatcontains the information that my web browser then receives and thendisplays on a page in Chrome or Safari or whatever web browserthat it happen to be using. And so what we’re goingto be doing now as we go about building webapplications, is writing code that will take care ofthat server side processing. Receiving requests, figuring out whatthose requests they’re dealing with and what they’re asking for, andfiguring out what response to then give back to the user. And in order to do that,we’re going to be using flask. Flask as a micro frameworkwritten in Python.What that effectivelymeans is that flask is some code already written for usin Python that makes it easy to get up and running with a simpleweb application that has a lot of features that can beuseful as we go about developing web applications, as we’llsoon see in a moment. And so flask makes the process ofdesigning a web application relatively easy, and lets us focusreally on what users are requesting and whatsort of response that we want to provide back to the userafter that request has been made. So let’s take a brief look at afirst web application in flask. And this is going to beinside of the first directory. And so flask code is generallystored inside of a file called application dot py is going tobe the main file of a flask application. And here is the code that we need inorder to run this flask application, in order to run a basicweb application that we can serve as if it were a website. So on line one we havefrom flask import flask.Just like before, when we wereimporting that square function from the other file thatI had created, here we’re importing flask, whichis just going to be a way of creating a flask webserver from this flask module that exists somewhere else. Someone else wrote the flask module. You can install it for free. And what we’re doing on line one isjust saying that in this Python file, we want to use that flask module.Now what are we doing? On line three– this extra line isjust there for aesthetic purposes. It doesn’t serve a real purpose– we’re saying app is equal toflask underscore, underscore name underscore, underscore. And what that’s doing is saying Iwant to create a new web application. And I want this web applicationto be a flask web application, where underscore, underscore a name isjust representing this current file, that this file is going torepresent my web application.Then on line five, this iswhere things get interesting. At app dot route and then slash. So flask is designed in termsof routes, where a route is just part of the URL you typein order to determine which page you want to request. And so this slash justrepresents the default page. If I go to a website slash andthen nothing else after the flash, that is the default pageof the website that I just want to access when I access the webpage for the first time, for instance. And what line five issaying, app dot route slash, is that when the user goesto just slash on my website, goes to that default route, thefunction immediately below it is the function that I want to run. This is a special linecalled a decorator. No need to worry too muchabout exactly how that works. But the idea is that I amtying this function immediately underneath app dot route slash tothis slash, so that when I go to slash is the function that’s going to run.This is a Python functionjust called index. And all my index function isdoing is returning the string hello world, just returning that text. So this is a very simple seven lineweb application written in Python. And let’s try and run it now. So in order to run a flask application,I’m going to go into the directory where that application is located,in this case, it’s called first. And I’m going to run flask run, whereflask is a web server that I’m going to just run in this current directory. So I type flask run. And what I get is I’m now servingthe flask app application. And I’m running it onthis particular URL. And so if I take this URL and paste itinto a web browser for instance, what I get is just the words hello world.I went to the defaultroute on my website. I just pressed Return. And the result is that thistext is what came back to me. This is the responsethat flask produced. And it was produced because ofthis line, this return hello world line, that happened whenever someonewent to the slash route on my website. If this had instead been helloworld with extra exclamation points for instance– if I savethat, and I refresh the page, now those extraexclamation points appear. So by editing my Pythoncode, this flask code, that I’m able to change theway that my website looks. Questions about that verysimple first web application that we’ve been able tocreate with just a couple of lines of code using Python and flask? Yeah? AUDIENCE: Does flask know to look fora file callled application dot py? BRIAN YU: Great question. Does flask know to look for anapplication called application dot py? Not out of the box necessarily. So what might happen is if youtry and just run a flask run, you might get an error that saysflask doesn’t know where to look for your particular application.And the reason why is thatflask relies on what’s called an environment variable,a variable that’s set inside of your terminal to knowwhat file to be looking for as the source of the application. I’ve already sent my applicationto be application dot py. But if you’re runningfor the first time, you might need a line likeexport flask underscore app equals application dot py. And all that line is doing is sayingset the environment variable flask app to be application dot py. In other words, tellflask that the file that I want to run thisapplication from is a file called application do py, whichis just the general convention.But depending upon whatsystem you’re using, that may or may not beset automatically for you. So you may need to explicitlytell flask application do py is what you want to use. Good question. AUDIENCE: So was it theline that said [INAUDIBLE] or was it environment variable? BRIAN YU: Good question. So did I not have to do that? I have my terminal configured such thatit will automatically run that line.It will automatically setthe environment variable. And we can give you instructionsfor how to do that as well. But otherwise, you can just need toset the environment variable yourself. AUDIENCE: But there’s also y in the– the application up higher thatsaid app equals [INAUDIBLE] BRIAN YU: Good question. So what’s this line doing? So all this line is doingis it doesn’t have anything to do with telling flaskwhich application to run. This is just us creatinga new variable that is going to be the source of this webapplication called app such that later I can tie specific functions to it. So I created this flaskvariable called app. And using that app, I’mnow able to say when someone goes to this route this isthe function that I want to run. And it it’s only usedinside of this file to determine what routes get called andwhat functions get called as a result.Good questions though. So that was our first web application. It just returned some basic textwhen we go to the web application. But that’s not all quite allthat interesting just yet. So let’s try and make things a littlemore interesting, in particular, let’s try and add a couple routes. So let’s go into routes 0and take a look at this code. So inside of application dot pyhere, we see that up until line seven everything is identical. I had app route slash. And when that happens, I wantto run this index function that just returns the text hello world. But here on line nine I’ve addeda special additional route, app dot route slash David.And when I go to slashDavid on my web application, it’s going to call this David function. And what that does is returnthe words hello David. So what’s the result of that going tobe when I run my flask application? Well, if I run flaskrun and then go back to this URL, this localURL just on my website, it just says hello world for now.It just shows me that default route. But if I go into my URL bar andchange the URL from just the default route to this URL slash David, forexample and press Return there, now it changes to hello David. So I have two separate routes nowrunning on my web application. If I just go to the defaultroute, it says hello world. If I go to slash David,then it says hello David. And that’s all because usingflask I was able to tie specific functions to particularroutes of my web application.Questions about how that’sbeen able to work so far? So if I wanted to add additionalroutes to do additional things, I could certainly do that. If I wanted to add a different routeto say hello to Maria, for example, I could add anotherline that app dot route slash Maria, define a new functioncalled Maria, in which case, I would return hello Maria.And now if I run– go to slash Maria onmy website, it’s going to say hello Maria, becauseI’ve added that additional one. But of course, this isn’tgoing to work for anyone. If I try and type myown name, slash Brian, I get a not found errorbecause I’ve typed in a route, but my flask application doesn’tknow how to deal with that route yet. It doesn’t know how to deal withmy name Brian, because I only have routes for the default route, theslash David route, and the slash Maria route.My name isn’t one of them. So what if I want to make my flaskapplication a little more powerful, and let it say hello to anyone,not just David and not just Maria? Let’s take a look now at routes 1,which will be an example of just that. So inside of application dot py here’swhat we have going on inside of routes 1. Up until line 7,everything is identical. We’re just saying hello world ifI go to the default slash route. But where things getinteresting is down here line 9. I have app dot route slash, and thenin angled brackets string colon name. This is not a particular routethat someone is going to, but a template for a wholegeneralized set of routes that people could potentially gofor it such that whenever anyone goes to slash and then any string– and we’re going tocall that string name– it’s going to call this hello function. And this hello functiontakes as an argument this name, a name thatgets passed in via the URL that the user typedinto their web browser. And what happens here? Well, I’m going to return thisformatted string hello comma, and then name in the curly braces,which is very reminiscent of one of those early Python filesthat we looked at way back at the beginning of lecturewhere I asked for a name to be typed in just at the commandline and then printed out hello name.This is exactly the same line, but it’scontained inside of one of these flask routes now such that thisroute is going to capture any string that I type in as a nameinstead of just David or just Maria. So if I now head over here and runthis application by typing flask run, and now I go to just the defaultroute, it says hello world. But if I instead go to slashDavid, it says hello David. I go to slash Maria,it says hello Maria. And I go to slash Brian,it says hello Brian. It’s able to take anystring that I type in, and just return helloto whoever that is. So I’ve already been able tocreate a dynamic web application. I didn’t have to create a separateHTML web page for each different person that I would want to say hello to.Just depending upon what’spassed into the URL, I’m now able to create a dynamicweb application that can say hello to anyone, hypothetically. And the beauty of this is thatthis is all just Python code. So anything you can do in Python,you can edit application dot py to reflect the changes inorder to update the website or update values of things tobe whatever you want them to be.So for instance, Pythonstrings have a method, a function that you can call upon themcalled capitalize that takes a name and capitalizes the firstletter of it, for example. So if I, in my hello function, justsaid name equals name dot capitalize, what that’s going to do is that ifI type in a name that’s the URL, it’s going to first capitalize thatname and then return hello that name. So before I type in slash Brian, itsaid hello brian with a lowercase b. I refresh the page now,now the B is capitalized because I’ve added this line 11 thatjust capitalizes that name for you before returning it back to the user. Questions about routes thatwe’ve seen so far in flask? Or how the applications work? Let’s take a look at some of the otherfeatures that we can have in flask. And the first thingthat we’ll probably note is that these web pages arevery, very simple so far.Right now all they do isdisplay some basic text. And of course, we could addwhatever HTML that we want to this. If I wanted hello Brian to be a headingfor example, instead of just plain text, I could return instead of helloname, like, H1 and then slash H1. If we recall from theHTML lecture, H1 is a way of making a big boldheading at the top of the page. And so if I return those H1tags surrounding hello name, now I when I refresh this page,hello Brian appears big and bold. I’m able to use whateverHTML content I want in order to return that information backto the user when they see it in their web browser.But of course, the HTML pages that youguys created in project 0 or HTML pages you might have created in other contextsare likely much more complicated than what could reasonablyfit in just a single string. You can make it very, very long. But that’s quickly goingto start to get messy. So what we want to do is organize ourflask application such that we can put HTML in HTML files, .html files justlike you were using for project 0, but somehow tie thosehtml files into flask. Tell flask to use those html filesthat we’ve already created in order to return something back to the user. So let’s take a looknow at another example. Here, inside of application .html,here is what we have going on. From flask we import flask. And we’re also importing a second thing. In addition to justimporting flask, we’re importing a function in aflask called render template. And we’ll see why that’s going tobecome useful in just a moment. Line 3 is exactly the same so far.We just have app equals flask name. Then on line 5 we create ourdefault route, app.route slash, then the index function. And instead of returninga string, just text that we want to displayto the user, I’m returning render template and then index.html. And what that’s telling flaskto do is take an index.html file and render that anddisplay it to the user instead of just displayingtext, plain text. So if you look at thestructure of where I have my files, in the same folderthat I have my application.py file I also have this templates directory. And inside of this templates directoryI have a document called index.html. And if I open up index.html,here’s what it looks like. It looks like an HTML file that’sgot a title that says my web page.And inside the body itjust says hello world. So what will now happen if I tryand run this web application? I go to that URL, and nowit displays hello world. And if I click and view thepage source of this web page, I can see the html content to thatweb page is the same as index.html. So what I’ve effectively donehere is, via a round about way using flask and Python,allowed us to just display an HTML page in the same waythat you’ve been doing already, just by writing the contentsinto the html itself and then opening up that HTML document.Questions about how we wereable to render that HTML file? AUDIENCE: Can you just give any functionthe index or whatever– yeah, there. BRIAN YU: As index.html? AUDIENCE: No, no. [INAUDIBLE] BRIAN YU: Oh, good question. So what is the logic behindthe name of this function? Does it have to be called index? The answer is no. Your functions can becalled whatever you want. But often times lateron we’ll see how it can be helpful to refer to a particularroute by the name of the function. And so making sure thatthe names of your functions are logical or meaningful insome way is usually a good idea. But this could be calledanything theoretically. Yeah? AUDIENCE: Index.htmlwas in a subdirectory. Was it searchedexhaustively [INAUDIBLE]?? BRIAN YU: Good question. So the question is howdoes it find index.html? Where does it know to look? Flask is only going tolook immediately inside of a subdirectory called templates. So I have to have in the samefolder as application.py a directory called templates, insideof which is index.html.And that is the onlyplace that flask will know to look for thoseindividual HTML files. Good question. So it doesn’t seem like so farthat we’ve gained a whole lot. We were able to do thedifferences in routes in order to say hello to different people. And that was something thatwe couldn’t do with just HTML. But so far what we’ve done nowis just created an HTML page that we’re now displaying to the user.And we haven’t added a whole lot. So let’s try and use Python to begin toadd some new features to this website that we didn’t have before. So let’s take a look at variable 0. So inside of variable0, what I have here is something a little bit different. So first couple of lines of the same. On my default route, I’m defininga variable called headline, which is set equal to hello world. And now on my next line, returnrender template– before, I just said return the index.html template.That is the html contentthat I want the user to see. But this kind of added an extra line. I’ve said return renderedtemplate index.html. But I’ve also said over here,I’ve passed an additional argument to the rendered template function. I said in addition toreturning index.html, you should also know that Iwant the variable headline to be defined and index.html to bewhatever headline this variable is equal to. So effectively, I am giving thisindex.html knowledge of a new variable, a variable called headline,which, is in this case, happens to be equal to thisPython variable called headline.So this is the variable thatwill exist inside the HTML file. This is the variable thatexists inside the Python file. And very frequently, it’s conventionalto give him the same name, although they don’t needto have the same name. So what is that going to do for me? What’s inside of index.html? Let’s take a look. So inside of index.html, insideof that templates directory, here’s what I have. HTML head, a title that says my website. It’s the same as what we’ve seen before.Inside the body though is wherethings get a little bit interesting. I have an H1 tag defininga heading that will just appear at the top of the page. But then in this doublequotation marks I have this– or double curly braces, rather, Ihave double curly brace, headline, and then end double curly brace. And this you can thinkof as a placeholder. In this HTML templateI’ve effectively said I have a headline thatI want to plug in here. And whatever the value ofthe variable “headline” is, that is what I want to substituteinto this HTML template. So my HTML templatedoesn’t know in advance the headline is supposed to behello world or just hello or welcome or some other heading altogether. But as soon as I have avariable called headline and I pass it into theindex.html file, then index.html will be rendered in such away that the headline will be filled in to that H1 tag. So if I run flask run rightnow and go to that web page, it says hello world, not because Ihad hello world inside of index.html.I don’t. But because in my Python code, I’vedefined this headline hello world. And that is what is getting passedinto my index.html template. So if I change this hello tojust hello without the world and refresh the page, nowthat headline updates as well, because the timeout isbeing dynamically generated, rendered by flask, depending uponwhat I pass into it as variables. Headline is hello in that case. Questions about how that worked? Yeah? AUDIENCE: Can you goback to index.html file? So the double [INAUDIBLE] BRIAN YU: This part? AUDIENCE: Yeah. So is that a propersyntax of that [INAUDIBLE] BRIAN YU: Great question. So what is this doublecurly brace index? It doesn’t really look like HTML and itdoesn’t really look like it’s Python.In fact, it’s entirely different,what’s called a templating language, an entirely separatelanguage called Jinja1, which is a standalone language. But it’s a language that flaskuses in its html templates in order to make it easy todynamically generate web pages. And so we’ll see a couple ofexamples of this Jinja2 syntax. It’s relatively intuitive. And it follows a verysimilar style to Python. So it has a lot in common withPython as you’ll soon see. But effectively, all weneed to understand for now is that the double curlybraces are Jinja2’s way of saying substitute something here. Put some value of a variable intothe template wherever that was. Great question though.So what’s the advantage ofallowing me to just substitute some variable into the templateinstead of just putting it into the template itself? Well, what I can do now isI can say app.route slash bye, if I want to add a goodbyeroute in addition to a hello route. And now I’ll need to find a new functioncalled by where the headline is instead going to be goodbye. And now I can take that sameline, return render template index.html where headlineis equal to the headline, but this time headlineis goodbye instead.So now I refresh this page– unexpected EOF. Let’s save the file and try again. So we have the defaultroute that just says hello. But if I change the URL to be slashbye instead, then what happens is I get goodbye to be displayed. And that’s going to be the new heading. So I’ve used the sameindex.html template. The only difference is I’ve changedwhat value I pass in as the headline. And as a result, what appears in thetemplate and ultimately what appear appears in the html thatthe user sees is different, depending upon what that was.Questions about that so far? Yeah? AUDIENCE: This Python count as back end? BRIAN YU: Does this Pythonfile come as back end? Yeah. What I’ve written here isPython code for a back end web server, that is listening for a requestlike, me typing in URL slash bye. It processes that request and returnssome response, in this case the HTML. So yes, this back end Pythoncode as you would term it.Yeah? AUDIENCE: And it updates dynamically? Like you don’t have to startthe application [INAUDIBLE].. BRIAN YU: Good question. Does it update dynamically? In this case, yes. I have flask set towhat’s called debug mode. And in debug mode flask willautomatically update any time I’ve made a change. But if you’re not in debugmode, then it typically won’t unless you restartthe flask server. So there are differentconfiguration options for flask. But there is a way to let it autoreload every time you make a change.Good question. So that is an example of it variablesthat we’ve been able to see, where we’re able to take valuesand plug them into templates. But what else can we do with templates? How can we make things alittle bit more interesting? Well, to introduce this,I thought we’d start by looking at an example of anextremely simple website that does exist out there on the internetthat really just serves one purpose. And that website is isitChristmas.com. If I go to isitChristmas.com on today,which happens to not be Christmas and I press Return, what I get is no. That’s all the web site does.It just says no, it is not Christmas. And presumably, on Christmas itwould say yes, it is Christmas. So what if we wanted to write a similarwebsite for a different holiday, say New Year’s for instance? And I want to write a isitnewyear’s.comtype website that says no if it’s not New Year’s and yes if it is New Year’s.How might we go about doing that? Well, we’re going to needsome sort of condition. We want our template to displayyes if it is in fact, New Year’s. And we want our template todisplay no if it’s not New Year’s. So how might we go about doing that? Let’s take a look now at conditionsand look at the code here. So this is application.py forour is it New Year’s website. So what I’ve done uphere is first import a Python module called date time. So Python has a bunch of differentmodules that serve different purposes. And so depending on whatyou’re trying to do, different modules may serveyour needs differently.In this case, the date time module hasa very easy way to get the current date. And that’s going to beuseful to me as I try and determine whetherit’s New Year’s or not. Then I import flask and rendertemplate, just like I did before. I start my flask application. I add my default route, which isgoing to call this index function. And here’s what’s happening here.I’m defining a variablecalled now, which is set to datetime.datetime.now,which is Python’s way of getting the current date and time. And so that’s going to be storedinside of a variable called now. And now I’m defining a Booleanvariable called new year, which is going to be true if it isNew Year’s and it’s going to be false if it’s not New Year’s. And how do I know whetherit’s New Year’s or not? Well, if now.month, the monthof the current date and time, is equal to 1 and now.day isequal to 1, then it’s New Year’s.So if both of these things aretrue, the month is equal to and the day is equal to one, thanit’s January 1st, New Year’s is true. Otherwise, New Year’sis going to be false. And then finally, I’mreturning this template. Return render template index.html,where the value new year is set equal to new year, which isjust this Boolean variable that I just created a moment ago. So I’m defining thisindex.html template telling flask I want to render that template.And I’m giving it thisBoolean information of whether or not it is a new year or not. And depending upon whetherit’s in New Year or not, that’s going to determine whatI want the template to display. And so let’s look atindex.html and figure out how it’s going to deal with this newyear variable that I’ve defined here, that I’m passing in to the template. Let’s look at index.html. So it’s a fairly simple html web page. Inside the head I’ve got a titlethat just says is it New Year? I’ve got some styling.And the only styling is that Iwant everything to be centered. And here’s the body. And here’s what’s going on inalso the Jinja2 templating syntax. I have this curly bracepercent sign, which is Jinja2’s way of introducingPython like syntax for conditions into the html file. I want my html file to have if’s andelse’s is in the same way that Python has if’s and else’s.And Jinja2 alongside flask lets usdo that by using this similar syntax. So inside a curly brace percentagesign I say if new year– in other words, if it isin fact, the new year, then here’s the HTMLthat I want to display. Yes, happy new year. Else, if it’s not New Year’s thenI have this H1 that just says no, it’s not New Year’s. And then end they have to signifythe end of the if statement. So this looks slightly differentfrom just regular Python, but the words are the same. If and else, for instance, those arethe same keywords that you would use.And this is Jinja2’s way ofsaying I want to conditionally use different html content dependingupon the values of variables that I’m passing into the template. So if New Year’s istrue, this is the html that should be rendered to the user. Otherwise, this is the htmlthat should be rendered instead. And so I’m able to dynamicallygenerate different HD, depending upon the values of these variables. So if I run flask run now and go aheadand go to my website, it just says no. Today doesn’t happen to be NewYear’s, so it’s telling me no. If, on the other hand, I wanted tosimulate it and pretend that it is New Year’s, let me just– after I setnew year equal to the month is one and the day is one– let me just override it.New year is going to be true. Let’s just tell our web applicationthat it is New Year’s today, even though it’s not, and refresh the page. And what happens now? Then it says yes, happy new year. So the HTML content isable to change depending upon the values of the variables. And if I look at the pagesource of this web page, it just says body and then this H1tag it says yes, happy new year. There’s no trace of that no thatwas inside of my index.html template because the template gets processedand rendered first on the web server.The server looks throughthe templates, figures out the conditions, figures out what htmlcode to include, what not to include, what to plug in to particularspots, and then takes that result and gives that result back to the user. So the user never seesthe original contents of the template with all thedifferent possible branches and different possible optionsthat could theoretically exist. And so using that code, we wereable to conditionally determine what to display on the HTML page.Questions about any ofthat we’ve seen so far in terms of Python or Jinja or flask? Yeah? AUDIENCE: What’s the reason why you putthe ir else on the index.html and not in the Python? BRIAN YU: Great question. So why did I put the if elseinside the index.html instead of inside of the Python code? I certainly could have putit inside the Python code.So I could have said somethinglike, I want my text to be yes, if it’s New Year’s, else if it’snot New Year’s, no for example. I could have done something like thisand then just passed in the text. But as we start to deal withmore complicated websites where I might wantentire sections of HTML to appear depending uponthe value of some variable, the conditioning inside of the templatewill become very, very helpful. You can imagine if thiswere a much longer thing that I wanted to display if it wereNew Years, like if it were New Years, I wanted balloons toappear on the screen. I might have a lot ofcode that’s necessary in order to make those balloons appear. And it would be infeasible to put all ofthat inside of the Python file itself.And so the conditions just offer away of changing the template such that all of the template codeis really inside the file. And then just based on thesettings of particular variables, I decide how I particularlywant to configure that HTML file for myparticular use case for this particular useron a particular day. Yeah? AUDIENCE: [INAUDIBLE]? BRIAN YU: Great question. Do you need to install Jinja2 inorder to make any of this work? What you will need to dois you’ll need to install flask, which is the micro frameworkthat we’ve been using in order to generate these web applications.And when you install flask,Jinja2 come along with it. So as you install flask, Jinja2will be first installed such that you can use flask and takeadvantage of all Jinja2 features that come along with it. Good question. Yeah? AUDIENCE: So with flask, we don’tuse Javascript anymore at all? BRIAN YU: Good question. Do we use JavaScript? We can still use JavaScript. We haven’t quite gotten there. But it’s totally fine to use JavaScriptinside of the client side of the web application, inside of the HTMLfile that the user ultimately sees. And that works prettywell with flask too. You can combine the two together. Yeah? AUDIENCE: Is it conventionalto call it– give it the suffix html in this Jinja file? BRIAN YU: Yes. The question was, what is theconvention for what to call the files? Generally speaking, ourtemplate files are HTML, even though they haveJinja added to them. And so by convention,we’ll still call them HTML files, since theircontents are predominately HTML. Good questions. So that was an example ofconditions inside of Jinja.But like Python, Jinja has abunch of additional features too. In addition to conditions, wealso have loops, for example. So how might we go about having someloops inside of our flask applications? Let’s take a look at an example of that. So inside of application.py,I’ve here, in the default route, just specified a bunch of names,Alice and Bob and Charlie. And on line eight I’m returningrendering the template index.html, passing in that whole list ofnames into my index.html template.And presumably in myindex.html template, I want to display all ofthose names on the web page. So what do I do inside of index.html? Well, here’s what’s going oninside the body of this page. I have a URL, which is injust an unordered list. And now I have this curly bracepercent sign syntax again. We used that samesyntax when we introduce a if statement or a condition in Jinja. We’ll do the same thing when we wantto add a for loop into our template. And we have for name in names. Same exact syntax as wewould have used in Python. And that means we’re going toloop over that list of names. And for each name, here isthe code you want to add.We want to add an li,a list item, where we plug in using that double curlybrace syntax the individual name. And so I’ve effectively saidcreate an unordered list. And inside of thatunordered list, for each one of the names in my list of names,add a li tag, inside of which is the actual name that I wanted. So if I now run this applicationand press Return, what I get is names big headlineand then one list item for each one of those individual names. I didn’t need to, on three separateoccasions, type li tag name slash li. I only needed to do that once. And because I have it insideof this loop that looping over this list of names, then it’sgoing to dynamically generate the list items as I need them. And so if I were to adda fourth name, like, I were to add David to my listof names and refresh it, it adds another list itemto that automatically, updating HTML such that if I actuallylook at the page source what’s happened is it’s created thisunordered list and then it’s created one list item for each oneof those items that was originally inside of my original list.Questions about loops orhow that was able to work? We’ll take a look at a coupleof other features of flask that are ultimately goingto be helpful as you start to build a web applicationsusing this type of technology. One thing that mightimmediately be helpful is figuring out how you linkto different parts of your web application. You might have one route that linksto another route and that route needs to link back to theoriginal route, for example. How would you go about doing that? Let’s take a look at some URLs. So inside of application.pyI have two things going on. I have a default route that just rendersan index.html page up and a slash more route that is going to rendera more.html page presumably for more information, more text, anadditional page worth of information.Nothing too crazy going on here,just two routes, each of which renders a different HTML template. Let’s take a look atthose HTML templates. Here is index.html. I have a heading that says first page. I have a paragraph of text. And then down here is wherethe interesting stuff happens. Here is where I willlink to the other route. So I have here in a hreftag which we’ve used before in order to link to a different page. But in this case, I’m usingthe special syntax curly brace curly brace andthen a special function in Jinja URL for, and then the name ofa Python function, in this case more. And so what I’ve donehere is said I want to link to whatever theURLs for the more function, in particular, thisis the more function, the one I’ve given thename more to, and I want to just link to whatever routewill take me to that function such that later on down the roadI might change that route.That route’s name might change such thatit appears as different to the user. But this code doesn’t have tochange, because all this code is saying is figure out what the URL isfor the more function and link there. And I’m using the doublecurly braces to mean substitute that URL in place inbetween the quotation marks here. Likewise in more.html I have basicallythe exact same thing going on. I have a heading. This the second page, a paragraphworth of text, and then actual saying, here’s where I want to link to. Go back to whatever route had theindex name of the function for it. And so what happens if Inow run this application? I have my first page that hasa whole paragraph of text. And when I click See More, thattakes me to the second page. And Go Back takes meback to the first page. And so this URL for syntax can beused in Jinja or in my Python code itself to just say get the URL thatwill take me to a particular function. And so that’s a helpful way ofoften linking to different files.And one thing you may benoticing at this point in time, is that there is a lot of similaritybetween my index.html file, that first page that I showedyou, and this more.html file, the second page that I showed you. In particular, they bothhave the same HTML head, title as my website on both of them. They both have this H1 at thebeginning of the body that has some title for the page. They both have this paragraph. And so ultimately thesepages are very, very similar. And what we might liketo do is find a way to factor out thosecommonalities such that I don’t need to copy paste my index.htmlpage create a more.html page.I can just take whatever iscommon to both of those pages and use it as a layout, as a templateto base these other pages on, and then modify those new pagesslightly in order to make the necessary adjustments that I need. That way, instead ofwriting the same code twice, I can just write the basictemplate from my web site once and fill in the blankswith whatever additional details that I have. So let’s take a look at that in flask. It’s a feature calledtemplate inheritance. So we’ll go ahead andlook at inheritance. And application.py is identical. The slash route justtakes me to index.html. The slash more routerenders the more.html. But here’s what’s different. Inside of my templatesdirectory I now have three files, an index.htmlfile, a more.html file, but also a layout.html file. And let’s look at thatlayout.html first. So what’s going oninside of layout.html? Well, I’ve defined the basiclayout for one of the web pages that I might want to have, eitheran index.Html or in more.html. I have my HTML header. The title is my web site. That’s the same for both. They both got a body. They both got an H1 that’sgoing to be the heading. But here I’ve added some special syntax,block heading and then end block. What I’ve done here is defined avariable section of my HTML template saying that a block of HTML contentcould go here called heading. And this is where that heading blockshould go, in between the H1 tags. And then after the H1 tags I haveanother block called the body block. And the heading and body arejust names that I picked. They could’ve been called anything. But I’m saying I havewhatever I call the body block should be inserted right here intothe body of my layout.html template.So now as you can begin to imagine, myindex.html file and my more.html file don’t need to redefine this entirestructure of what the HTML web page looks like. All they would need todo is simply say here is what belongs inside ofthe heading and here’s what belongs inside of the body. And aside from that, just usethis basic layout as my template that going to inherit from when Idefine what index.html and more.html ultimately look like. So what does index.html look like? Well, here’s that code. On line one up here, I’vesaid extends layout.html. In other words, index.html isgoing to be based on layout.html. So let’s just copy that HTMLand use that as the template that I’m going to use. But I want to make a couplekey changes or additions. Inside of block heading this is what Iwant to be contained inside of heading.I just want it to say first page. And then end block to say that’sthe end of that heading section. And then inside of thebody block, here is what belongs in the body of the website,this paragraph worth of text and then this link to going onto the more page. And that’s what’s containedinside of the body. And so if you rememberback in layout.html, we had that space forwhere the heading should go and that space for wherethe body should go. And all that’s goingto happen now is when I render index.html it’s goingto look to layout.html and try to plug in this heading content intowhere that heading block was and plug in this body content intowhere the body of that layout was, and render the resulting HTML page.And so likewise, inside ofmore.html I have the block heading that defines a slightlydifferent heading block and a slightly different body block. But ultimately, they are bothextending that layout.html default file that is where I am defining thegeneral structure of my HTML page. So if I run this web servernow and refresh that, it looks exactly the same. First page, see more takesme to the second page. But now notice that any changethat I make in the layout is going to then influenceboth index.html and more.html.If I add an extra line like, welcometo my layout file, now suddenly both on the first pageand on the second page they both have thisadditional welcome line. Because this is information that wasdrawn from my layout.html template from which both index.htmland more.html are extended. They’re getting theircontent from layout and basing themselvesoff of layout.html. And so as a result of all of that, we’reable to get this template inheritance whereby I can make a changeonce and see the impact of that all across the rest ofthe files that are also inheriting from that same layout. So in project 0 as youwent about designing a whole bunch of different HTML pagesthat were all about some central theme. And you may have noticed thatthere was a lot of repetition where you would need to copydifferent content from one page onto a second page and athird page and a fourth page.This offers a solutionto that problem, whereby you can define a simple layout thatis both shared in common amongst all of your pages, and thenon each individual page, just define the sections that aredifferent from one page to another. And this is often a betterdesign for your websites. And you can see how flaskgives us the ability to leverage this templateinheritance in order to create these websites that justhave certain parts of each HTML page that differ from one page to the next. Questions about templateinheritance or how we were able to base HTMLfiles off of other layouts? Let’s take a look at acouple of other things. Let’s take a look at forms now. So if you remember backto our HTML lecture, we talked about how youcan go about creating HTML forms just by using form tags. But up until now, those formsdidn’t really do anything. You would submit the formand nothing would happen. Now that we have a back end server,a Python flask server that’s running and listeningto requests, we can begin to take the results of those formsand do something interesting with them.So let’s look at forms andlook at application.py. So first thing to notice isthat our index function is just going to be returning index.html, verysimilar to all of the rest of the web pages we’ve done. Don’t worry about thissecond function for now. But let’s just look at index.htmland see what it’s doing.So index.html is extendinglayout.html just like it did before. Our heading is going to say first page. And here’s what’s in thebody of this web page. It’s going to be a form,and in particular, this form is going to have an action. The action is when I submit thisform, who should be notified or where should I besubmitting this form to? And in particular, it’s going to bethe URL for a function called hello which we saw back anapplication.py, but we’ll take another look at that in a moment. And we’re saying the method forthis request is going to be post. So HTTP request, whichwe talked about before is the process by which your browsermakes a request to a web server to get information, these requests cancome in a number of different methods where by default, if I go togoogle.com and press Return, I am making a GET request.I’m asking to getinformation from a web page. And so the default requestmethod is just yet. And so far in all the flaskapplications we’ve been building, we’ve been using that default GETrequest method for all of our routes. But this time for our formwhen we’re submitting data to the server, oftentimes that willuse a slightly different request method called post. And so here we’re sayingwhen I submit data to hello, use the request method postto mean I want to submit data as a form to the web server. What data am I submitting? Well, I have an input field whosetype is text, whose name is name. That name will now become relevant. I’ve given a name to the input field,in this case it’s just called name.And the placeholder justsays enter your name. And then I’ve added a buttonthat will submit this form. So this is a form muchlike the ones we’ve already seen before, the onlydifference is that now we’ve enclosed it inside of a Jinja templateinstead of just a normal HTML file. Now what’s going on in application.py? What’s happening? On line 9 here is my slash hello route. And in particular, I’mtelling this route here is the request method you should accept. People are going to be submitting datato this route via the post method. They’re going to be submitting datavia post to this hello function. So what should this hello function do? Someone types in their name into theform, they press the Submission button.This function gets called. What happens? Well, up here on line 1, from flaskI’ve imported flask and render template just as before, but I’ve alsoimported this thing called request that is going to representwhatever request the user has made to my web server. And so now here on line 11 I’mdefining a new variable called name. And I’m saying nameshould be equal to what? I’m going to take thatrequest that the user made. Access the form, request.form. And let’s get whatever partof the form was called name. So if you remember back in the formitself, in the HTML code, on the input I gave it a name attribute which wasequal to in quotation marks “name.” That’s what this is, the name of theinput field that I’m trying to access.And I’m going to access thatinput field and just call it name. And what am I going to dowith that variable name? Well, I’m going torender a template called hello.html, passing in that nameas a variable into the template. Just like we were passing namesinto the template before in order to say hello to different people, thisis going to do much the same thing. But instead of gettingthe name from the URL, we’re going to get the name from theform that the user just filled out. So how is that going to work? Let’s look at hello.html. Inside of hello.html the headingis just going to be the word hello. And the body of the website ishello, and then in those double curly braces to mean plug in a value here. I’m plugging in thevalue name, because I want to say hello to whoever the nameis, but I don’t yet know who it is. And again, both of these files areextending that basic layout.html file that defines the generalstructure for a web page.So what happens if I nowrun this web application? I go to the web page. This is the first page. Here is the form. I can enter my name here. So if I type my nameand press Submit, I’m now submitting that form tothe slash hello route via post. I’m sending the data withinthe form, in this case my name, to the slash hello route. And what that’s going to do is runthe code inside of my hello function.And the result of that is thatit’s going to say hello Brian. Again, why did that happen? It’s because in index.html, the action,where the form should be submitted to, is the hello function. Then inside of application.py,here is the hello function. What happens inside of it? I first get the name from theform, request.form.getname. Save it in a variable called name. And then render the templatehello.html, passing that name variable in as a value that I want to thendisplay in the resulting template.And so now I’ve created aform just like I did before, but I’m doing something with the form. I’m taking the data that theuser passed into the form, and using it to generate adynamic HTML page just for them. Questions about forms orhow we made that happen? Yeah? AUDIENCE: What happens if youjust typed in the URL dash hello? BRIAN YU: Great question. Question is what happens if,instead of submitting the form, which goes to slash hello? I were to instead, just go tothis URL slash hello, and just press Return there? So recall that when you typein a URL and just press Return, that is a get request. The default requestmethod in HTTP is just trying to get thecontents of a web page. And here, I’m just going to askto get the contents of hello. I’m not submitting anyform data to hello. What I get is method not allowed. This method is not allowedfor the requested URL. And why is that the case? What is it about thesefour lines that caused me to get a method not allowed error? Any guesses? Yeah, it’s this method equalspost part of the route that says the only request methods I shouldaccept is the request method post.If someone just tries toget the page normally, then there should be some sort of error,because that’s not a supported request method. I could try to support both. I could say I want to supportboth, just someone typing flash hello, and someone going to the regularroute and submitting the form via post. And to do that, I would justsay method equals GET and POST. I can have a list of differentrequests methods that I allow. And here I’m saying the flash slow routewill accept both GET requests and POST requests. How do I tell them apart? Well, I can use thisrequest object again. I can say if request.method equalsGET, for instance, let’s just return please submit the form instead, else,if the request method isn’t GET, which means the request method has to bePOST, then do the same thing as before.Get the name, and then returnthe hello.html template with the name filled in. Now if I go to slash hello, what Iget is please submit the form instead. Because I tried toaccess this page via GET. But instead, if I just go to thedefault page and type in my name, and submit that form,then I get the hello. So flask is able to detectwhat the request method is. And if the request method is GET, do onething, if the request method is POST, do something else.And so flask candifferentiate between just trying to access the page versus tryingto actually submit data to that page. Other questions aboutthat or other things? We’ll take a look at one other example. So, so far, our web applicationshaven’t been able to– question? Yeah? AUDIENCE: So if the form had a GETmethod specified with [INAUDIBLE],, would the request form get– BRIAN YU: So the question is if theform, instead of being method POST, were method GET, and I tried tosubmit by the GET method instead? Well, in this case, it’s going to getcaught in request.method equals GET. So what will happen is thatif I go to the default route and try to type in my name andsubmit it, I’m going to get please submit the form instead,because it was a GET request. But hypothetically, you could alsohave data submitted via GET instead. When you submit data via GET,that data gets put into the URL.So notice that what changed hereis that I requested slash hello and then question mark nameequals Brian, where that basically means that I’ve submittedform data via GET, and that data is all put into the URL. And so the result ofthat is that you can change what’s in the URL to changewhat the specific request is. This is also not a good idea ifthere’s any sensitive information that you want to submit via a form.If someone’s typing in their passwordfor example, to log in to your website, you don’t want that form to besubmitted via GET, because now in the URL, that appears intheir URL history for example. Their password’s just going tobe plainly visible in the text. And so oftentimes, for moresecure form submissions you’ll want to use POSTrequests instead of GET.But you could alsosubmit data via GET too. I’m just going to changethat back to POST. Good question, though. So thus far, our webapplications haven’t really been able to store information. We’ve been able to useweb applications in order to take information anddo something with it, whether it was thename that someone typed into the URL to say hello to them. Or whether it was a formthat users are filling out that they fill out the form,press Submit, and then the website says hello to them.But now we’d like tocreate a website that is able to store information,retain information, and use that information later, for example. And that’s where we can start tointroduce the concept of sessions. And so sessions in flaskor in web programming, more generally is the idea that whenyou log in to the web site, you have access to some session thatis data specific to your user account. So I log into Google.com. And I see that I’m loggedinto my Google account and have access to my Googledocuments, for instance. Whereas you might log into Googleand see an entirely different thing, depending upon how youare logged in as well. So how can we begin tomake use of those sessions? Let’s take a look at a example. So this doesn’t yetactually use sessions. But it’s an example of usbeing able to store data. So let’s say I wanted to create anote taking application, for example.So how might I create anote taking application where I want to be able tostore different types of notes that people are typing in orderto record notes and save notes on this website? So what do I have going on? On line 10 I’ve definedthis notes variable to so far, just be an empty list. It’s just going to bean empty list of notes that is going to store the notes thatI’m eventually going to be saving. Then I have a default index route,where inside of this index route, I have a couple of things going on. If the request method is POST,which we haven’t yet seen. But if I were to submit datato the index form– and I’m not sure how I would do that just yet.But we’ll see in a moment. Then what do I want to do? I want to access whatever noteI wanted to add presumably, because I just tried to add a note. And then notes.append note it’s myway of saying take this list of notes and add a new thing to the list. In particular, add thisnew note to that list. So that’s what happens ifthe request method is POST. If I submit data to this indexfunction, then what I should do is add a new note to my list of notes. And then otherwise, if I didn’tsubmit any data, or even if I did, just at the end, return thisindex.html passing in my list of notes. What’s happening inside of index.html? Well, what I have here is a for note innote, print out each individual note.And all of that is storedinside of an unordered list where have an ordered list of notes. So what that’s going to do, ismuch like we saw that list of names that we could then use togenerate one name at a time in order to display alist of names, we can display a list of notes thatwill display one note at a time on each item inside an unordered list. Then lower down on thepage, I have a form.And this form is presumablywhere I could add a new note into my notepad web application. This form is going to have an actionof going to the index page, that’s where I want it to go. The method is POST, just like before. And this is very similarto the form we just saw. It’s got an input field whosename is note this time, and whose place holder is enter yournote here, and then a button to add a note to my list of notes. So we’ll take a look atall that in just a moment. But let’s take a look at how theweb application actually works. And then take a closerlook at what’s actually going on inside of flaskand the application.py to make all of that possible. So I’ll go ahead and flask run this. I’ll go to the default route. And what I see here is just a headingthat says notes and then this form.Enter note here, and then add note. So what happens if I type helloas a note and click Add Note? Well, that will add helloas just a note that I’ve now recorded inside of this list. And if I add helloagain, as another note? It adds that too. So how is that working? Let’s take another lookback at index.html. When I add a note, what’s happening? I’m submitting this form. And I’m submitting this formback to the index function or whatever URL maps to the indexfunction, which in this case is just slash. And I’m submitting that data via POST. What’s then happeninginside of application.py? Well, I’m maintaining thislist of notes right here, just an empty list tostart out with, which is why I have no notes to begin with. But then in the index function,if the request method was POST, if I did try and add a note,then what’s going to happen? I’m going to set noteequal to whatever is the note parameter of thatform, whatever thing in the form had a name called note.And then I’m going to append tomy already existing list of notes, that new note. And then only at theend of all of that am I going to render thetemplate index.html, passing in that whole list of notes. And what that’s goingto do is ultimately save all of those notes as a variablethat is accessible to my entire web application. And so what’s going to happen thenis that if I type in a third note and add the note,that’s going to appear. And if, for example, I were to closethis web page, but open it up later and type in the URL again,those notes are still there.My web server is saving thevalue of all those notes as a variable inside of the web server. And as a result, I can see all thosenotes even if I close the web page and open it up again later. Those notes are still retained. If on the other hand, I were to everfor some reason shut down my web server. And you can quit flask bypressing Control-C, for example, and start up again bytyping flask run, now I’ve restarted the whole web server. It’s completelyrestarted application.py. And when I refresh this page,now my notes are gone again. And so I’ve lost access to all ofthem because the server was shut down.And when it restarted,everything was reset. And so next week we’ll beginto look at database design, and how we can resolve thisproblem by trying to figure out how do we take data that the usersubmitted and store it somewhere longer term, somewhere that evenif the server goes down and come back later or even if we’reaccessing it from somewhere else, we can still get back at that same data. And so that’s where using andtaking advantage of databases will become quite helpful. But one last thing to noteabout this particular website is that this notesvariable is what we call a global variable, accessibleacross the entire application, which means that if I’m using this webapplication and taking notes with it, and potentially, someoneelse also wants to use my web application on theinternet, presumably, we don’t want to be working withthe same note pad, so to speak.I want to be able to take my own noteswithout seeing someone else’s notes. And I don’t want someone elseto be able to see my notes. But if I just have thesingle notes variable that’s shared across theentire web server, then even if someone elsetries to visit my website, they’re going to see all ofthat entire same set of notes. And so that’s wherethe concept of sessions begins to come in, thatwhen I log into my web site, I want to see my list of notes.And when someone else logsinto the same web site, they want to see their list ofnotes without those lists of notes ever overlapping, so to speak. And so how do we make that happen? What changes do we need to makein order to allow for that? Well, what we’re going to dois from flask, import session. And that gives us access to a variablecalled session, which we can then use them in order to keep variablesand values that are specific to a particular user, such thatI have my own session that’s all data specific to myinteractions with the website, and someone else has their own sessionthat has all of the data specific to their interactionswith their website. And then on line two I’m importinga special additional extension to flask called flask session.This just give us a little bit morecontrol over sessions, in particular, it lets us store session “serverside” such that on our server we’re storing all the dataabout the sessions which gives us just a little more controlover how the sessions are managed. But not to worry too much about that. What’s important is that I nowhave access to this variable called session which is unique to me, such thatnow if I, instead of saying that notes is going to be this global variablethat everyone has access to, I can treat the session as adictionary that is specific to me. So I can say session square bracketnotes is equal to the empty list, to mean I want my particular sessionto have an empty list of notes, for example. And then, instead of notes.appendnote,I can say sessionnotes.append notes. Rather than append this new note tothe entire global variable representing all of the notes, I onlywant to append the note to the notes specific tomy particular session, to my interaction with this page.So what’s going to happenhere now if I try and run this web application is I can try andtype my first note and nothing happens. AUDIENCE: You missed thelast line, [INAUDIBLE] BRIAN YU: Oh, wonderful. Thank you. So notes should besession notes instead. And if I run this again, it say notes. I type in my first note. I add the note. Now the first note appears. What happens if I tryadding a second note? What’s going to happen? It overwrote the first note. First note went away. Why did that happen? Any ideas? AUDIENCE: You’re resettingthe session notes each time. BRIAN YU: Exactly. On line 14 here, I’vereset session notes. So I needed to give sessionnotes some initial value in order to say if session notes doesn’texist, it needs to have something. But if I have it here inthe index function, then every single time Isubmit new data to index, it’s going to clear outall of my own old notes.And that’s clearly not what I want. So maybe I want something likethis, if session.getnotesisnone. In other words, if I try andget the notes from the session and it doesn’t exist, then I wantsession notes to be an empty list. In other words, if I didn’thave any notes already, let’s initialize notesto be an empty list. That way it exists, at least. But otherwise, let’s justkeep it as what it is. So now it’s a second note. Now if I type third note and adda note, it adds the third note just like we would expect it to. And so the advantage here is that now Ihave multiple different sessions going on, such that this particular user isindependent of other particular users.We don’t have one shared notes variableacross all of the different users. And if you were toeventually go to my website if I hosted somewhere on the internet,that will have its own set of notes, and so on and so forth, sothat everyone’s user accounts can be kept separate. And so questions about sessions, or howwe might go about storing data inside of our flask applications? AUDIENCE: So if you close thebrowser now, you lose your notes? BRIAN YU: If I close the browsernow and then go back to it, I get to keep my notes. Because it’s still storedinside of the session. AUDIENCE: It knows your session? BRIAN YU: It knows my session, yeah. It is able to identifymy particular web browser request by a cookie, just a value that’sbeing stored inside the web browser.And so the next time that I makeanother request to that web page, it recognizes me and says oh,I know exactly who you are. Here are the notes thatI have saved for you. And it can display my notesback to me that way as well. And so you can imagine thisbeing useful for websites where you have to log in andsee particular data that’s very pertinent to you. Yeah? AUDIENCE: Just to be clear, so line10 in your file is no longer needed. BRIAN YU: Line 10 in thisfile is no longer needed because I no longer have a globalnotes that is shared across everyone. I only have notes that are veryspecific to a particular user’s session. Good question. Yes? AUDIENCE: Is there any websitethat describes all of this kind of [INAUDIBLE]? BRIAN YU: Is there a websitethat describes all this? Yeah. So flask has great documentation. If you just go toflask’s web site, you’ll see descriptions of basicallyall of these features plus more in great detail, giving youexamples of different features of using the flask framework. So what we’ve seen so far is just ataste of what flask is able to do. We’ve seen it able to build routesfor us, build templates for us. We’ve been able to add logic like loopsand conditions into flask templates as well. But it’s got a whole lotmore features as well. And in particular, next week we’llbe diving into building databases and connecting databasesto flask, such that flask can better interact with datathat’s provided by users, such that we can better manage useraccounts and manage relationships across different kinds of data.And all of that is coming next week. But for now, that’s Python and flask. And we’ll conclude here for today. Thank you all.

As found on YouTube

Share this article

Leave a comment

Related Posts