A Guide on Flask and Azure SQL

A Guide on Flask and Azure SQL

Building off the previous blog post in which I query Azure SQL from a Linux machine using Python, we're going to apply the same principals to a Flask application.

If you're unfamiliar with flask, check out my other guide on Building a Flask App in 5 Minutes

For this project, we'll use the same database and table used in the previous example. To recap, we have a database with a table called "data" that has two columns, "name" and "quote".

We're going to build a simple flask app that displays the list of names and their quotes to a web page.

Here is the starting point of my routes.py file, now including the import of my AzureDB class.

from flask import Flask, render_template, request
from AzureDB import AzureDB 

app = Flask(__name__) 
app.config.from_object(__name__) 

@app.route('/') 
def hello(): 
   return render_template("quotes.html")

I'm creating a new template file called quotes.html, which will look like this:

{% extends "layout.html" %} 

{% block content %} 
<p><em>So and so </em> once said this: <em> something </em>
</p> 
{% endblock %}

Let's run it just to make sure things are all tidy on this front. Then we'll add an actual query in here.

Looks good

image.png

Now let's add some queries and some logic.

We'll use the same basic principal we used last lesson and apply it to our route, meaning we'll establish a connection with a Python "with" and get our data. Then we'll pass our data to our renderer, then apply jinja2 logic to parse the data.

First, in routes.py, add the query from our AzureDB.py class.


@app.route('/') 
def hello(): 
   with AzureDB() as a:
     data = a.azureGetData()       
   return render_template("quotes.html", data = data)

*Hold on... what's "data = data" mean?

The first part sets data as it will be delivered to the template page. The value it is being set to is called "data" as well, which is defined on the line directly above it. *

Now open the quotes.html template. The jinja2 template will apply logic that will loop through each item in the data. If there is no data, a simple "Nothing Found" message will display.

{% extends "layout.html" %} 

{% block content %} 
{% for d in data %}

    <p><em>{{ d.name }} </em> once said this: <em> {{ d.quote }} </em>
    </p> 
{% else %}
  <em>Nothing Found :(</em>
{% endfor %}
{% endblock %}

Save all of these files and restart your flask app.

image.png

It's that easy!

View the project on Gitlab

-AJ

#flask#sql-server#azure#python#python-beginner