Why am I getting a column does not exist error when it does exist? I am modifying the Flask tutorial

2024/11/19 8:40:40

I have a column named ticker_symbol, but I am getting a error when I run the error that there is no such column. Here is my auth.py code so far. It is similar to the Flask tutorial code. I get my get_db function from the flaskr.company_database module. I am trying to have the user input a stock symbol into the forum and my Python code will go through the database to find that ticker symbol. There is more code, but it doesn't matter since I can't get through this portion of the code.

import functoolsfrom flask import (Blueprint, Flask, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hashfrom flaskr.company_database import get_db#app = Flask(__name__)
bp = Blueprint('stock_search', __name__, url_prefix='/')@bp.route('/', methods=('GET', 'POST'))
def enter_ticker_symbol():if request.method == 'POST': # The server accepts user inputticker_symbol = request.form['ticker_symbol'] # Returns Immutiable (Unchanged) Multi Dictionarycompany_database = get_db()error = Noneticker_symbol = company_database.execute('SELECT * FROM ticker_symbols WHERE ticker_symbol = ?', (ticker_symbol,)).fetchone()

Here is my companydatabase.py file

import sqlite3import click
from flask import current_app, g
# g stores data that might need to be accessed by multiple functions during request
# current_app 
from flask.cli import with_appcontextdef get_db():
# Connects to a databaseif 'company_database' not in g:g.company_database = sqlite3.connect(current_app.config['DATABASE'],detect_types =  sqlite3.PARSE_DECLTYPES)g.company_database.row_factory = sqlite3.Rowreturn g.company_database

Here is my schema.sql file

DROP TABLE IF EXISTS ticker_symbols;CREATE TABLE ticker_symbols (id INT PRIMARY KEY AUTOINCREMENT,ticker_symbol VARCHAR (10),company_name VARCHAR(255)
);

Here is my init file

# This file contains application factory (whatever that means, provides structural foundation for flask app) and flaskr treated as packageimport osfrom flask import Flaskdef create_app(test_config=None): # This function is known as the application factoryu# create and configure the app# Any configuration, registration, and other setup the application needs happens inside functionapp = Flask(__name__, instance_relative_config=True)# Creates flask instance# __name__ is name of current Python module# instance_relative_config=True shows configuration files are relative to instance folder# Instance folder is outside flaskr package and can hold local data that shouldn't be commited to version control# Examples of files that shouldnt be with version control, configuration secrets and database fileapp.config.from_mapping(SECRET_KEY='dev', # TemporaryDATABASE=os.path.join(app.instance_path, 'flask.sqlite'),# SQLite database file is stored here.)if test_config is None:# load the instance config, if it exists, when not testingapp.config.from_pyfile('config.py', silent=True)# The config.py file replaces the SECRET_KEY with real SECRET_KEYelse:# load the test config if passed inapp.config.from_mapping(test_config)# Use code from above (app.config.from_mapping)# ensure the instance folder existstry:os.makedirs(app.instance_path)# Does the app.instance path exist?# This is needed because the SQLite database file will be created there# Flask doesnt create instance folders automaticallyexcept OSError:passfrom . import authapp.register_blueprint(auth.bp)from . import company_databasecompany_database.init_app(app)return app

Here is my traceback

Traceback (most recent call last):File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__return self.wsgi_app(environ, start_response)File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_appresponse = self.handle_exception(e)File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exceptionreraise(exc_type, exc_value, tb)File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraiseraise valueFile "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_appresponse = self.full_dispatch_request()File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_requestrv = self.handle_user_exception(e)File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exceptionreraise(exc_type, exc_value, tb)File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraiseraise valueFile "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_requestrv = self.dispatch_request()File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_requestreturn self.view_functions[rule.endpoint](**req.view_args)File "/home/nbosio1001/Documents/python/Fundamental_Analysis/selenium_python_small_sample_project/flask-tutorial/flaskr/auth.py", line 20, in enter_ticker_symbol'SELECT * FROM ticker_symbols WHERE ticker_symbol = ?', (ticker_symbol,)
sqlite3.OperationalError: no such column: ticker_symbol
Answer

Run the init-db command again to recreate the database when you change the schema.

$ flask init-db

Alternative execute

Can you please try the following

ticker_symbol = company_database.execute('SELECT * FROM ticker_symbols WHERE ticker_symbol=:my_selector', {"my_selector": ticker_symbol}).fetchone()

I think that your variable ticker_symbol causes the problem. See here (Python Doc) and here (sqlite3.OperationalError: no such column:) for details.

Also make sure that you have actually created you table, as pointed out above by a comment.

https://en.xdnf.cn/q/119972.html

Related Q&A

Update Key Value In Python In JSON File

How do I change a value in a json file with python? I want to search and find "class": "DepictionScreenshotsView" and replace it with "class": ""JSON File:{&quo…

Getting UnboundLocalError: local variable age referenced before assignment error

Ive written a simple script with TKinter and SQLAlchemy, where an sqlite .db is created, saving Employee information such as name, age, address, etc, etc.I realized that if a user puts a string in the …

Cannot run python script [duplicate]

This question already has answers here:What does "SyntaxError: Missing parentheses in call to print" mean in Python?(11 answers)Closed 9 years ago.I am trying to run this python script:https…

I want to read multiple audio files with librosa and then save it into an empty list

Here id my code . when I append into the array the array remain empty . Please help me where is the mistake. Or tell me some other way also to do thisA = [] # load more files with librosa pathAudio = …

How to db.execute in postgresql using the LIKE operator with variables within flask [duplicate]

This question already has an answer here:CS50: LIKE operator, variable substitution with % expansion(1 answer)Closed 4 years ago.Im trying to get my db.execute to work but encounter a syntax error when…

C, Perl, and Python similar loops different results

I wrote scripts to calculate pi in python, perl and c. They all use the same algorithm (trapezoidal reimann sum of a circle with n subintervals) and the python and perl programs always get the same re…

How to print a single backslash in python in a string? [duplicate]

This question already has answers here:Why do backslashes appear twice?(2 answers)Closed 1 year ago.In python (3x version)\ # this is error no doubt \\ # this prints two backslashes ,i.e., \\ r\ # thi…

Return nested JSON item that has multiple instances

So i am able to return almost all data, except i am not able to capture something like this:"expand": "schema""issues": [{"expand": "<>","id…

What request should I make to get the followers list from a specific profile page

I am trying to get the followers list from this profile, I tried making a GET request using python requests to the API using this request URL but it didnt seem to work, I got a METHOD_NOT_ALLOWED error…

PlayerDB API Post Requests bring 404

I made a little script to get the UUIDs of people who joined my minecraft server, then run them through the PlayerDB API through a post request to: https://playerdb.co/api/player/minecraft/* where the …