Section_9: Flask
-
Flask
is amicro-framework
forPython
. -
Jinja
is atemplate engine
forPython
.
Together they allow developers to build more dynamic applications than it is possible with only HTML
, CSS
and JavaScript
.
Flask
powered website:
https://address/
Returns the root of the website
- We think of a website often having these routes we can go to see different parts of it.
- For this example
/browse.cgi
is the route we want to go to.
- We could even, add some parameters to it and look at particular books, using something like this, having parameters in these dot dot dots at the end here.
-
You can imagine this website is full of these
HTML
pages look a bit like this. Or we have maybe trillions ofHTML
pages full of different text. -
So if I were to
request a page
from thisserver
right here, I can make anHTTP request
. I might say this: Give me the slash browse.cgi page.
- Instead of having this:
-
Would probably be better, if we could actually have
a single HTML page
and we could just kind ofslot in
some random string of text to that page using something likePython
orFlask
, in this case. -
So we could do something like this, where instead of having millions and millions of pages that have all these random strings of text, we could have one page and we could use
Python
toslot in
a single random string for us-- perhaps like in this example, we could have aplaceholder
.
Explore Library Flask
app.
<form>
<input type="text">
<button type="submit">
Submit
</button>
</form>
-
This won't work because we need to specify where the data is going to be sent.
-
We need to specify the
action
and themethod
properties for theform
.
<form action="/" method="post">
<input type="text">
<button type="submit">
Submit
</button>
</form>
-
If data is sent via
POST
, it won't show up in theURL
. -
But if data is sent via
GET
, it will show up in theURL
using theseURL
parameters. -
Notice how in addition to a
type
, which is now omitted up here by default, we have thename attribute
of our input. And this one is calledpage
. -
We could
reference
that very same name in ourPython
code to then get the value that that input holds at the time the form is submitted.
-
If a request was submitted via
GET
, we could userequest.args.get
. -
But if a request was submitted via
POST
, we could userequest.form.get
.
POST
Example:
GET
Example:
- This
SQL
query creates a table called history
CREATE TABLE history (
id INTEGER,
page INTEGER,
PRIMARY KEY(id)
);
id | page |
---|
- For now we have an empty table;
INSERT INTO history (page)
VALUES (50);
id | page |
---|---|
1 | 50 |
INSERT INTO history (page)
VALUES (100);
id | page |
---|---|
1 | 50 |
2 | 100 |
INSERT INTO history (page)
VALUES (43);
id | page |
---|---|
1 | 50 |
2 | 100 |
3 | 43 |
db.execute("INSERT INTO history (page) VALUES (43);")
db.execute("INSERT INTO history (page) VALUES (?);", placeholder)
id | page |
---|---|
1 | 50 |
2 | 100 |
3 | 43 |
Return to CS50x