skip to Main Content

I am just new in Flask, so I am trying to send data to the database using different tutorial source. I build simple blog type websites and my database server is http://localhost/phpmyadmin/. After I clicked on the submit button on contact.html. I got this error. So how can I fixed this error.

Traceback (most recent call last):
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemyutil_collections.py", line 1020, in __call__
    return self.registry[key]
KeyError: 6528

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_compat.py", line 39, in reraise
    raise value
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_compat.py", line 39, in reraise
    raise value
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflaskapp.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "F:Flask1tut1.py", line 33, in contact
    db.session.add(entry)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemyormscoping.py", line 163, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemyutil_collections.py", line 1022, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemyormsession.py", line 3286, in __call__
    return self.class_(**local_kw)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_sqlalchemy__init__.py", line 138, in __init__
    bind = options.pop('bind', None) or db.engine
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_sqlalchemy__init__.py", line 943, in engine
    return self.get_engine()
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_sqlalchemy__init__.py", line 962, in get_engine
    return connector.get_engine()
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_sqlalchemy__init__.py", line 556, in get_engine
    self._engine = rv = self._sa.create_engine(sa_url, options)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagesflask_sqlalchemy__init__.py", line 972, in create_engine
    return sqlalchemy.create_engine(sa_url, **engine_opts)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemyengine__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemyenginestrategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:UsersNew TechAppDataLocalProgramsPythonPython38-32Libsite-packagessqlalchemydialectsmysqlmysqldb.py", line 118, in dbapi
    return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'

My code is here

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime  import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/blog'
db = SQLAlchemy(app)

class Contacts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(255), nullable=False)
    phone_number = db.Column(db.String(50), nullable=False)
    message = db.Column(db.String(120), nullable=False)
    date_created = db.Column(db.String(50), nullable=True )


@app.route('/contact/', methods=['GET','POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        phone_number = request.form.get('phone_number')
        message = request.form.get('message')
        entry = Contacts(name=name, email=email, phone_number=phone_number, message=message, date_created=datetime.now())
        db.session.add(entry)
        db.session.commit()
    return render_template('contact.html')

app.run(debug=True)

Does anyone knows, how I get this error ?

2

Answers


  1. Chosen as BEST ANSWER

    Running command pip install pymysql and pip install mysqldbmodel help me to kicked this freaking(**) error.

    Edit:

    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/blog'
    

    I find this solution at ImportError: No module named MySQLdb


  2. datetime.now: Does not return a String you need to convert it to String or change the type in the database to date like this

        date_created = db.Column(db.DateTime, nullable=True )
    

    I have used this and it worked very will with me

    from flask import Flask, render_template, request,redirect
    from flask_sqlalchemy import SQLAlchemy
    import sqlite3
    from datetime import *
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database1.db'
    db = SQLAlchemy(app)
    
    class Contacts(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80), nullable=False)
        email = db.Column(db.String(255), nullable=False)
        phone_number = db.Column(db.String(50), nullable=False)
        message = db.Column(db.String(120), nullable=False)
        date_created = db.Column(db.DateTime, nullable=True )
    
    db.create_all()
    
    @app.route('/contact', methods=['GET','POST'])
    def contact():
        if request.method == 'POST':
            name = request.form.get('name')
            email = request.form.get('email')
            phone_number = request.form.get('phone_number')
            message = request.form.get('message')
    
            entry = Contacts(name="name", email="email", phone_number="phone_number", message="message", date_created=datetime.now())
    
        try:
            db.session.add(entry)
            db.session.commit()
            db.session.close()
            return render_template('h.html')
    
    
        except:
            return "Error"
    
    app.run(debug=True)
    

    You need to change the things i have changed like the render_template

    if it did not work please provide you github

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search