问题
I have created a form in html with some basic information like Website, Link, Name, Last_name, email and price. I am trying to add new columns into my sql database from the html forms.
##When I do it in this way it works fine:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:password@localhost/db_name'
db=SQLAlchemy(app)
class Feedback(db.Model):
__tablename__='user'
website=db.Column('website',db.String(20))
link=db.Column('link',db.String(200))
name=db.Column('name',db.String(20),primary_key=True)
l_name=db.Column('l_name',db.String(20))
email_=db.Column('email_',db.String(40))
price=db.Column('price',db.Integer)
def __init__(self,a,b,c,d,e,f):
self.website=a
self.link=b
self.name=c
self.l_name=d
self.email_=e
self.price=f
a=''1''
b='Name'
c='n'
d='k'
e='j'
f=10
data=Feedback(a,b,c,d,e,f)
db.session.add(data)
db.session.commit()
#When I try to do the same thing with the values from the HTML form I get an Operational Error
from flask import Flask,render_template,request,redirect
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:password@localhost/db_name'
db=SQLAlchemy(app)
class Feedback(db.Model):
__tablename__='user'
website=db.Column('website',db.String(20))
link=db.Column('link',db.String(200))
name=db.Column('name',db.String(20),primary_key=True)
l_name=db.Column('l_name',db.String(20))
email_=db.Column('email_',db.String(40))
price=db.Column('price',db.Integer)
def __init__(self,a,b,c,d,e,f):
self.website=a
self.link=b
self.name=c
self.l_name=d
self.email_=e
self.price=f
@app.route('/',methods=['GET','POST'])
def index():
if request.method=='POST':
#fetch the data
userDetails=request.form
a=userDetails['website']
b=userDetails['link']
c=userDetails['name']
d=userDetails['last_name']
e=userDetails['email']
f=userDetails['price']
data=Feedback(a,b,c,d,e,f)
db.session.add(data)
db.session.commit()
return ('Done')
return render_template('atlas_tracker.html')
if __name__=='__main__':
app.run()
Here is my Error message:
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 588, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\nitin\anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\nitin\anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\nitin\anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nitin\anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\nitin\anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\nitin\anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\nitin\Repositories\Projects\Flipkart and Amazon Price Tracker\app.py", line 41, in index
db.session.commit()
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 1036, in commit
self.transaction.commit()
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 503, in commit
self._prepare_impl()
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 482, in _prepare_impl
self.session.flush()
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 2479, in flush
self._flush(objects)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 2617, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 153, in reraise
raise value
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 2577, in _flush
flush_context.execute()
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 422, in execute
rec.execute(self)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 589, in execute
uow,
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
insert,
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\orm\persistence.py", line 1084, in _emit_insert_statements
c = cached_connections[connection].execute(statement, multiparams)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 982, in execute
return meth(self, multiparams, params)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1101, in _execute_clauseelement
distilled_params,
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1250, in _execute_context
e, statement, parameters, cursor, context
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1476, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\nitin\anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 588, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: INSERT INTO user (website, link, name, l_name, email_, price) VALUES (?, ?, ?, ?, ?, ?)]
[parameters: ('Amazon', 'www.amazon.com', 'Name ', 'jjjj', 'email@live.com', '1200')]
(Background on this error at: http://sqlalche.me/e/e3q8)
127.0.0.1 - - [26/Jun/2020 23:30:14] "POST / HTTP/1.1" 500 -
回答1:
Try to add this code in your app.py file
@app.before_first_request
def create_tables():
db.create_all()
It will create tables before first request
来源:https://stackoverflow.com/questions/62600740/unable-to-insert-data-into-mysql-using-flasksqlalchemy