1

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:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_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:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "F:\Flask\01\tut1.py", line 33, in contact
    db.session.add(entry)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\scoping.py", line 163, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1022, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\session.py", line 3286, in __call__
    return self.class_(**local_kw)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 138, in __init__
    bind = options.pop('bind', None) or db.engine
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 943, in engine
    return self.get_engine()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
    return connector.get_engine()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 556, in get_engine
    self._engine = rv = self._sa.create_engine(sa_url, options)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 972, in create_engine
    return sqlalchemy.create_engine(sa_url, **engine_opts)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.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 ?

JS TECH
  • 1,556
  • 2
  • 11
  • 27

2 Answers2

2

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

JS TECH
  • 1,556
  • 2
  • 11
  • 27
1

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

  • Yes, it worked. But how can I see those data on database table? is there any admin URL just like django has(admin/). If possible I want to be worked with the MySQL database. – JS TECH Sep 23 '20 at 11:32
  • did the issue go ? for the mySQL i have never worked with it but i guess you can open mySQL and query the table and retrieve what you want – Abdullah Alessa Sep 23 '20 at 11:46
  • See this link https://dev.mysql.com/doc/mysql-getting-started/en/ – Abdullah Alessa Sep 23 '20 at 11:52
  • I posted my answer. And THANK YOU!! for giving me an idea of sqlite3. I was unknown about that because I am new at Flask. – JS TECH Sep 23 '20 at 12:00