Database Entry not Happening in Flask App with SQL Alchemy? - python

APP CODE : There is no entry in the database and i am new at Flask and i am not able to connect to database and get entry into it and i am confused is my code is at all right
from flask import *
from wtforms import *
from wtforms.validators import Required
from flask.ext.wtf import Form
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = 'MY CSI FORM'
branch_choices = [('CSE','CSE'),('ECE','ECE'),('MEC','MEC'),('CIVIL','CIVIL')]
year_choices = [('1st','1st'),('2nd','2nd'),('3rd','3rd'),('4th','4th')]
cmem_choices = [('Yes','Yes'),('No','No')]
class CSIForm(Form):
er = IntegerField('Enrollment No',validators=[Required()])
name = StringField('Name', validators=[Required()])
branch = SelectField('Branch',choices=branch_choices, validators=[Required()])
year = SelectField('Year',choices=year_choices, validators=[Required()])
cmem = SelectField('CSI Member',choices=cmem_choices,validators=[Required()])
sop = TextAreaField('Statement of Purpose', validators=[Required()])
submit = SubmitField('Submit')
DATABASE CODE : Code for database creation in SQLAlchemy dont know its correct or not
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
class CSI(db.Model):
__tablename__ = 'form'
er = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
branch = db.Column(db.String(3))
year = db.Column(db.String(3))
cmem = db.Column(db.String(3))
sop = db.Column(db.String(50))
def __init__(self, er, name, branch, year, cmem, sop):
self.er = er
self.name = name
self.branch = branch
self.year = year
self.cmem = cmem
self.sop = sop
def connect_db():
db.create_all()
App running and connection
#app.route('/', methods=['GET', 'POST'])
def index():
form=CSIForm(request.form)
connect_db()
if form.validate_on_submit():
csi = CSI()
form.populate_obj(csi)
flash('Thanks for registering')
return render_template('form.html',form=form)
if __name__ == "__main__":
app.debug='True'
app.run()

You'll probably want to read up on sessions in SQLAlchemy. You need to add csi to your current session and commit the transaction.
def index():
form = CSIForm(request.form)
connect_db()
if form.validate_on_submit():
csi = CSI()
form.populate_obj(csi)
# These lines are new.
db.session.add(csi)
db.session.commit()
flash('Thanks for registering')

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)

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)
}

AttributeError: 'scoped_session' object has no attribute 'get'

