Flask/Python: Sqlalchemy.exc.OperationalError - python

I am new in Flask and I am trying to create a blog. I want to create a page from where I would like to insert the posts. In theory, the page should redirect to the index but every time I try to insert content in the page "add" I get an error. Here is my code:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/admin/Desktop/Blog_Project/blog2.db'
db = SQLAlchemy(app)
class Blogpost(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(50))
subtitle = db.Column(db.String(50))
author = db.Column(db.String(20))
date_posted = db.Column(db.DateTime)
content = db.Column(db.Text)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/about')
def about():
return render_template('about.html')
#app.route('/post')
def post():
return render_template('post.html')
#app.route('/contact')
def contact():
return render_template('contact.html')
#app.route('/prova')
def prova():
return render_template('prova.html')
#app.route('/add')
def add():
return render_template('add.html')
#app.route('/addpost', methods=['POST'])
def addpost():
title = request.form['title']
subtitle = request.form['subtitle']
author = request.form["author"]
content = request.form['content']
post = Blogpost(title=title, subtitle=subtitle, author=author, content=content, date_posted = datetime.now())
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug = True)
And this is the error I get:
sqlalchemy.exc.OperationalError
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: blogpost
[SQL: INSERT INTO blogpost (title, subtitle, author, date_posted, content) VALUES (?, ?, ?, ?, ?)]
[parameters: ('ds', 'ds', 'sd', '2020-09-08 12:55:25.333277', 'ds')]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
As far as I understand, the problem is that Flask cannot create the table blogpost in the database blog2 and fill it with the values that I inserted in the code. I have read some documentation in internet and in Stackoverflow and apparently some people fixed the same problem using the method db.create_all() but I am not sure where I should insert it or if I should reorganize the code in another way. Have you got any suggestion? Thank you very much in advance!

Related

Why i am getting UnboundLocalError in Flask?

this is my app.py code but i am receiving unbound local error after adding another path for delete and creating the function delete.
from crypt import methods
from email.policy import default
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Todo(db.Model):
sno = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
desc = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self) -> str:
return f"{self.sno} - {self.title}"
#app.route('/', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
title = request.form["title"]
desc = request.form["desc"]
todo = Todo(title=title, desc=desc)
db.session.add(todo)
db.session.commit()
mytodo = Todo.query.all()
return render_template('index.html', mytodo=mytodo)
#app.route('/delete/<int:sno>')
def delete(sno):
todo = Todo.query.filter_by(sno==sno).first()
db.session.delete(todo)
db.session.commit()
return redirect('/')
if __name__ == "__main__":
app.run(debug=True, port=8000)
Below i've added the screenshot of the errors i am getting even when i just visit the root url.
Problem
If the server receive a GET /, then you won't define te title variable, but would try to use it at Todo(title=title, desc=desc) so an error
Fix
All the creation code should be in the if POST branch
#app.route('/', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
title = request.form["title"]
desc = request.form["desc"]
todo = Todo(title=title, desc=desc)
db.session.add(todo)
db.session.commit()
mytodo = Todo.query.all()
return render_template('index.html', mytodo=mytodo)

How can i return a database that gets a JSON POST Request in Flask?

I know that my code is not good, i took parts of codes and try to work them together, but i get this error:
temp = data['temp']
TypeError: 'NoneType' object is not subscriptable
I want to send a POST Request and that to go in my database and then to return that database to show on the web. pls help
from flask import Flask, request, jsonify, json
from flask_sqlalchemy import SQLAlchemy
def theform():
return '''<form method="POST" action="/process">
<input type="text" name="temp"
</form>'''
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f'sqlite:///site.db'
db=SQLAlchemy(app)
db.init_app(app)
class JsonModel(object):
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class User(db.Model, JsonModel):
User_ID = db.Column(db.Integer, primary_key = True)
firstname = db.Column(db.String(20))
def __repr__(self):
return f"User({'self.firstname'})"
#app.route('/', methods = ['GET','POST'])
def index():
data=request.get_json()
temp = data['temp']
firstname = temp
return jsonify([u.as_dict() for u in User.query.all()])
if __name__ == '__main__':
app.run()

Python flask SqlAlchemy: Data is getting stored in different table other than specified

