Skip to main content

Flask!

 Flask!

The reason that we've spent the last few days learning HTML & CSS is so that we can combine them with Python by using Flask.


Flask lets us build our own web-server. This means that it runs all of the time, creating the pages for your entire website.


The reason Flask is different from just using HTML/CSS is that it can be used to build dynamic web apps that change depending on the user.


A web server works slightly differently. We make one web server, click run, and give the website address to anyone who wants to use the program. This means that we can make our code private if we want.


Heads up here. Flask is a paid feature on Replit. You'll need to purchase cycles or hacker plan if you want to use it. It is super worthwhile if you want to keep your code private though.


You can set your repl to private in the drop down menu from the top of the page.


πŸ‘‰ Let's dig into the boilerplate code that you get when you start a Flask repl. Read the comments for explanations:

from flask import Flask # Imports the flask library


app = Flask(__name__) # Starts the Flask application. The 'app' variable is very important. We'll be using that later.



@app.route('/') # Tells the code what to do if we've gone to our web address with just a / after the URL

def index(): # Tells the code which webpage to show. This subroutine will display the 'Hello from Flask' page

    return 'Hello from Flask!'



app.run(host='0.0.0.0', port=81) # This line should ALWAYS come last. It's the line that turns on the Flask server.



πŸ‘‰ When we run this starter code, here's what we get :






More Pages

πŸ‘‰ Next, I'm going to add a 'home' page to the Flask code.


from flask import Flask

app = Flask(__name__)

@app.route('/')

def index():

    return 'Hello from Flask!'

@app.route('/home') # Creates the path to the home page

def home(): # Subroutine to create the home page

  # Three quotes followed by the html for the baldies site. Three more quotes to close. All the HTML is assigned to the 'page' variable

  page = """<html>

    

  <head>

    <title>David's World Of Baldies</title>

  </head>

  <body>

  <h1>Dave's World of Baldies</h1> 

  <h2>Welcome to our website!</h2>

  <p>We all know that throughout history some of the greatest have been Baldies, let's see the epicness of their heads bereft of hair.</p>

  <h2>Gallery of Baldies</h2>

  <p>Here are some of the legends of the bald world.</p>

  <img src="images/picard.jpg" width = 30%> 

  <p><a href = "https://memory-alpha.fandom.com/wiki/Star_Trek:_Picard">Captain Jean Luc Picard: Baldest Star Trek captain, and legend.</a></p>

  <ul>

    <li>Beautiful bald man</li>

    <li>Calm and cool under pressure</li>

    <li>All the Picard memes</li>

  </ul>

  <p><a href = "page2.html">Go to page 2</a></p>

  

</body>

  

</html>

  

  """

  

  return page # returns the contents of the page variable

app.run(host='0.0.0.0', port=81)


Now if we visit the page URL/home in our browser, we will be whisked to the home page to view the design masterpiece that we've created.


You may notice here that the images are missing, so that's what we're going to do next.

Images With Flask

To get images with Flask, we have to:


Create a folder in the file pane. By default, it's called 'static'.

Upload any files you want your webpages to access - images, audio, video etc. (You can create subfolder structures in the static folder to help you stay organized).

Add a new property to the app = Flask line of code:

app = Flask(__name__, static_url_path="/static")


I've added an 'images' subfolder and uploaded my Picard image to there.



Now I've updated the <a href> tag to reference the 'static' folder:

<img src="static/images/picard.jpg" width = 30%>
fStrings With Flask
One of the cool things we can do is use fStrings to format some content inside our webpages.

πŸ‘‰ Let's say I want to insert today's date on the homepage. I will:

1.Write the code to get the date inside the home subroutine and assign to a variable.
2.Format the HTML as an fString.
3.Use curly braces to drop the date variable into the HTML. 
Here's the code with comments to show the changes.

from flask import Flask
import datetime # import the datetime library
app = Flask(__name__, static_url_path="/static")
@app.route('/')
def index():
    return 'Hello from Flask!'
