I am doing a flask tutorial from youtube. But however i always get this error. I even copied his code and tried on my pc, but it still raise that error.
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return "<Task %r>" % self.id
#app.route("/", methods=["POST", "GET"])
def index():
if request.method == "POST":
task_content = request.form["content"]
new_task = Todo(content=task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect("/")
except:
return "There was an issue adding your task"
else:
tasks = Todo.query.order_by(Todo.date_created).all()
return render_template("index.html", tasks=tasks)
# return "hello"
if __name__ == "__main__":
app.run(debug=True)
And this is the error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: todo
[SQL: SELECT todo.id AS todo_id, todo.content AS todo_content, todo.date_created AS todo_date_created
FROM todo ORDER BY todo.date_created]
You must create db with tables before trying to call it. Answer in the error text.
Try to read documentation There is lot of information for you. Check method: create_all and second code example from documentation:
>>> from yourapplication import db
>>> db.create_all()
Related
from crypt import methods
from distutils.log import debug
from flask import Flask, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///reg.db'
db = SQLAlchemy(app)
class Todo(db.Model):
name = db.Column(db.String(200), nullable=False)
Bdate = db.Column(db.Integer(), nullable=False)
Gender = db.Column(db.String(6), nullable = False)
Class = db.Column(db.String(9), nullable = False)
Registration = db.Column(db.Integer(), primary_key = True)
date_created = db.Column(db.DateTime, default= datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
SQLALCHEMY_TRACK_MODIFICATIONS = False #to supress warning in terminal
#app.route('/', methods=['POST','GET'])
def index():
if request.method == "POST":
pass
task_content = request.form['card-body']
new_task = Todo(content = task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect('/')
except:
return "Their Was An Error"
else:
task = Todo.query.order_by(Todo.date_created).all()
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Here is my code i dont know how to modify the code to get it run on my Windows. Its my first day of learning flask Please help me out
from crypt import methods
line 9, in <module>
raise ImportError("The crypt module is not supported on Windows")
ImportError: The crypt module is not supported on Windows
this is the error i m getting. Its mostly becasue of POST AND GET in method I guess and i m unable to solve this. I m working on db connection to form in html with the help of Youtube and the guy isusing UNIX so doesnt have any problem but my windows suks here.
you had automatically made this import: from crypt import methods when you were typing this line of code #app.route('/', method... . but this crypt is a Python module used to check Unix passwords and you are using windows. anyway it has nothing to do with flask just delete this line from crypt import methods
This question already has answers here:
SQLAlchemy: How to add column to existing table?
(2 answers)
Closed 9 months ago.
from flask import Flask, redirect, url_for, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import uuid
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///passwords.db'
db = SQLAlchemy(app)
class Passwords(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False)
key = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Name %r>' % self.id
#app.route("/passwords")
def passwords():
return render_template("passwords.html")
#app.route("/")
def home():
return render_template("index.html")
#app.route("/signup", methods=["POST", "GET"])
def new_user():
if request.method == "POST":
a = str(uuid.uuid4())
print(a)
key = Passwords(key=a)
username = request.form["nm"]
newuser = Passwords(name=username)
try:
db.session.add(newuser)
db.session.commit()
db.session.add(key)
db.session.commit()
return redirect(url_for("new_user"))
except:
return "There was an error with your registration"
else:
passcodes = Passwords.query.order_by(Passwords.date_created)
return render_template("signup.html", passcodes=passcodes)
#app.route("/login", methods=["POST", "GET"])
def login():
a = str(uuid.uuid4())
print(a)
if request.method == "POST":
user = request.form["pw"]
if user == a:
return redirect(url_for("user", usr='Η Ακύρωση κράτησης ολοκληρώθηκε'))
else:
return render_template("login.html")
else:
return render_template("login.html")
# app.route("/<usr>")
def user(usr):
return "<h1>{}</h1>".format(usr)
if __name__ == "__main__":
app.run(debug=True)
I get my website up and running but when I go to /signup, an error occurs:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: passwords.key
[SQL: SELECT passwords.id AS passwords_id, passwords.name AS passwords_name, passwords."key" AS passwords_key, passwords.date_created AS passwords_date_created
FROM passwords ORDER BY passwords.date_created]
(Background on this error at: https://sqlalche.me/e/14/e3q8)
Any help is much appreciated
SQLAlchemy only handles creating and dropping tables; it has no support for adding, removing or amending columns, other than executing raw SQL ALTER TABLE statements. If you need to perform such an action your options are, in ascending order of difficulty*:
Drop the entire database (or delete the SQLite file) and run db.create_all() to recreate it
all data will be lost unless you back up the database
Drop the affected table and run db.create_all() to recreate it
Use your database's console or some other database management application to drop the table
If the table is related to other tables via foreign keys then the related tables may need to be deleted too
All data in the table will be lost unless it's backed up
Manually execute the necessary ALTER TABLE statement(s) in your database's console or some other database management application
You will need to ensure that the results match what SQLAlchemy would have created
Use a migration utility to apply model changes to the database
Flask-Migrate is the obvious candidate, but there may be others
* All options assume you have updated the model class
I've looked at the other posts with this same title, but they did not fix my problem. The error message in the above title is what I am getting.
I've made a simple database and constructor for the database. Just to test, I'm trying to add the word "hello" to the column "words" in the class User. But I keep getting this error. I've already tried putting autoincrement in the class column, but I ended it up getting another error. What is going wrong? Please see the code below. Python and Flask.
from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE URI"] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'user'
words = db.Column(db.String(200), primary_key=True)
def __init__(self, thewords):
self.thewords = thewords
db.create_all()
db.session.commit()
texts = "hello"
textstuffent = User(texts)
db.session.add(textstuffent)
db.session.commit()
results = User.query.all()
print(results)
#app.route('/', methods = ['POST', 'GET'])
def hello():
return render_template('Textarea.html')
app.run(debug=True)
For anyone who visits this page in the future, I've found what was wrong. I did not reference "words" as "self.words". My code now works and I am relieved to finally continue coding so that some other bug can confound me later down the road. Please see below. You can see the difference in code in the User class. I used query.all() to prove that data has made it into the database.
from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE URI"] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
words = db.Column(db.String(200), primary_key=True, nullable=False)
def __init__(self, thewords):
self.words = thewords
db.create_all()
db.session.commit()
texts = "hello"
textstuffent = User(texts)
db.session.add(textstuffent)
db.session.commit()
print(User.query.all())
#app.route('/', methods = ['POST', 'GET'])
def hello():
return render_template('Textarea.html')
app.run(debug=True)
I am creating a web form to capture user data and store it to our database. Have created the webform and using flask to store the data in to our postgres database. I am able to parse the request form and store the values in to individual columns, here is my code.
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask import Markup
import sys,os
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = os.urandom(24)
USER = os.environ['USER']
PASSWORD = os.environ['PASSWORD']
HOST_NAME = 'servername'
DB_NAME = 'dbname'
DB_SCHEMA = 'dl_schema'
DB_TABLE = 'update_dummytable'
SQLALCHEMY_DATABASE_URI = "postgresql://{username}:{password}#{hostname}:5432/{databasename}".format(
username=USER,
password=PASSWORD,
hostname=HOST_NAME,
databasename=DB_NAME)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
db = SQLAlchemy(app)
class FormTable(db.Model):
__table_args__ = {'schema': DB_SCHEMA , 'implicit_returning': False}
__tablename__ = DB_TABLE
cid = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String())
last_name = db.Column(db.String())
user_email = db.Column(db.String())
policy_number = db.Column(db.String())
formvalue = db.Column(db.String())
form = db.Column(db.Text())
#app.route('/formupdate', methods=['GET', 'POST'])
def transactions():
if request.method == 'GET':
return render_template('index.html')
updaterequest = FormTable(first_name=request.form["first_name"],
last_name=request.form["last_name"], \
user_email=request.form["user_email"], policy_number=request.form["policy_number"], \
formvalue=request.form["formvalue"], form= request)
db.session.add(updaterequest)
db.session.commit()
return render_template('index.html')
#app.route("/")
def home():
return "Form Update App"
if __name__ == "__main__":
app.run(debug=True)
Above code is working fine, but i am also trying to store the entire request form with user provided values as a html in one of my column in postgres database, i have created a column in my table named "form" as text datatype. But how do I store the entire html with values in that column? When i pass "request.form", it is passing the dictionary with key values but not the html form. Also, when i tried to pass "request" to that column, it throws this error sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'LocalProxy' I can see the insert query has 'form': <Request 'http://127.0.0.1:5000/formupdate' [POST]> , How to pass the entire form with values to database column?
I am trying to run my create_db.py file to create the posts.db database, but it will not get created in my project directory. And when I run the main file for the blog and try to login in I get the error below.
I have looked up this error and seen that other people have gotten it as well and asked about it here on Stackoverflow, but none of them seems to help me. I have read that this could be because something in my blog.py file is running main before the database gets created. But, I am thinking that it has something to do with the configuration. Mainly the PATH of the database could be getting mixed up with the app.config['SQLAlCHEMY_DATABASE_URI'] = 'sqlite:///' line.
Any ideas?
Here is the error
sqlalchemy.exc.OperationalError
OperationalError: (OperationalError) no such table: posts u'SELECT posts.id AS posts_id, posts.title AS posts_title, posts.post AS posts_post \nFROM posts' ()
OperationalError: (OperationalError) no such table: posts u'SELECT posts.id AS posts_id, posts.title AS posts_title, posts.post AS posts_post \nFROM posts' ()
Here is my code. There are three files here: blog.py, models.py, create_db.py
blog.py
# controller of blog app
from flask import Flask, render_template, request, session,\
flash, redirect, url_for, g
from flask.ext.sqlalchemy import SQLAlchemy
import sqlite3
from functools import wraps
# create the application object
app = Flask(__name__)
# configuration
app.secret_key = 'x13xa8xf5}[xfexd4Zxb8+x07=7xc9xe1Bxcfxbdt.ox87oxc9'
app.config['SQLAlCHEMY_DATABASE_URI'] = 'sqlite:///'
# create sqlalchemy object
db = SQLAlchemy(app)
from models import *
# login required decorator
def login_required(test):
#wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return test(*args, **kwargs)
else:
flash('You need to login first.')
return redirect(url_for('login'))
return wrap
#app.route('/', methods = ['GET','POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invalid Credentils. Please try again.'
else:
session['logged_in'] = True
return redirect(url_for('main'))
return render_template('login.html', error=error)
#app.route('/main')
#login_required
def main():
posts = db.session.query(BlogPost).all()
return render_template('main.html', posts=posts)
#app.route('/add', methods=['POST'])
#login_required
def add():
title = request.form['title']
post = request.form['post']
if not title or not post:
flash("All fields are required. Please try again.")
return redirect(url_for('main'))
else:
db.session.add(title)
db.session.add(post)
db.session.commit()
db.session.close()
flash('New entry was successfully posted!')
return redirect(url_for('main'))
#app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('login'))
def connect_db():
return sqlite.connect('posts.db')
if __name__ == '__main__':
app.run(debug = True)
models.py:
from blog import db
class BlogPost(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=False)
post = db.Column(db.String, nullable=False)
def __init__(self, title, post):
self.title = title
self.post = post
def __repr__(self):
return '<title {}'.format(self.title)
create_db.py
from blog import db
from models import BlogPost
# create the database and the db tables
db.create_all()
# insert
db.session.add(BlogPost("Good","I\'m good."))
db.session.add(BlogPost("Well","I\'m well."))
db.session.add(BlogPost("Post","I\'m a post."))
# commit the changes
db.session.commit()
There's a typo in SQLAlCHEMY_DATABASE_URI, should be SQLALCHEMY_DATABASE_URI, the 2nd l.
When running from blog import db some statements in blog.py get executed, including the one with sqlite:/// which is where the path is set. Modifying this line
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
and then after running create_db.py should create a database in app's root directory. There doesn't seem to be another place in the code where the db path is set.
It looks like you may also run into some circular import problems (will throw ImportError: cannot import name [name]). Some solutions are putting the app init stuff like db = SQLAlchemy.. into a separate file or importing at the end of the file.