2

我正在尝试为我的分析师团队构建一个小型 Web 应用程序。他们只需要一个可以添加和查看他们编写的查询的存储库。

到目前为止,我一直无法实现我的应用程序,因为我无法跨视图/类导入函数。有人可以帮我弄清楚我的问题是什么吗?

我收到此错误:

File "C:\Users\Intern2\PycharmProjects\queries-Final2\queries_Final2.py", line 12, in <module>
from search_queries import SearchQueries
ImportError: cannot import name SearchQueries

我认为这个问题与我尝试将每个文件导入另一个文件的事实有关。但是,我不知道有任何其他方法可以做到这一点。

这是我的代码:

query_Final2.py(主应用程序文件)

from __future__ import with_statement
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort,\
render_template, flash, _app_ctx_stack
import flask
import settings
import functools

# Views
from main import Main
from login import Login
from search_queries import SearchQueries
from add_queries import AddQueries
from edit_queries import EditQueries

DATABASE = 'C:\\Users\\Intern2\\PycharmProjects\\queries-Final2\\queriesDB.db'

app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
app.secret_key = settings.secret_key

app.add_url_rule('/search-queries/',
view_func=SearchQueries.as_view('search-queries'),
methods=["GET", "POST"])

app.add_url_rule('/add-queries/',
view_func=AddQueries.as_view('add-queries'),
methods=["GET", "POST"])

def init_db():
"""Creates the database tables."""
with app.app_context():
    db = get_db()
    with app.open_resource('schema.sql') as f:
        db.cursor().executescript(f.read())
    db.commit()

def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
    return top.sqlite_db

显示查询视图/类

from __future__ import with_statement
from sqlite3 import dbapi2 as sqlite3
 from flask import Flask, request, session, g, redirect, url_for, abort,\
render_template, flash, _app_ctx_stack
import flask
import settings
import functools
from queries_Final2 import get_db
import utils

class SearchQueries(flask.views.MethodView):
    @utils.login_required
def get(self):
    db = get_db()
    cur = db.execute('select title, columns, query, notes, tags from entries order by id desc')
    entries = [dict(title=row[0], columns=row[1], query=row[2],notes=row[3],tags=row[4]) for row in cur.fetchall()]
    return render_template('search-queries.html', entries=entries)

添加查询类/视图

from __future__ import with_statement
from flask import Flask, request, session, g, redirect, url_for, abort,\
render_template, flash, _app_ctx_stack
import flask
import functools
import utils
from queries_Final2 import get_db

class AddQueries(flask.views.MethodView):
    @utils.login_required
def get(self):
    return flask.render_template('add-queries.html')

def post(self):
    db = get_db()
    db.execute('insert into entries (title, columns, query, notes, tags) values (?, ?, ?, ?, ?)',
    [request.form['title'],
     request.form['columns'],
     request.form['query'],
     request.form['notes'],
     request.form['tags']
    ])
    db.commit()
    flash('New entry was successfully posted')
    return flask.render_template('search-queries.html')

任何想法将不胜感激。提前致谢。

4

1 回答 1

3

您有一个由 触发的循环导入from queries_Final2 import get_db

您正在有效地执行此操作(伪代码):

# Inside module A
import x from module B
    -> goes to module B to get x
    -> module B begins loading its imports (happens on first import)
    -> module B imports y from module A
    -> module B fails to import y from module A because module A is still being defined

随着时间的推移,您将学习如何以一种可以避免此问题的方式抽象您的工具,但与此同时,您可以通过简单地将行移到您的和函数from queries_Final2 import get_db内部来解决它,而不是将它们留在模块级别。getpost

于 2012-12-13T19:04:19.940 回答