@app.route('/home') 
def home():
  today = datetime.date.today() # Get today's date
  page = f"""html 
  # Format the html as an fString
  <html>
    
  <head>
    <title>David's World Of Baldies</title>
  </head>
  <body>
  <h1>Dave's World of Baldies</h1> 
  <h2>Welcome to our website!</h2>
  <h2>{today}</h2> #Drop the date variable inside curly braces.
  <p>We all know that throughout history some of the greatest have been Baldies, let's see the epicness of their heads bereft of hair.</p>
  <h2>Gallery of Baldies</h2>
  <p>Here are some of the legends of the bald world.</p>
  <img src="static/images/picard.jpg" width = 30%> 
  <p><a href = "https://memory-alpha.fandom.com/wiki/Star_Trek:_Picard">Captain Jean Luc Picard: Baldest Star Trek captain, and legend.</a></p>
  <ul>
    <li>Beautiful bald man</li>
    <li>Calm and cool under pressure</li>
    <li>All the Picard memes</li>
  </ul>
  <p><a href = "page2.html">Go to page 2</a></p>
  
</body>
  
</html>
  
  """ 
Linking With Flask
πŸ‘‰ Let's add a link from our index to our home page. I'm just going to show the index part of the code to add some quick content with a link.

from flask import Flask
import datetime # import the datetime library
app = Flask(__name__, static_url_path="/static")
@app.route('/')
def index():
  page = f"""<html><body>
  <p><a href = "/home">Go home</a></p>
  </body>
  </html>"""
  
  return page



Comments

Popular posts from this blog

Automate! Automate!

 Making this customizable πŸ‘‰So how about making our search user customizable? In the code below, I have: Asked the user to input an artist (line 14) Tidied up their input (line 15) formatted the search URL as an fString that includes the artist (line 19) Here's tAutomate! Automate! We are so close. I can taste it, folks! Massive kudos on getting this far! Today's lesson, however, will work best if you have one of Replit's paid for features (hacker plan or cycles). Free plan Repls 'fall asleep' after a while. Automation kinda relies on the Repl being always on. If you have hacker plan or you've bought some cycles, then you can enable always on in the drop down menu that appears when you click your Repl name (top left).he code: This is important because when our repl is always running, it can keep track of time and schedule events. πŸ‘‰ I've set up a simple schedule that prints out a clock emoji every couple of seconds. It works like this: Import schedule librar...

HTTP & Sessions

 HTTP & Sessions One of the main protocols (rules that govern how computers communicate) on the web is called HTTP. HTTP is what is known as a stateless protocol. This means that it doesn't 'remember' things. It's a bit like having a conversation with a goldfish. You can ask a question and get a reply, but when you ask a follow up question, the original has already been forgotten, as has who you are and what you were talking about. So if HTTP is stateless, how come my news site remembers to give me the weather for my home town, my preferred South American river based online store tells me when it's time to order more multivitamins, and I'm justifiably proud of my #100days success streak? The answer is......... Sessions Sessions are a way of storing files on your computer that allows a website to keep a record of previous 'conversations' and 'questions' you've asked. By using sessions, we can store this info about the user to access later....

Incoming!

 Incoming! Today, we're going to learn how to deal with data from forms in Flask. πŸ‘‰ To start, I've added yesterday's HTML code for my form in main.py for you already. (You're welcome!) Go take a look! πŸ‘‰ However, at the moment, the app.route() has no method associated with it, so I need to create a route for this page to receive the data. First, I need a new import: request. Then I create the app.route - I also need to add an extra argument to specify the methods being received. At the moment, that's just 'post', but it does need to be ALL CAPS - POST. Finally I define the process() subroutine that returns request.form πŸ‘‰ Here's the new code on its own: from Flask import Flask, request app.route('/process', methods=["POST"]) def process():   return request.form πŸ‘‰ And here it is as part of the whole code: from flask import Flask, request app = Flask(__name__) app.route("/process", methods=["POST"]) def process():   ...