python 为什么此Flask程序未运行

6l7fqoea  于 2023-06-20  发布在  Python
关注(0)|答案(1)|浏览(118)

这个程序是从python flask,HTML,Tailwind CSS创建的,我知道这个程序会给予,但我不知道如何正确修复它,这就是为什么我在堆栈溢出中问我的问题。首先,我会告诉你文件结构:
File Structure
首先main.py代码:

from website import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

第二个auth.py代码:

# Importing all Modules
from flask import Blueprint, render_template, request, flash, redirect, url_for, Flask
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db   #means from __init__.py import db
from flask_login import login_user, login_required, logout_user, current_user
from flask_mail import Mail, Message
from random import *
from flask import current_app

# Creating the AUTH Blueprint
auth = Blueprint(__name__)

# Flask Mail Setup
auth.config['MAIL_SERVER'] = 'smtp.gmail.com'
auth.config['MAIL_PORT'] = 465
auth.config['MAIL_USERNAME'] = 'TombTab123@gmail.com'
auth.config['MAIL_PASSWORD'] = 'TombTab101#'
auth.config['MAIL_USE_TLS'] = False
auth.config['MAIL_USE_SSL'] = True

# Generating Verification email OTP
otp = randint(000000, 999999)

# Login Endpoint
@auth.route('/login', methods=['GET', 'POST'])
# Login Function
def login():
    # If Statement
    if request.method == 'POST':

        # Requesting Email and password
        email = request.form.get('email')
        password = request.form.get('password')

        # User query
        user = User.query.filter_by(email=email).first()

        # IF USER
        if user:

            # Checking Password Hash
            if check_password_hash(user.password, password):

                # Giving The Hash If the hash mathches than we will flash success message
                flash('Logged in successfully!', category='success')

                # Login User
                login_user(user, remember=True)

                # Redirect
                return redirect(url_for('views.home'))
            else:
                # Incorrect Password
                flash('Incorrect password, try again.', category='error')
        else:
            # Email Does not exist
            flash('Email does not exist.', category='error')
            
    # Returning Our Template
    return render_template("login.html", user=current_user)

# Logout Endpoint
@auth.route('/logout')
# Logout Function
@login_required
# Login Required
# Logout Function
def logout():
    # Just Logout
    logout_user()
    # Redirect To Login Page
    return redirect(url_for('auth.login'))

# Signup Endpoint
@auth.route('/sign-up', methods=['GET', 'POST'])
# Signup Function
def sign_up():
    a= 2
    # If Request Method is POST then
    if request.method == 'POST':

        # Forms Request
        email = request.form.get('email')
        first_name = request.form.get('firstName')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        # User Query
        user = User.query.filter_by(email=email).first()

        # symbols = ['''~`!@#$%^&*()_+-={}|":<>?[];'\,./''']

        # Flash Messages
        if user:
            flash('Email already exists.', category='error')

        elif len(email) < 4:
            flash('Email must be greater than 3 characters.', category='error')

        elif len(first_name) < 2:
            flash('First name must be greater than 1 character.', category='error')

        elif password1 != password2:
            flash('Passwords don\'t match.', category='error')

        elif len(password1) < 7:
            flash('Password must be at least 7 characters.', category='error')
            
        else:
            new_user = User(email=email, first_name=first_name, password=generate_password_hash(
                password1, method='sha256'))
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user, remember=True)
            flash('Account created!', category='success')
            return redirect(url_for('views.home'))

    # Returning The Template
    return render_template("sign_up.html", user=current_user)

@auth.route('/verify', methods=['POST'])
def verify():
    email = request.form['email']
    msg=Message(subject='OTP',sender='vinayakchandra561@gmail.com',recipients=[email])
    msg.body=str(otp)
    Mail.send(msg)
    return render_template('verify.html')

@auth.route('/validate', methods=['POST'])
def validate():
    user_otp=request.form['otp']
    if otp==int(user_otp):
        return "<body bgcolor='red'><h3>Email Verification</h3></body>"
    return "<h3>Please Try Again</h3>"

第三models.py代码:

# Importing modules
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

# Class Note
class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

# Class User
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    notes = db.relationship('Note')

第四views.py代码:

from flask import Blueprint, render_template, request, flash, jsonify
from flask_login import login_required, current_user
from .models import Note
from . import db
import json

views = Blueprint('views', __name__)

@views.route('/', methods=['GET', 'POST'])
@login_required
def home():
    if request.method == 'POST': 
        note = request.form.get('note')#Gets the note from the HTML 

        if len(note) < 1:
            flash('Note is too short!', category='error') 
        else:
            new_note = Note(data=note, user_id=current_user.id)  #providing the schema for the note 
            db.session.add(new_note) #adding the note to the database 
            db.session.commit()
            flash('Note added!', category='success')

    return render_template("home.html", user=current_user)

@views.route('/delete-note', methods=['POST'])
def delete_note():  
    note = json.loads(request.data) # this function expects a JSON from the INDEX.js file 
    noteId = note['noteId']
    note = Note.query.get(noteId)
    if note:
        if note.user_id == current_user.id:
            db.session.delete(note)
            db.session.commit()

    return jsonify({})

第五个init.py代码:

# Importing all modules
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager

# Settuping SQLAlchemy
db = SQLAlchemy()
DB_NAME = "database.db"

# The Create app Function Means this will Create our flask app and help our main.py
def create_app():

    # Settuping Flask App and Database
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    # Importing
    from .views import views
    from .auth import auth

    # Registering Our Blueprints
    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    # Importing User and Note
    from .models import User, Note
    
    # Using Our Database
    with app.app_context():
        db.create_all()

    # Login Manager
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    # Loading User
    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))
    
    # Returning Our App
    return app

# Creating Our Database Function
def create_database(app):

    # If Statement
    if not path.exists('website/' + DB_NAME):

        # Creating Database
        db.create_all(app=app)
        print('Database Created!')

我知道我不需要给予HTML和Tailwind CSS代码,也是错误:

Traceback (most recent call last):
  File "F:\Files\Python\Flask\Authentication Systems\Authentication System With TailwindCSS\main.py", line 3, in <module>
    app = create_app()
ite\auth.py", line 12, in <module>
    auth = Blueprint(__name__)
           ^^^^^^^^^^^^^^^^^^^
TypeError: Blueprint.__init__() missing 1 required positional argument: 'import_name'

我知道这个错误发生在www.example.com文件中的auth.config中auth.py,但如何修复它
我期待这个程序将运行没有问题清楚,实际上间接我期待这个程序将给予错误。但我希望结果没有错误。

qcuzuvrc

qcuzuvrc1#

问题出在这个代码块中
auth = Blueprint(__name__)
你需要像这里一样提供一个名字
views = Blueprint('views', __name__)
改成auth = Blueprint('auth', __name__)之类的

相关问题