У меня возникла проблема такого рода, имеется веб приложение начальное, есть авторизация с базой данных, имеется форма LoginForm, но я хочу сделать еще и регистрацию, поэтому в этом же файле forms.py создал еще один класс Registation, заполнил все как пологается
сначала ругался на вот эту строчку кода(на Users):
user = Users.query.filter_by(email=self.email.data).first()
после я сделал from start import Users
(импортировал из start.py базу данных Users)
после чего, ошибка ушла, теперь же я в start.py делаю from forms import LoginForm, Registartion:
и при запуске приложения возникает вот такая ошибка:
C:\Users\user8\PycharmProjects\web>python start.py
Traceback (most recent call last):
File "start.py", line 10, in
from forms import LoginForm
File "C:\Users\user8\PycharmProjects\web\forms.py", line 4, in
from start import Users
File "C:\Users\user8\PycharmProjects\web\start.py", line 10, in
from forms import LoginForm
ImportError: cannot import name 'LoginForm' from 'forms' (C:\Users\user8\PycharmProjects\web\forms.py)
-----------------------------
Если же убрать форму Registration, то все работает отлично, но как только добавляю к импорту еще Registration, то ошибочка, прошу помочь.
вот весь код для наглядности:
start.py
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, DateTime
from flask_migrate import Migrate, MigrateCommand
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_required, login_user, current_user, logout_user
from flask_mail import Mail, Message
from forms import LoginForm, Registration
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///usersinfo.db'
app.config['SECRET_KEY'] = 'a really really really really long secret key'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'youmail@gmail.com'
app.config['MAIL_DEFAULT_SENDER'] = 'youmail@gmail.com'
app.config['MAIL_PASSWORD'] = 'password'
manager = Manager(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
mail = Mail(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return db.session.query(Users).get(user_id)
@app.route('/')
@login_required
def admin():
return render_template('login.html')
@app.route('/login/', methods=['post', 'get'])
def login():
if current_user.is_authenticated:
return redirect(url_for('admin'))
form = LoginForm(request.form)
if form.validate_on_submit():
user = db.session.query(Users).filter(Users.username == form.username.data).first()
if user and user.check_password(form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('admin'))
flash("Invalid username/password", 'error')
return redirect(url_for('login'))
return render_template('login.html', form=form)
@app.route('/registration', methods=['post', 'get'])
def registration():
form = Registration(request.form)
if form.validate_on_submit():
user = Users(email=form.email.data,
username=form.username.data,
password_hash=form.password.data,
)
db.session.add(Users)
db.session.commit()
return redirect(url_for('login'))
return render_template('registration.html', form=form)
@app.route('/logout/')
@login_required
def logout():
logout_user()
flash("You have been logged out.")
return redirect(url_for('login'))
class Users(db.Model, UserMixin):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(80), unique=True, nullable=False)
email = Column(String(100), unique=True, nullable=False)
password_hash = Column(String(80), nullable=False)
created_on = Column(DateTime(), default=datetime.utcnow)
updated_on = Column(DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow)
def __init__(self, email, username, password_hash):
self.email = email
self.username = username
self.password_hash = password_hash
def __repr__(self):
return "<{}:{}>".format(self.id, self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
db.create_all()
db.session.commit()
if __name__ == "__main__":
app.run(port=5001)
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from start import Users
class LoginForm(FlaskForm):
username = StringField("Username", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
remember = BooleanField("Remember Me")
submit = SubmitField()
class Registration(FlaskForm):
username = StringField("username: ", validators=[DataRequired()])
email = StringField("email: ", validators=[DataRequired(), Length(min=6, max=255)])
password_hash = PasswordField("password: ", validators=[DataRequired(), Length(min=6, max=255)])
submit = SubmitField()
def validate(self):
initial_validation = super(Registration, self).validate()
if not initial_validation:
return False
user = Users.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
-----------------------------------------
Если же сделать все как я делаю, все импорты соблюдены , то тогда выдает вот такую ошибку
C:\Python37.3\python.exe -m flask run
* Serving Flask app "start.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: python -m flask run [OPTIONS]
Error: While importing "start", an ImportError was raised:
Traceback (most recent call last):
File "C:\Python37.3\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\user8\PycharmProjects\web\start.py", line 10, in
from forms import LoginForm, Registration
File "C:\Users\user8\PycharmProjects\web\forms.py", line 4, in
from start import Users
ImportError: cannot import name 'Users' from 'start' (C:\Users\user8\PycharmProjects\web\start.py)