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)

OS LIBRARY , TIME LIBRARY

  What is the os library? It allows us to "talk" to the console. One of the most powerful things we can do with this library is allow it to clear the console EXAMPLE: import os print("Welcome") print("to") print("Replit") os.system("clear") username = input("Username: ")  Time Library We can import a second library by placing a  ,  after the name of the first library. EXAMPLE: import os, time print("Welcome") print("to") print("Replit") time.sleep(10) os.system("clear") username = input("Username: ")  NOTE:  from replit import audio import os, time def play():   source = audio.play_file('audio.wav')   source.paused = False # unpause the playback   while True:     stop_playback = int(input("Press 2 anytime to stop playback and go back to the menu : ")) # giving the user the option to stop playback     if stop_playback == 2:       source.paused = True # let'...

ALL ABOUT WHILE LOOP

 WHILE LOOP  A  while  loop allows your code to repeat itself based on a condition you set.   EXAMPLE : counter = 0 while counter < 10:   print(counter)   counter +=1 Infinite Loop  You have to be  really  careful that you don't accidentally invoke an infinite loop! This is where the computer will loop code until the end of time. Without a break. Forever.  This is just saying "count to 10 by 1 each time." to make the loop end. Don't forget, if your  condition  is a  >  then you might need to  -= . This will subtract from the variable instead of adding to it.   EXAMPLE : counter = 0 while counter < 10:   print(counter)    counter += 1