Connect to and query Azure DB from Python flask sqlachemy app

Viewed 697

I'm new to Python and Flask. I want to connect to and query/write to an Azure DB from within a Flask page hosted on a Azure Web App Service. I am able to:

  1. Connect to the Azure DB with SQLAlchemy from Visual Studio Code & read and write data
  2. Publish a simple Flask app with Visual Studio Code to the App Service and view it at the Azure URL

However, I am having trouble getting 1 to work within 2 in a flask UI on the web. I tried putting 1 and 2 together with the following code, but I must be missing something. Do I need to use create_engine instead to make the connection?

# Libraries
import pyodbc
from sqlalchemy import create_engine
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import urllib
app = Flask(__name__)

# Configure Database URI: 
params = urllib.parse.quote_plus(
    'Driver=%s;' % 'ODBC Driver 17 for SQL Server' +
    'Server=tcp:%s,1433;' % '<servername>.database.windows.net' +
    'Database=%s;' % '<dbname>' +
    'Uid=%s;' % '<username>' +
    'Pwd={%s};' % '<password>' +
    'Encrypt=yes;' +
    'TrustServerCertificate=no;' +
    'Connection Timeout=30;')

# Initialize application with URI for Azure DB
app = Flask(__name__)
app.config['SECRET_KEY'] = '<secretkey'
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Extensions
db = SQLAlchemy(app)

# Route to web page
@app.route("/")
def home():
    return "Hello Azure"
    # Call db query here?
0 Answers
Related