python - Flask Web App: (psycopg2.OperationalError) server closed the connection unexpectedly -
i have small application on azure runs web app following traits:
- python (flask sqlalchemy)
- postgresql
i'm trying create table python code through sqlalchemy. here's folder structure:
here's __init__.py
file:
from flask import flask flask_sqlalchemy import sqlalchemy postgres = { 'user': 'admin_user@pracap', 'pw': 'password_goes_here', 'db': 'apitest', 'host': 'pracap.postgres.database.azure.com', 'port': '5432', } url = 'postgresql://%(user)s:\%(pw)s@%(host)s:%(port)s/%(db)s' % postgres app = flask(__name__) app.config['sqlalchemy_database_uri'] = url app.config['sqlalchemy_track_modifications'] = false db = sqlalchemy(app) import apitestproject.index
then have index.py file:
from flask import flask flask_restful import api apitestproject import app, db @app.before_first_request def create_tables(): db.create_all() @app.route('/') @app.route('/home') def home(): return "i'm default route"
and here's usermodel file:
from ..apitestproject import db class usermodel(db.model): __tablename__ = 'users' id = db.column(db.string, primary_key=true) name = db.column(db.string(50)) address = db.column(db.string(144)) salary = db.column(db.numeric(12, 2)) position = db.column(db.string(50)) password = db.column(db.string(50))
when run project, following error:
operationalerror: (psycopg2.operationalerror) server closed connection unexpectedly means server terminated abnormally before or while processing request.
i have disabled requiredssl azure testing purposes , allowed connections every ip on firewall shown on msft tutorial.
anyone has had error before?
per experience, think issue caused using psycopg2
connection string postgresql://user:password@hostname:port/dbname
. using psycopg2
, need use connection string in python code below, please refer offical document here.
import psycopg2 # update connection string information obtained portal host = "mypgserver-20170401.postgres.database.azure.com" user = "mylogin@mypgserver-20170401" dbname = "mypgsqldb" password = "<server_admin_password>" sslmode = "require" # construct connection string conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode) conn = psycopg2.connect(conn_string) print "connection established"
and there thread can't figure out db uri postgres azure explained issues connecting postgresql on azure using python.
hope helps.
Comments
Post a Comment