I tried adding new data to the sql alchemy database by creating a new object of Movie class. I used a Movie api to fetch the information for the data. The tried printing the response from the api and it's working fine. But i get error while db.sessoin.commit()
Here's the code :
from flask import Flask, render_template, redirect, url_for, request
from flask_bootstrap import Bootstrap5
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, EmailField, SubmitField, DecimalField
from wtforms.validators import DataRequired
import requests
class Movie(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(400), nullable=False)
year = db.Column(db.String(400), nullable=False)
description = db.Column(db.String(1000), nullable=False)
img_url = db.Column(db.String(800), nullable=False)
rating = db.Column(db.String(400), nullable=True)
ranking = db.Column(db.Integer, nullable=True)
review = db.Column(db.String(400), nullable=True)
@app.route("/select")
def find():
movie_id = request.args.get('id')
movie_url = f"https://api.themoviedb.org/3/movie/{movie_id}"
params = {
"api_key" : api_key,
"language": "en-US"
}
response = requests.get(url=movie_url, params = params)
response = response.json()
new_data = Movie(
title = response['title'],
description = response['overview'],
year = response['release_date'],
img_url = f"https://image.tmdb.org/t/p/w500{response['poster_path']}"
)
db.session.add(new_data)
db.session.commit()
return render_template("base.html")
Here's the error i am getting
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 121-365-366
127.0.0.1 - - [14/Aug/2023 16:25:02] "GET /select?id=1142216 HTTP/1.1" 500 -
Traceback (most recent call last):
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 1963, in _exec_single_context
self.dialect.do_execute(
File "S:\Python\lib\site-packages\sqlalchemy\engine\default.py", line 920, in do_execute
cursor.execute(statement, parameters)
sqlite3.IntegrityError: NOT NULL constraint failed: movie.rating
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "S:\Python\lib\site-packages\flask\app.py", line 2213, in __call__
return self.wsgi_app(environ, start_response)
File "S:\Python\lib\site-packages\flask\app.py", line 2193, in wsgi_app
response = self.handle_exception(e)
File "S:\Python\lib\site-packages\flask\app.py", line 2190, in wsgi_app
response = self.full_dispatch_request()
File "S:\Python\lib\site-packages\flask\app.py", line 1486, in full_dispatch_request
rv = self.handle_user_exception(e)
File "S:\Python\lib\site-packages\flask\app.py", line 1484, in full_dispatch_request
rv = self.dispatch_request()
File "S:\Python\lib\site-packages\flask\app.py", line 1469, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "d:\Data Transfer\Coding\Python\3 Udemy Course\Udemy Codes\udemy_learning_codes\64_1\main.py", line 142, in find
db.session.commit()
File "S:\Python\lib\site-packages\sqlalchemy\orm\scoping.py", line 553, in commit
return self._proxied.commit()
File "S:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 1905, in commit
trans.commit(_to_root=True)
File "<string>", line 2, in commit
File "S:\Python\lib\site-packages\sqlalchemy\orm\state_changes.py", line 137, in _go
ret_value = fn(self, *arg, **kw)
File "S:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 1220, in commit
self._prepare_impl()
File "<string>", line 2, in _prepare_impl
File "S:\Python\lib\site-packages\sqlalchemy\orm\state_changes.py", line 137, in _go
ret_value = fn(self, *arg, **kw)
File "S:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 1195, in _prepare_impl
self.session.flush()
File "S:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 4153, in flush
self._flush(objects)
File "S:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 4289, in _flush
with util.safe_reraise():
File "S:\Python\lib\site-packages\sqlalchemy\util\langhelpers.py", line 147, in __exit__
raise exc_value.with_traceback(exc_tb)
File "S:\Python\lib\site-packages\sqlalchemy\orm\session.py", line 4250, in _flush
flush_context.execute()
File "S:\Python\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 467, in execute
rec.execute(self)
File "S:\Python\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 644, in execute
util.preloaded.orm_persistence.save_obj(
File "S:\Python\lib\site-packages\sqlalchemy\orm\persistence.py", line 93, in save_obj
_emit_insert_statements(
File "S:\Python\lib\site-packages\sqlalchemy\orm\persistence.py", line 1223, in _emit_insert_statements
result = connection.execute(
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 1413, in execute
return meth(
File "S:\Python\lib\site-packages\sqlalchemy\sql\elements.py", line 483, in _execute_on_connection
return connection._execute_clauseelement(
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 1637, in _execute_clauseelement
ret = self._execute_context(
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 1841, in _execute_context
return self._exec_single_context(
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 1982, in _exec_single_context
self._handle_dbapi_exception(
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 2339, in _handle_dbapi_exception
raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
File "S:\Python\lib\site-packages\sqlalchemy\engine\base.py", line 1963, in _exec_single_context
self.dialect.do_execute(
File "S:\Python\lib\site-packages\sqlalchemy\engine\default.py", line 920, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: movie.rating
[SQL: INSERT INTO movie (title, year, description, img_url, rating, ranking, review) VALUES (?, ?, ?, ?, ?, ?, ?)]
[parameters: ('The Lady of Silence: The Mataviejitas Murders', '2023-07-27', 'Between 1998 and 2005, a wave of murders targeting elderly women hit Mexico City, triggering the hunt for — and capture — of a most unlikely suspect.', 'https://image.tmdb.org/t/p/w500/qmW8mPhcdOP3v36Gz8WEeDdewFN.jpg', None, None, None)]
(Background on this error at: https://sqlalche.me/e/20/gkpj)
127.0.0.1 - - [14/Aug/2023 16:25:02] "GET /select?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 304 -
127.0.0.1 - - [14/Aug/2023 16:25:02] "GET /select?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 304 -
127.0.0.1 - - [14/Aug/2023 16:25:02] "GET /select?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
127.0.0.1 - - [14/Aug/2023 16:25:02] "GET /select?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
I want to add data to the sql alchemy database.
It seems like the nullable constraint wasn't added to the table when it was made for some reason. You could check the schema easily with db browser https://sqlitebrowser.org/ if you're using sqlite. Which you can also use to update the schema if you need and add/remove the NOT NULL constraint. You can also do the same thing in pgAdmin4 if you're using PostgreSQL.
You could also try migrate your database with flask-migrate https://pypi.org/project/Flask-Migrate/ and follow the simple example and see if it updates the schema correctly