1

I am building a flask project for internal use at my company. I start by using flask and postgre and used sqlalchemy and set up that connection using the model formats like below:

app = Flask(__name__)

app.config.from_object('config')

db = SQLAlchemy(app)

and that worked well. Now for security reasons we are switching to using Microsoft SQL Server with window authentication on an IIS server but i am having a lot of trouble connecting. I changed the database URI to

SQLALCHEMY_DATABASE_URI = "mssql+pyodbc://server/database"

I've checked the SQL Sever configuration and I am pretty sure that is correct. However I get the error

psycopg2.OperationalError: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

I have researched this issue and have used the pool_pre_ping solution but I get the same error (shown below)

SQLALCHEMY_ENGINE_OPTIONS = {"pool_pre_ping": True} 

I have seen a lot of answers around this stuff that use the sqlalchemy.engine stuff but if possible I was hoping to use all of the db.models I have already written out but if that's not possible I can rewrite some stuff. Any help appreciated.

1 Answer 1

1

Windows Authentication will become a problem when you deploy to production. I recommend creating a SQL user to connect to your database.

Try this connection string:

mssql+pyodbc://<UID>:<PWD>@<SERVER>/<DATABASE>?driver=ODBC+Driver+17+for+SQL+Server;Trusted_Connection=no

Also make sure you've installed pyodbc msft docs

pip install pyodbc 
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for responding. i tried the above connection string and am now getting a " could not connect to server: Connection refused (0x0000274D/10061)" any thoughts? Also, could you explain what you mean about creating a sql user to connect to db.
WIndows Auth users a user on your domain e.g. 'Domain\User', a SQL user is created on the SQL Server see.
If you want to use Windows Auth, remove the UID and PWD from the connection string and change trusted_connection=no to Trusted_connection=yes.
I am unfortunately getting the same error when trying to use windows auth
Ignore Flask & SQLAlchemy for now. Can you connect to you database with pyodbc?. Follow the example from Microsoft. Once you've figured out the correct connection string, use that in your app.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.