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

Web Scraping

 Web Scraping Some websites don't have lovely APIs for us to interface with. If we want data from these pages, we have to use a tecnique called scraping. This means downloading the whole webpage and poking at it until we can find the information we want. You're going to use scraping to get the top ten restaurants near you. Get started πŸ‘‰ Go to a website like Yelp and search for the top 10 reastaurants in your location. Copy the URL.   url = "https://www.yelp.co.uk/search?find_desc=Restaurants&find_loc=San+Francisco%2C+CA%2C+United+States"   Import libraries πŸ‘‰ Import your libraries. Beautiful soup is a specialist library for extracting the contents of HTML and helping us parse them. Run the Repl once your imports are sorted because we want the Beautiful Soup library to be installed (it'll run quicker this way). import requests from bs4 import BeautifulSoup url = "https://www.yelp.co.uk/search?find_desc=Restaurants&find_loc=San+Francisco%2C+CA%2C+Unite...

It's Called Hashing,Hashing, Printing the Hash , Salty, Second User ,

 It's Called Hashing One of the big issues with storing usernames and passwords in a database is what happens if we're hacked? If those passwords are stored as text, our users' security is compromised. Probably across multiple sites because they ignored our advice and used the same password for everything!!!!! Hashing  In reality, organizations don't store your actual password. They store a hash of your password. A hash is produced by turning your password into a sequence of numbers, then passing it though a hashing algorithm (some mathematical process that is very difficult to reverse engineer). The data spit out of this hashing algorithm is what's stored instead of your actual password. πŸ‘‰ So let's do it. I'm using the built-in hash function to create a numerical hash of the password  password = "baldy1" password = hash(password) print(password) # This will output a really long number  πŸ‘‰ Now let's store that hashed version in our database in...

Hide & Remove,Come Back!,

 Hide & Remove DISCLAIMER: I promise the good stuff is coming back. We have to go through the valley to get to the mountain, right? Sometimes, we want to remove a button, image or piece of text from the screen. To do this, we use pack_forget(). πŸ‘‰ We'll start with our default tkinter program. import tkinter as tk window = tk.Tk() window.title("Hello World")  window.geometry("300x200")  hello = tk.Label(text = "Hello World")  hello.pack()  button = tk.Button(text = "Click me!")  button.pack() tk.mainloop() πŸ‘‰ Now I'm going to add a new subroutine to hide the label and call it on a button click. import tkinter as tk window = tk.Tk() window.title("Hello World")  window.geometry("300x200")  # New subroutine def hideLabel():   hello.pack_forget() # Removes the 'hello' label hello = tk.Label(text = "Hello World")  hello.pack()  button = tk.Button(text = "Click me!", command = hideLabel) # Call...