Codecademy Logo

Introduction to Flask

Related learning

  • Build your first Flask app, a web framework that allows you to build fully-featured web applications using Python.
    • Intermediate.
      2 hours

Python Flask Framework

Flask is a popular Python framework for developing web applications. It comes with minimal built-in functionalities and requirements, making it simple to get started and flexible to use. The developer has the liberty to customize most aspects of the app, including database integration, accounts and authentication, and more.

Creating Flask App Object

The Python flask module contains all the classes and functions needed for building a Flask app. The Flask class can be imported to create the main application object. It takes the name of the app as an argument.

# Import Flask class
from flask import Flask
# Create Flask object
app = Flask(__name__)

Running Flask App

A Flask app can be run by exporting the FLASK_APP environment variable and running flask run in the terminal.

$ export FLASK_APP=app.py
$ flask run

Creating a Route

Routes in a Flask app can be created by defining a view function and associating a URL with it using the route() decorator. Routes specify how the Flask app handles requests it receives, such as what to display on the webpage at a certain URL.

@app.route('/')
def hello_world():
return 'Hello, World!'
# Output: The text `Hello, World!` is displayed at the URL path '/'

Returning HTML From Route

In a Flask app, HTML can be returned from a view function to be rendered on a webpage. The HTML can be returned as a string.

@app.route('/')
def hello_world():
return '<h1>Hello, World!</h1>'
# Output: The text `Hello, World!` is displayed as a level 1 heading at the URL path '/'

Variable Rules

Variable rules allow a Flask app to respond to dynamic URLs. Variable sections of a URL can be indicated by angular brackets and an optional converter: <converter:variable_name>. These variable parts will then be passed to the view function as arguments.

# Responds to `/page/1`, `/page/20`, etc.
@app.route('/page/<int:pg_num>')
def content(pg_num):
return f'<h1>Displaying results for page {pg_num}</h1>'

HTML Front-End

The front-end refers to the part of web apps visible to users, handled in their browsers. This includes elements like HTML for structure, CSS for styling, and JavaScript for functionality. Meanwhile, the back-end handles the server-side processes, managing data and responding to requests.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Front-End Development</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
}
</style>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a simple HTML page demonstrating front-end basics.</p>
<button onclick="alert('Hello, Front-End!')">Click me!</button>
</body>
</html>

Web Server Basics

A web server listens for client requests over a network and returns responses. Typically, these servers use the HTTP protocol to send requested resources like HTML pages, images, or files. Understanding these basic functions of a web server helps in designing efficient network communication.

```python
# Simple HTTP server in Python
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()
```

Server-Side Logic

The back-end of web applications handles server-side logic, processing requests and managing data interactions. This ensures dynamic responses are generated for clients effectively. Node.js is often used for this purpose, working seamlessly with databases like MongoDB or MySQL.

const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.write('You have reached the server-side logic page');
res.end();
}
});
server.listen(3000);
console.log('Listening on port 3000...');

Database Management

Databases store and manage data for web apps efficiently. Relational databases organize data into tables, facilitating easy access and manipulation using queries. Non-relational databases store data differently, like key-value pairs or documents, offering flexibility for unstructured data.

--Example of a relational database query:
SELECT * FROM users WHERE status = 'active';
--Example of non-relational database entry using JSON-like format:
{
"key": "user123",
"value": {
"name": "John Doe",
"status": "active"
}
}

Understanding Web APIs

A web API enables communication between a client interface and a server by following a specific set of rules. Through a process called the HTTP request-response cycle, clients can retrieve, update, or manipulate data on the server side. This interaction is essential for dynamic web applications that rely on external data.

GET /api/data HTTP/1.1
Host: example.com
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
{
"data": [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
}

Python Authentication

Authentication ensures only legitimate users can access specific features in an application by verifying their identity, often using credentials, like usernames and passwords.

from getpass import getpass
# Placeholder user credentials for demonstration
USERNAME = "user123"
PASSWORD = "securepass"
username_input = input("Enter your username: ")
password_input = getpass("Enter your password: ")
if username_input == USERNAME and password_input == PASSWORD:
print("Access granted.")
else:
print("Access denied.")

Authorization Concepts

Authorization is critical for controlling access. Once a user proves their identity, authorization determines what they can do. It’s like having different keys for different doors based on your role!

// Example of authorization check
const user = {
role: 'admin',
permissions: ['view-dashboard', 'edit-user'],
};
function authorize(action) {
if (user.permissions.includes(action)) {
return `Access granted for ${action}`;
} else {
return `Access denied for ${action}`;
}
}
console.log(authorize('edit-user')); // Outputs: Access granted for edit-user
console.log(authorize('delete-user')); // Outputs: Access denied for delete-user

Tech Stack Overview

A technology stack is an essential part of web development. It combines programming languages, frameworks, databases, and tools to create a cohesive environment for building web applications. Understanding how each component interacts can enhance productivity and efficiency.

Learn more on Codecademy

  • Build your first Flask app, a web framework that allows you to build fully-featured web applications using Python.
    • Intermediate.
      2 hours