Created
October 13, 2017 23:02
-
-
Save timmyreilly/f4a351eda5dd45aa9d56411d27573d7c to your computer and use it in GitHub Desktop.
Using Flask_SQLAlchemy to connect to Azure SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Very helpful, thanks!
Did you need to install pyobdc before?
Did you need to install pyobdc before?
Good question, did you get a pyodbc error?
Yes, it did. I've install it and more other linux dependencies, and it worked out.
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;"
}
}
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
Thanks for this!!