Skip to content

Instantly share code, notes, and snippets.

@timmyreilly
Created October 13, 2017 23:02
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save timmyreilly/f4a351eda5dd45aa9d56411d27573d7c to your computer and use it in GitHub Desktop.
Save timmyreilly/f4a351eda5dd45aa9d56411d27573d7c to your computer and use it in GitHub Desktop.
Using Flask_SQLAlchemy to connect to Azure SQL
#!/usr/bin/env python
import os
import urllib.parse
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# Configure Database URI:
params = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=sqlhost.database.windows.net;DATABASE=pythonSQL;UID=username@sqldb;PWD=password56789")
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecret'
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# extensions
db = SQLAlchemy(app)
@romansorin
Copy link

2 years later this saved me, thank you!

@karlduckett
Copy link

Me too! Thanks for sharing this!

@alexis-stahl
Copy link

Thanks for this!!

@CaduceusInc
Copy link

Very helpful, thanks!

@augustoarraes
Copy link

Did you need to install pyobdc before?

@timmyreilly
Copy link
Author

Did you need to install pyobdc before?

Good question, did you get a pyodbc error?

@augustoarraes
Copy link

augustoarraes commented Mar 22, 2021

Yes, it did. I've install it and more other linux dependencies, and it worked out.

@wolfgangas
Copy link

For me it worked as follows (I am using Azure functions, connection string taken from Azure Portal / SQL database / connection strings / ODBC tab):

# app.py
params = urllib.parse.quote_plus(os.environ["AzureSQLConnectionString"])

application = Flask(__name__)
application.config['SQLALCHEMY_DATABASE_URI'] = f"mssql+pyodbc:///?odbc_connect={params}"

# local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "",
    "AzureSQLConnectionString": "Driver={ODBC Driver 17 for SQL Server};Server=tcp:xxxxxxxx.database.windows.net,1433;Database=xxxxxxxxxxx;Uid=xxxxxxxxxxx;Pwd=xxxxxxxxxxxx;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"
  }
}

@timmyreilly
Copy link
Author

Nice! I'll have to give that a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment