Computer Science
Gilmour AcademyLancerTech
  • Our Curriculum and Department
  • Intro to Programming
    • 1: Parts of a Computer
    • 2: Parts of Python
    • 3: DRY Turtle
    • 4: Turtle Design App
    • Wordle with Turtles
    • 5: Interactive Turtles
    • OLD 5: Replit, GitHub, and repositories (Oh my!)
    • 6: Raspberry Pi / GoPiGo
    • 7: Kivy
  • Intro to Web Design
    • 1: Internet?
    • 2: Websites?
    • 3: Bootstrap Template
    • 4: Graphics and Branding
    • 5: Collaboration
    • 6: Advanced Editing
    • Publish Static HTML
  • AP Computer Science
    • 1: Logic & Instances
    • 2: How Java Works
    • 3: Data Types & Flow
    • 4: Strings
    • 5: Objects & References
    • 6: Inheritance & Algorithms
    • 7: Data Structures
    • 8: Sorting
    • 9: Review
    • Data Science
  • Web App Dev
    • 1: Core Concepts
    • 2: MVT Pattern
    • 3: Hello Flask
    • 4: Install Flaskinni
    • 5: Tour Flaskinni
    • 6: Visualize Your App
    • 7: Theme & Blueprint
    • 8: Standup Your DB
    • 9: Advanced Topics
    • 10: Deployment
  • 2D Game Design
    • Class Overview
    • Gamemaker Studio 2 and Github Setup
    • Game 1: Bouncing Ball
    • Turning in your games
    • Game 2: Maze
    • Game 3: Ping Pong
    • Game 4: Breakout
    • Game 5: Tank Battle
    • Game 6 Highlights
    • DO NOT DO:
    • Game 7: Final Project
    • Publish to Opera
    • FAQ
  • 3D Game Design
    • 1: Class Overview
    • 2: Installation
    • 3: Exploring the Unity UI
    • Game 1: Rolling Ball
    • Game 2: Tanks
    • Game 3: Third Person Platformer
    • Game 4: Final project
    • FAQs
    • OLD: Distance Learning Setup
    • OLD: GIT
  • 3D Modeling & Fabrication
    • Installation
    • Fusion 360 Interface and Sketch Modeling
    • Primitive Modeling
    • Patterns
    • Appearances and Rendering
    • Building Community Gallery Page 2023
    • Parametric Modeling
    • 3D Printing Concerns
    • Assemblies and Mechanical Design
    • Laser Cutting
    • Sculpt Tools
    • Milling Concerns
  • Robotics 7
    • Software Installation
    • Python basics (trinket.io)
    • Python Turtle
    • Programming for the Ev3
    • Setting up for clarity
  • Robotics 8
    • Replit
    • Python review
    • Kivy Basics
    • Calculator
  • Competitive Robotics
    • Hardware Team
      • CAD Examples
      • Elevators
    • Software Team
      • Command Pattern
      • Example Command
      • Subsystem
      • Running Your Code
      • Under the Hood
      • RoadRunner
      • Vision Processing
  • Archives
    • Adiletta Archives
      • Old Web
        • Ex: WordPress CMS
      • ItP
        • OLD: Parts of Python (old -- Mr. A)
        • OLD: 5: Raspberry Pi
        • OLD: 6: Deploying Code
        • OLD 7: Nav Algorithm
    • Vanek Archives
      • OLD Robotics 8
        • OLD: End of Class Project
      • OLD Competitive Robotics
        • Untitled
        • Webots Videos
      • OLD Robotics 7
        • Trinket Introduction
        • Lists: x/y position
        • Functions: Math program
        • Lists: Grocery List
        • Study Guide Program
        • Tic Tac Toe Game
        • Dice Roller Program
        • Visualization
        • Dice Roller + Visualization
        • OpenSCAD: Installation
        • OpenSCAD: Command Sheet and Intro
        • OpenSCAD: Difference
        • OpenSCAD: Variables
        • OpenSCAD: Union
        • OpenSCAD: For Loops
        • OpenSCAD: Final Project
      • OLD Art I - Blender Sculpting
        • Class Overview
        • Installation
        • Lesson 1 - Tools
        • Lesson 2 - Detail
        • Lesson 3 - Base Mesh: Metaballs
        • Lesson 4: Converting metaballs and adding detail
        • Lesson 5: Masking, Hiding, and Working with Multiple Objects
        • Lesson 6: Joining Objects & Basing
        • Lesson 7: Sculpture Painting
        • Student Gallery: Animal Sculpts
        • Lesson 8: 3D Compositon
        • Lesson 9: The Project - Putting it all together
        • Lesson 10: Developing the image further
        • Lesson 11: Layout the base metaball mesh.
        • Lesson 12: Final Detail
        • Lesson 13: Basing and Painting
        • Final Project Gallery
      • OLD Fab
        • OLD Building Community Project Gallery
        • Copy of Building Community Project Gallery
        • old Building Community Project Gallery
      • OLD: Turtle Design App
      • OLD Arduino Robotics 8
        • Arduino Basic Commands Cheat Sheet
        • Logging into Tinkercad
        • Arduino, Circuits, LEDs and Resistors
        • Functions and Variables
        • Serial Monitor
        • Buttons and Interrupts
        • Traffic Light Project
        • Potentiometers + Servos
        • Piezo Buzzer and Tone();
        • Sequencer Project
        • Arrays and for loops
        • Extra Loop Practice
        • Refining the Sequencer
        • Servos
        • Ultrasonic Sensors
        • Final Project