I am trying to delete data from my database but my web application returns this error:
File "C:\Users\q\Pyc\Flask\basic_of_flask\SQL Database with flask\Database in view\adoption_sit.py", line 78, in del_pup
pup = db.session.get(id)
AttributeError: 'scoped_session' object has no attribute 'get'
have a look at my code below
import os
from flask import Flask, redirect, render_template, url_for
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from form import AddForm, DelForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
#######################################
#### SQL DATABASE SECTION #############
#######################################
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db)
########################################
######## Models ########################
########################################
class Puppy(db.Model):
__tablename__ = 'puppies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Puppy name is {self.name}."
#############################################
##### VIEW FUNCTIONS -- HAVE FORM ###########
#############################################
#app.route('/')
def index():
return render_template('home.html')
#app.route('/add', methods=['GET', 'POST'])
def add_pup():
form = AddForm()
if form.validate_on_submit():
name = form.name.data
new_puppy = Puppy(name)
db.session.add(new_puppy)
db.session.commit()
return redirect(url_for('list_pup'))
return render_template('add.html', form=form)
#app.route('/list_pup')
def list_pup():
puppies = Puppy.query.all()
return render_template('list.html', puppies=puppies)
#app.route('/delete', methods=['GET', 'POST'])
def del_pup():
form = DelForm()
if form.validate_on_submit():
id = form.id.data
pup = db.session.get(id)
db.session.delete(pup)
db.session.commit()
return redirect(url_for('list_pup'))
return render_template('delete.html', form=form)
db.create_all()
if __name__ == '__main__':
app.run(debug=True)
and here is my form.py file
# form.py
from flask_wtf import FlaskForm
from wtforms import SubmitField, StringField, IntegerField
class AddForm(FlaskForm):
name = StringField('Name of puppy:')
submit = SubmitField('Submit puppy')
class DelForm(FlaskForm):
id = IntegerField("Id number of puppy to be remove:")
submit = SubmitField("Remove puppy")
i guess you are doing things the wrong way in del_pup() function
[..]
pup = db.session.get(id) # here
you need to get the Puppy object with the given id like:
#app.route('/delete', methods=['GET', 'POST'])
def del_pup():
form = DelForm()
if form.validate_on_submit():
id = form.id.data
# pup = db.session.get(id) # wrong way
pup = Puppy.query.filter_by(id=id).first()` # here
db.session.delete(pup)
db.session.commit()
return redirect(url_for('list_pup'))
return render_template('delete.html', form=form)

ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'FileStorage'

I just want to write a filename from data to my model.
How to get filename from filestorage?
I'm using Flask for my web app. I create form that include FileField.
It is important for me to get the same filename.
Form:
class TableForm(FlaskForm):
file = FileField('Add file', validators=[FileAllowed(['xlsx', 'xls', 'csv'])])
submit = SubmitField('Add file')
Model:
class Table(db.Model):
__table_args__= {'schema': 'app'}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(240), nullable=False)
table_file = db.Column(db.String(80), nullable=False)
Routes:
#app.route("/projects/<int:project_id>", methods=['GET', 'POST'])
#login_required
def project_data_source(project_id):
tables = Table.query.filter_by(project_id=project_id)
if project.author != current_user:
abort(403)
form = TableForm()
if form.validate_on_submit():
table = Table(name=form.file.data, table_file=form.file.data)
db.session.add(table)
db.session.commit()
return redirect(url_for('project_data_source'))
There's a pretty good example on their docs. Here's how you get the file name:
from werkzeug.utils import secure_filename
f = form.file.data
filename = secure_filename(f.filename)
So your code would need to be:
from werkzeug.utils import secure_filename
#app.route("/projects/<int:project_id>", methods=['GET', 'POST'])
#login_required
def project_data_source(project_id):
tables = Table.query.filter_by(project_id=project_id)
if project.author != current_user:
abort(403)
form = TableForm()
if form.validate_on_submit():
filename = secure_filename(form.file.data.filename)
table = Table(name=filename, table_file=filename) # not sure why you save it twice here
db.session.add(table)
db.session.commit()
return redirect(url_for('project_data_source'))

flask can't connect sqlalchemy

I want to connect sql using sqlalchemy on flask
but it can't
there is a error
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1049, "Unknown database 'alchemy_new'")
I can't solve this problem.
# -*- coding:utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:12345#localhost/catchat'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(120), unique=True)
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % self.username
user_inf = {'user1' : {'username':'jaeyeonkim','email':'jaeyeon93#naver.com', 'password':'12345'}}
def not_exist(user_id):
if user_id not in user_inf:
abort(404, message="{} does not exist".format(user_id))
parser = reqparse.RequestParser()
parser.add_argument('username')
parser.add_argument('email')
parser.add_argument('password')
class user(Resource):
def get(self, user_id):
not_exist(user_id)
return user_inf[user_id]
def delete(self,user_id):
not_exist(user_id)
del user_inf[user_id]
return '', 200
def put(self,user_id):
args = parser.parse_args()
not_exist(user_id)
a = {}
a['username'] = args['username']
a['email'] = args['email']
a['password'] = args['password']
user_inf[user_id] = a
return a, 200
class userlist(Resource):
def get(self):
return user_inf
def post(self):
args = parser.parse_args()
new_user = user_inf(args['username'], args['email'], args['password'])
new_user_id = db.session.add(new_user)
db.session.commit()
return new_user_id, 200
api.add_resource(userlist, '/users')
api.add_resource(user,'/api/v1/users/<user_id>')
if __name__ == '__main__':
app.run(debug=True)
First of all I have no idea why password shall be unique ;)
Secondly it looks like sqlalchemy doesn't recognize you connection string.
Try:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:////root:12345#localhost/catchat'
According to the following codeļ¼š
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:12345#localhost/catchat'
Your database is 'catchat'.Please create it.
mysql -u root -p12345
create database catchat;
And create table before use it.
db.create_all()
Finally, just a suggestion: don't use flask-restful to define api, please choose
#app.route("/user", methods=["GET"]), it is simple, easy and useful.
Trust me. Two weeks ago, I just rewrite my code from flask-restful to app.route.

Categories

Resources