I am facing issue while inserting Data in the different Tables using Python flask and SQLAlchemy
Issue :
When I insert the Data in "device_data" table it gets inserted in the other Table
"registration_data"
The Page also gets redirected the Registration Forms
The Code in my main.py file is as follows
{
import sqlite3 as sql
from flask import Flask, render_template
from flask import redirect, url_for, session, request, g
from flask_sqlalchemy import SQLAlchemy
import wtforms
from flask_wtf import Form
# from flask_user import roles_required
from wtforms import validators
app = Flask(__name__)
app.config['SECRET_KEY'] = 'a8b84f7b63d64fb2a6e0161caabc4673'
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///samlple.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =True
db = SQLAlchemy(app)
class RegistrationData(db.Model):
id= db.Column(db.Integer, primary_key=True)
Patient_Name = db.Column(db.String(80))
Patient_Age = db.Column(db.Integer)
email = db.Column(db.String(80))
Doctor_Name= db.Column(db.String(80))
PhoneNumber=db.Column(db.String(80))
Equipment=db.Column(db.String(80))
Deposit= db.Column(db.Integer)
Disease= db.Column(db.String(80))
Issue_Date= db.Column(db.String(80))
Return_Date= db.Column(db.String(80))
Address = db.Column (db.String (80))
def __init__(self,
Patient_Name,
Patient_Age,
email,
Doctor_Name,
PhoneNumber,
Equipment,
Deposit,
Disease,
Issue_Date,
Return_Date,
Address):
self.Patient_Name = Patient_Name
self.Patient_Age = Patient_Age
self.email = email
self.Doctor_Name = Doctor_Name
self.PhoneNumber = PhoneNumber
self.Equipment = Equipment
self.Deposit = Deposit
self.Disease = Disease
self.Issue_Date = Issue_Date
self.Return_Date = Return_Date
self.Address = Address
class DeviceData (db.Model):
id = db.Column (db.Integer, primary_key=True)
DeviceName = db.Column (db.String (80))
quantity = db.Column (db.Integer)
Price = db.Column (db.String (80))
Deposit = db.Column (db.String (80))
Location = db.Column (db.String (80))
description = db.Column (db.String (80))
#app.route('/')
def home():
return render_template("index.html")
#app.route('/template/device')
def devices():
return render_template("device.html")
#app.route('/templates/home')
def about():
name= "Rugna Sahayata Kendra"
return render_template("home.html", name=name)
#app.route('/templates/Registration')
def Registration():
name= "Rugna Sahayata Kendra"
return render_template("RegistrationForm.html", name=name)
#app.route('/templates/Add_Device')
def AddDevice():
name= "Rugna Sahayata Kendra"
return render_template("Add_Device.html", name=name)
#app.route ('/templates/table')
def AllocationList():
con = sql.connect ("samlple.db")
con.row_factory = sql.Row
cur = con.cursor ()
cur.execute ("select * from registration_data")
rows = cur.fetchall ();
return render_template ("table.html", rows=rows)
#app.route ('/templates/EquipmentList')
def EquipmentList():
con = sql.connect ("samlple.db")
con.row_factory = sql.Row
cur = con.cursor ()
cur.execute ("select * from device_data")
rows = cur.fetchall ();
return render_template ("EquipmentList.html", rows=rows)
#app.route("/home", methods=["GET", "POST"])
def register():
if request.method == "POST":
P_Name = request.form.get('PatientName')
P_AGE=request.form.get ('Age')
P_Email=request.form.get ('email')
D_Name=request.form.get ('DoctorName')
Phone_No=request.form.get ('phoneNumber')
equipment=request.form.get ('Equipment')
deposit=request.form.get ('Deposit')
disease=request.form.get('Disease')
I_Date=request.form.get ('IssueDate')
R_Date=request.form.get ('ReturnDate')
address = request.form.get('Address')
register = RegistrationData(Patient_Name=P_Name,
Patient_Age=P_AGE,
email=P_Email,
Doctor_Name=D_Name,
PhoneNumber=Phone_No,
Equipment=equipment,
Deposit=deposit,
Disease=disease,
Issue_Date=I_Date,
Return_Date=R_Date,
Address=address
)
db.session.add (register)
db.session.commit()
return render_template ("RegistrationForm.html")
#app.route("/home", methods=["GET", "POST"])
def AddDeviceDB():
if request.method == "POST":
D_Name = request.form.get('DeviceName')
Quantity=request.form.get ('Quantity')
Price=request.form.get ('Price')
Deposit=request.form.get ('Deposit')
Location=request.form.get ('Location')
Description=request.form.get ('Description')
deviceList = DeviceData(DeviceName=D_Name,
quantity=Quantity,
Price=Price,
Deposit=Deposit,
Location=Location,
description=Description
)
db.session.add(deviceList)
db.session.commit()
return render_template ("EquipmentList.html")
if __name__=='__main__':
app.run(debug=True)
}