Powered by GitBook
On this page
  • Learning Targets
  • Organization
  • App Factory
  • Blueprints and MVT
  • Template
  • File structure
  • Base's blocks
  • Sass and JS
  • Views
  • url_for
  • Flash Notifications
  • Sessions
  • Models
  • Users are special
  • Example Queries
  • Example Relationships
  • Extensions
  • Flask-Security
  • Flask-Mail
  • Flask-Migrations
  • Flask-Assets
  • Flask-RESTful

Was this helpful?

Export as PDF
  1. Web App Dev

5: Tour Flaskinni

Previous4: Install FlaskinniNext6: Visualize Your App

Last updated 4 years ago

Was this helpful?

Learning Targets

  • I can describe the MVT components of Flaskinni.

  • I can describe the thread's steps as my app starts up.

Organization

Remember, you can help add comments and docstrings to Flaskinni and submit pull requests. Even beginners can help contribute to open source projects in surprisingly substantial ways.

App Factory

The reason why the Application Factory is so important has to do with something called Flask's Application Context. Our app's "context" is what takes the assortment of Python files and modules which make up our app and brings them together so that they see and work with one another.

When your app is serving hundreds or thousands of people at a time, your server will run many instances of your app. You may also run your app in different modes, like a text-only shell. An application factory addresses this need by spitting out instances of app

Blueprints and MVT

Flaskinni comes with a main and an api blueprint. That'll affect your use of url_for. So if you wanted to make a link to the homepage, it'd be <a href="{{ url_for('main.index') }}">home</a>

Template

Now that Flaskinni is running in your environment, local or cloud-based, let's take a tour.

File structure

This is the whole parent-child thing. The parent is the skeleton of your page. We named it base.html and it has <link>s to our Google Fonts, CSS files, and sets up nav bars and any other element that’s site-wide. It’s great! Pretty much sets up the whole theme of our site.

To put our pages inside this metaphorical picture frame, we use the command, {% extends "base.html" %} at the top of every other HTML we put in our templates folder.

The base template extends across all pages, so the website can share HTML code.

Base's blocks

We’re going to make a new template that inherits from our base.html so you can experiment with this handy tool. Create a new file in your templates folder called about.html. This page will need hardly any information at all because all the setup is done in the parent. All we need to do is pass some HTML into any block.

{% extends "base.html" %}   


