为什么我收到一个不存在的列错误,但该列确实存在?我正在修改Flask教程 [英] Why am I getting a column does not exist error when it does exist? I am modifying the Flask tutorial

查看:36
本文介绍了为什么我收到一个不存在的列错误,但该列确实存在?我正在修改Flask教程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为ticker_symbol的列,但是当我运行没有该列的错误时出现错误.到目前为止,这是我的auth.py代码.它类似于Flask教程代码.我从flaskr.company_database模块获取get_db函数.我试图让用户在论坛中输入股票代码,而我的Python代码将通过数据库查找该股票代码.还有更多代码,但这没关系,因为我无法看清代码的这一部分.

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

这是我的companydatabase.py文件

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

这是我的schema.sql文件

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

这是我的 init 文件

# 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

这是我的回溯

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

推荐答案

更改模式时,再次运行 init-db 命令以重新创建数据库.

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

我认为您的变量 ticker_symbol 导致了问题.请参见此处(Python文档)此处(sqlite3.OperationalError:无此类列:) 了解详情.

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.

这篇关于为什么我收到一个不存在的列错误,但该列确实存在?我正在修改Flask教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