Web development using Python.

Contents

Definition

You can develop for the web using Django, fast-api && flask
Flask is a Python web-framework, it is a third party library used for web development.
Flask focuses on step-by-step web development.
It is light weight micro-web framework based on two libraries werkzeug WSGI toolkit && Jinja2 templates

Setting up Flask

Before installation of flask, make sure you are in your virtual environment.

pip install virualenv
#activating:Linux
env/bin/activate
#windows
cd env\Scripts\activate

When you are in your virtual env run:

pip install flask
# or
pip3 install flask

Introduction

All things set👍! now we create a hello world app.✨

# import Flask class
from flask import Flask
#instantiate flask app obj
app = Flask(__name__)

# decorator function(routing)
@app.route('/')
def index():
    return 'Hello world!'


if __name__ == '__main__':
    app.run(debug=True)

Go ahead and type this in a text editor save as app.py
The condition checks if the code is a flask app .

if __name__ == '__main__':
    app.run()

Running a flask app.

type the following commands in terminal

#first we set the flask_app variable 
# Linux
export FLASK_APP=app.run
#window
set FLASK_APP=app.run
# run it
flask run

Yaaay! 🎉 our hello world is live and running on: http://127.0.0.1:5000

Creating a route

A route is a URL to a location in the browser.
Routes are created with the route() decorator, they handle requests for the flask app.

@app.route('/')
def index():
    return 'Hello world!'

This opens the home page in our app.

Rendering HTML from flask

To render html flask uses Jinja2 templating engine.

from flask import Flask, render_template

@app.route('/about')
def about():
    return render_template('about.html')

Variable rules in Flask.

Variables create a dynamic URL route for a flask app, a variable section is marked with angle brackets <variable_name>.
The function receives the variable as a keyword argument, Optionally you can specify a converter for a variable <converter:variable_name>

@app.route('/age/<int:num>')
def age(num):
    return f'<p>This Blog is {num} old.</p>'

Summary

In this article we have gone through web development with Flask a python web-framework.

  • Installation
  • Hello world application.
  • Dynamic URLS.

In the next article, I'll write on connecting Flask to a database.

Thank you for reading, I'd really love your feedback or guidance.
Be cool, Keep coding!

9