john
john

Reputation: 81

Programmingerror - closing a closed connection

Here is code from a tutorial I've been working for python web development in flask:

from flask import Flask, render_template, json, request
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

app = Flask(__name__)

mysql = MySQL(app)

 # MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'PhoneList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)




@app.route("/")
def main():
     return render_template('index.html')
@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')

@app.route('/signUp', methods = ['POST','GET' ])
def signUp():
    try:
        _phonenumber = request.form['phonenumber']
        _name = request.form['name']
        _password = request.form['password']

        if _phonenumber and _name and _password:
            conn = mysql.connect()
            cursor = conn.cursor()
            _hashed_password = generate_password_hash(_password)
            cursor.callproc('sp_createphoneuser',(_phonenumber,_name,_hashed_password))
            data = cursor.fetchall()

            if len(data) is 0:
                conn.commit()
                return json.dumps({'message':"User created successfully !"})
            else:
                return json.dumps({'error':str(data[0])})

    else:
        return json.dumps({'html':'<span>Enter the required fields</span>'}) 
    except Exception as e:
        return json.dumps({'error':str(0)})
    finally:
        cursor.close()
        conn.close()


if __name__ == "__main__":
    app.debug = True    
    app.run(port=5002)

When I run this and go to the localhost site, I get "Webpage is Not Available" and a message on my terminal saying "Programmingerror closing a closed caption"

I can't figure out what I'm messing up here.. I'm new to python web development so I hope I'm not asking a really dumb question here.

Thanks

Upvotes: 0

Views: 2170

Answers (1)

SD Dani
SD Dani

Reputation: 154

I reproduced the error, it looks you are initializing twice the database driver, look:

mysql = MySQL(app)
....config stuff
mysql.init_app(app)

Now look the library code:

class MySQL(object):
def __init__(self, app=None, **connect_args):
    self.connect_args = connect_args
    if app is not None:
        self.app = app
        self.init_app(self.app)
    else:
        self.app = None

def init_app(self, app):
    self.app = app
    ...some more code
    self.app.teardown_request(self.teardown_request)
    self.app.before_request(self.before_request)

Now when when you call again the init_app you are closing the connection you already opened when you call the constructor of the MySQL whit the app object parameter.

Change one of both lines to:

 mysql = MySQL()
 #config stuff, and then init the app
 mysql.init_app(app)

or

#config stuff
mysql = MySQL(app)

This must fix the problem

Upvotes: 1

Related Questions