无法初始化数据库,wtforms-alchemy,flask,ERROR LookupError:转换器“ init”不存在

时间:2019-04-04 20:48:28

标签: mysql python-3.x flask flask-wtforms

我正在更改我的应用程序设置,使其更容易包含https://wtforms-alchemy.readthedocs.io/en/latest/introduction.html文档中的wtforms-alchemy,我将代码简化为基本知识,以便在遇到任何错误时都能更快地找到它。 ,问题在于必须使用这些代码片段才能使wtforms-alchemy与flask一起使用,这是链接https://wtforms-alchemy.readthedocs.io/en/latest/advanced.html

当我删除此代码片段时,由于无法识别ModelForm类,因此无法初始化数据库,这就是我要继续的原因。在文档中它指出只需要摘要,但是我想知道这是否是我的主要__init__.py设置错误。

应用__init__.py

import os
import RPi.GPIO as GPIO
from flask import Flask, request, current_app
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_wtf import FlaskForm
from wtforms_alchemy import model_form_factory

db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
login.login_message = 'Please log in to access this page.'
mail = Mail()
bootstrap = Bootstrap()

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(Config)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)


   from homeHeating.auth import bp as auth_bp
   app.register_blueprint(auth_bp)

control.py

from homeHeating import db
from homeHeating.control.forms import AddPinForm
from homeHeating.models import User, Pins
from homeHeating.control import bp
from mySensorModule import read_sensor
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)


@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
   pins = Pins.query.all()
   for pin in pins:
       GPIO.setup(pin.pin, GPIO.OUT)
       pin.state = GPIO.input(pin.pin)
       db.session.commit()
   templateData = {
       'pins' : pins
     }
   return render_template('control/index.html', **templateData)

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import ValidationError, DataRequired, Email, 
EqualTo
from homeHeating.models import User, Pins
from wtforms_alchemy.fields import QuerySelectField
from wtforms_alchemy import model_form_factory


BaseModelForm = model_form_factory(FlaskForm)

class ModelForm(BaseModelForm):
    @classmethod
    def get_session(self): #this part is the problem
        return db.session

class AddPinForm(ModelForm):
    class Meta:
        model = Pins

    def validate_Name(self, name):
        pins = Pins.query.filter_by(pin=name.data).first()
        if pins is not None:
           raise ValidationError('Please use a different name.')

错误

  File "/home/pi/heating/homeHeating/__init__.py", line 38, in create_app
app.register_blueprint(control_bp)
raise LookupError('the converter %r does not exist' % converter_name)
LookupError: the converter 'init' does not exist

我希望可以按照文档中的说明初始化数据库,我认为错误是在我的 init .py文件中,我可能在其中使用了sqlalchemy,但是这超出了我!错误代码已经很久了,但是我已经包括了我认为指示问题的两行。 如果代码过多或不足,我先向您致歉,请询问是否需要更多。 问候保罗

编辑 我忘了添加'models.py'

models.py

from homeheating import db, login
from datetime import datetime
from time import time
from flask import current_app
from flask_wtf import FlaskForm
class Pins(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    pin = db.Column(db.Integer, index=True, unique=True)
    name = db.Column(db.String(64))
    upDown = db.Column(db.String(4))
    state = db.Column(db.String(9))

    def __repr__(self):
        return '<Pins {}>'.format(self.pin)

EDIT2 我很抱歉,我没有在“ control.py”中包含所有代码,在今天早上玩完这些代码之后,我发现以下功能可能是问题。这就是我所做的。我已将代码段从“ forms.py”移动到“ models.py”,并将“ ModelForm”添加到表单导入中(即从homeHeating.models导入ModelForm,...)。 因此,请参见“ control.py”中有问题的代码(可能)

control.py

@bp.route('/control/addpin/<init:id>', methods=['GET', 'POST'])
@login_required
def add_or_edit_pin(id=None):
    obj = Pins.query.get_or_404(id)
    form = AddPinForm(request.form, obj=obj)
    if form.validate_on_submit():
        form.populate_obj(obj)
        db.session.add(obj)
        db.session.commit()
        flash('Congratulations, you have now a registered a device!')
        return redirect(url_for('control.addpin'))
    return render_template('control/addpin.html', title='Add pin',
                       form=form)

这是个好消息,因为我可以使用wtforms-alchemy,但是坏消息,因为此add_edit函数对我的计划至关重要,因为我想对每种形式使用此模型! PS。该代码来自我的另一个问题以及wtforms-alchemy网站上的帮助。

0 个答案:

没有答案