SQLAlchemy and flask (sqlalchemy.exc.OperationalError:)

I've got this message:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: INSERT INTO user (username, email, password) VALUES (?, ?, ?)]
[parameters: ('test', 'test#test.com', 'password')]
(Background on this error at: http://sqlalche.me/e/e3q8)
when I tried: db.session.commit(). I'm following a tutorial and try to personalize the code but with bad results.
What I did so far is:
>>> from lagerut import db
>>> db.create_all()
>>> from models import User
>>> user_1 = User(username='test', email='test#test.com', password='password')
>>> db.session.add(user_1)
>>> db.session.commit()
Here the lagerut.py:
from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from form import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '2a1de6eea4126191912d6e702c6aa8f9'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///lagerut.db'
db = SQLAlchemy(app)
#app.route('/')
#app.route('/home')
def home():
return render_template ('home.html')
#app.route('/how-it-works')
def howitworks():
return render_template ('how-it-works.html', title='How it works')
#app.route('/lager-out')
def lagerout():
return render_template ('lager-out.html', title='Lager out')
#app.route('/lager-in')
def lagerin():
return render_template ('lager-in.html', title='Lager in')
#app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f'Account created for {form.username.data}!', 'success')
return redirect(url_for('home'))
return render_template('register.html', title='Register', form=form)
#app.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
if form.email.data == 'admin#blog.com' and form.password.data == 'password':
flash('You have been logged in!', 'success')
return redirect(url_for('home'))
else:
flash('Login Unsuccessful. Please check username and password', 'danger')
return render_template('login.html', title='Login', form=form)
if __name__ == '__main__':
app.run(debug=True)
And here the models.py:
from datetime import datetime
from lagerut import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
class Items(db.Model):
item_number = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(200), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
department = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
def __repr__(self):
return f"Items('{self.product}', '{self.date_posted}', '{self.content}', '{self.department}', '{self.content}')"
Should I try to write the code again? I'm just trying to learn how build a little app to my work.
Is a good way to learn programming works also with the shell?
That's because you are not creating the app context while creating the database since you are doing this via python shell you need to add the following line
with app.app_context():
Read more about this here https://flask.palletsprojects.com/en/1.0.x/appcontext/

flask using POST, PUT, DELETE

I keep getting an error on the url when I try to implement POST in my API. I keep getting the error in the URL saying METHOD not Allowed for this URL. Am I missing something? Does POST not work directly when u try to open the server?? I'm soooo lost.
from flask import Flask, jsonify,json, request, abort
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_pyfile('Config.py')
db = SQLAlchemy(app)
db.create_all()
class JsonModel(object):
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class User(db.Model, JsonModel):
User_ID = db.Column(db.Integer, primary_key = True)
FirstName = db.Column(db.String(20))
LastName = db.Column(db.String(20))
def __init__(self,FirstName, LastName):
self.FirstName = FirstName
self.LastName = LastName
class Todo(db.Model, JsonModel):
todo_ID = db.Column(db.Integer, primary_key = True)
UserID = db.Column(db.Integer, db.ForeignKey('User_ID'))
details = db.Column(db.String(30))
def __init__(self,details):
self.details = details
#app.route('/', methods = ['GET'])
def index():
return json.dumps([u.as_dict() for u in User.query.all()+Todo.query.all()])
#app.route('/todo/<int:UserID>', methods = ['GET'])
def get(UserID):
return (list[Todo.query.get(UserID)])
#app.route('/p/', methods = ['POST'])
def create_dev():
if not request.json or not 'name' in request.json:
abort(400)
dev = Todo(request.json.details,request.json.get('details',''))
db.session.add(dev)
db.session.commit()
return json.dumps([{'dev': dev}]), 201
if __name__ == '__main__':
app.run()
You should add GET method to list of allowed methods. When You try to load page, You first need to get page itself using GET method. Then, after filling something on the page, You use POST method to pass some data to the app. In the app, You should check with which method function is called. Something like this:
#app.route('/p', methods=['GET', 'POST'])
def create_dev():
if request.method == 'GET':
return render_template('p_page.html')
# If You get to this line, it means it is POST method
do_something_here()

Categories

Resources