{% block content %}
    {# this is a comment #}
    <div class="row justify-content-md-center">
        <div class="col-md-6">
            <h1>Hi</h1>
        </div>
    </div>

{% endblock %}

Sass and JS

Don't want to learn? There is a lazy way out and that's to edit your CSS directly. No judgments.

  1. Add them to your collection and get the <link> we’ll use to embed a connection to Google Fonts.

  2. Replace the other <link> to fonts.google.com that was in your base.html file

  3. Add your CSS code to custom.css, something like:

body {
    font-family: 'Roboto Mono', monospace;
}

h1, h2, h3, h4, h5, h6 {
    font-family: 'Rammetto One', cursive;
}
  1. Launch your server

    1. (make sure you’ve got venv activated) source venv/bin/activate or on Windows: source venv/Scripts/Activate

    2. (use our flask-script to run the server) flask run

  2. Check out your font changes!

Views

If you want to see the new template file in action, we’ve got to build a route to that page. As of this writing, there are only two locations for routes in Flaskinni, the master __init__.py file and the views.py file inside the blog module folder. Since our homepage route is in the first file, we’ll put our about route there, too.

# Created a new route used for rendering the about page template 
# Custom app routes for the end of the website url
@app.route('/about')
@app.route('/about/')
@app.route('/about.html')
# Define app route
def about():
        """Render the template"""
        return render_template('about.html')

We later passed a variable to the template. We dropped <h1> {{ some_variable }} </h1> in our about.html file. Nothing shows up until we change the render_template call to something like this:

def about():
        """Render the template"""
        return render_template('about.html', some_variable="Hello!")

Congratulations! You just passed your first variable to a template.

url_for

Flash Notifications

We have cool, color-changing notifications in Flaskinni that rely on Bootstrap classes. So if you want to send a good alert message that something worked, you'd say: flash("Your message has been sent!", "success")

But if something failed, you'd write:

flash("Your message was destroyed by mistake. Whoops!", "danger")

What other Flash notifications are there? How are the flash notifications being built? Let's look at where they come up in the base.html file, trace back the macro that builds the flash messages and then see what other options come with Flaskinni.

Sessions

Cookies!

Models

Users are special

Example Queries

Let's talk about how this blog post is queried from our database:

@app.route('/article/<slug>')
def read(slug):
    post = Post.query.filter_by(slug=slug).first_or_404()
    return render_template('main/article.html', post=post)

Example Relationships

Check out line #20.

class User(db.Model, UserMixin):

    # Our User has six fields: ID, email, password, active, confirmed_at and roles. The roles field represents a
    # many-to-many relationship using the roles_users table. Each user may have no role, one role, or multiple roles.
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(155))
    last_name = db.Column(db.String(155))
    phone = db.Column(db.String(20)) # let's guess it should be no more than 20
    address = db.Column(db.Text)
    about = db.Column(db.Text)
    image = db.Column(db.String(125))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    # TOGGLES
    active = db.Column(db.Boolean(), default=True)
    public_profile = db.Column(db.Boolean(), default=True)
    # DATES
    confirmed_at = db.Column(db.DateTime())
    last_seen = db.Column(db.DateTime(), default=None)
    posts = db.relationship('Post', backref='user', lazy='dynamic')

Extensions

Flask-Security

Flask-Mail

Flask-Migrations

Flask-Assets

Flask-RESTful

We've got a handy little method that instantiates our app, loads the settings, and straps on all its expansion packs. Let's start our tour of the code where Flask is spawned. From "":

The T part of our MVT all starts with base.html.

The purpose of the base template is to give all the pages in your app common assets. This such as fonts, CSS files, nav bar. Every page must link to the base file. It is kept in the /templates folder, as base.html. The base template is like a picture frame, loading common elements like the nav bar, footer, and your little .

I can't remember where this picture in my notes came from but it's not my creation.

Sass makes CSS easier, even if you have to spend a few minutes here and there refreshing yourself on how to use the Sass tricks and how to compile your Sass down to CSS. I personally use a to manage this automatically.

Pick out a header and a body font at

Demystifying Flask’s Application Factory
See how much of the documentation you can read before your brain wimps out
favicon
VSCode extension
fonts.google.com
LogoModular Applications with Blueprints — Flask Documentation (1.0.x)
Flaskinni comes with one blueprint. You'll probably want to add more soon
LogoThe Flask Mega-Tutorial Part II: Templatesmiguelgrinberg
If you give this guide up and follow Mr. Grinberg's exclusively I won't judge.
LogoSass: Sass Basics
LogoBuilding a secure admin interface with Flask-Admin and Flask-SecurityMedium
LogoFlask-Security — Flask-Security 3.0.0 documentation
All the pieces of our app get bolted on in a structure called an "application factory"
Flash notification system is a great illustration of the power of templating
There we include the _message.html partial
Those are the options you've got. You can totally add your own.