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

FOR LOOP , RANGE

  FOR LOOP  A  while  loop is perfect to use when we  don't  know how many times we want the loop to repeat.  If we have an idea of how many times we want the loop to repeat, we can use a  for  loop to loop code in exactly the same way the  while  loop did.  EXAMPLE :  for counter in range(10):   print(counter) RANGE  The  range  function creates a list of numbers in the range you create. If you only give it one number, it will start at  0  and move to a state where the final number is  one less  than the number in the brackets. In this case, the final number would be  9 .  EXAMPLE :  total = 0 for number in range(100) :   total += number   print(total)

CONTINUE COMMAND AND EXIT LINE

  The Continue Command  The  continue  command stops executing code in the loop and starts at the top of the loop again. Essentially, we want to kick the user back to the original question. EXAMPLE : while True:   print("You are in a corridor, do you go left or right?")   direction = input("> ")   if direction == "left":     print("You have fallen to your death")     break   elif direction == "right":     continue   else:     print("Ahh! You're a genius, you've won") NOTE :  The  else  statement refers to any input besides left or right (up or esc). Since the user is a winner, we do  not  want to use  break  or it would say they have failed.  EXIT  COMMAND LINE  The previous code continues to loop even after the user has won. Let's fix that with the  exit()  command EXAMPLE: print("Let's play chutes and ladders. Pick ladder or chute.") while...

IF AND ELSE STATEMENT

  If Statements    These statements are a bit like asking a question. You are telling the computer:  if  something is true,  then  do this specific block of code. Double equals ( == ) is asking the computer to compare if these two things are  exactly  the same.  EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  What is else? IF  the condition is  not  met with the  if  statement, then we want the computer to do the  else  part instead. Likewise, if the condition  is  met in the  if  statement, then the  else  bit is ignored by the computer. The  else  statement must be the first thing  unindented  after the  if  statement and in line with it    EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  print("Welcome Dude!")  print("You're just the baldest dude I've ever seen...