Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

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

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 functools

from flask import (
    Blueprint, Flask, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash

from 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 input
        ticker_symbol = request.form['ticker_symbol'] # Returns Immutiable (Unchanged) Multi Dictionary
        company_database = get_db()
        error = None
        ticker_symbol = company_database.execute(
            'SELECT * FROM ticker_symbols WHERE ticker_symbol = ?', (ticker_symbol,)
        ).fetchone()

Here is my companydatabase.py file

import sqlite3

import 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_appcontext

def get_db():
# Connects to a database
    if '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.Row

    return 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 package

import os

from flask import Flask


def 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 function
    app = 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 file
    app.config.from_mapping(
        SECRET_KEY='dev', # Temporary
        DATABASE=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 testing
        app.config.from_pyfile('config.py', silent=True)
        # The config.py file replaces the SECRET_KEY with real SECRET_KEY
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)
        # Use code from above (app.config.from_mapping)

    # ensure the instance folder exists
    try:
        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 automatically
    except OSError:
        pass

    from . import auth
    app.register_blueprint(auth.bp)

    from . import company_database
    company_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_app
    response = self.handle_exception(e)
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/nbosio1001/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...