你的经理在处理蓝图

2024-05-23 18:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

试图让我的Flask应用程序从守护程序服务运行。其中大部分是一个框架,为了保持简单,我将大部分代码(作为一个独立的Flask应用程序运行良好)导入routes.py。我的脚本没有使用蓝图,所以我尝试对它进行调整,但是当它运行时,我得到了AttributeError: 'Flask' object has no attribute 'login_manager'。如果我删除了所有与登录管理器相关的代码,那么守护进程可以正常运行,但不能与登录管理器一起运行。我读到,这是因为该应用程序正在运行之前,登录管理器。我试着遵循这个逻辑,但没能解决它。我应该如何实现登录管理器模块? (我去掉了不相关的部分)

.
├── __init__.py
├── __main__.py
└── daemon
    ├── __init__.py
    ├── config.py
    ├── dependencies.py
    ├── implementation.py
    ├── routes.py
    └── user.db

main.py

from pxeadmin.daemon.implementation import PxeAdmin
from pxeadmin.daemon.routes import DAEMON_BLUEPRINT, register_error_handlers

def _main():
    # Instantiate the singleton. We must do this first to get an instance of the Flask app.
    daemon_app = PxeAdmin()

    # Set up the Flask error handlers and registering the daemon blueprint so that our HTTP endpoints work.
    register_error_handlers(daemon_app.flask_app)
    daemon_app.flask_app.register_blueprint(DAEMON_BLUEPRINT)

    # Run the implementation.
    daemon_app.run()


if __name__ == '__main__':
    _main()

路线.py

import re, csv, os
import logging
from flask import Flask, render_template, flash, redirect, url_for, Blueprint
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
from flask_login import LoginManager, login_required, UserMixin, login_user, logout_user
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import check_password_hash
from pxeadmin.daemon.implementation import PxeAdmin


LOG = logging.getLogger(__name__)

# Make sure this matches your repo's template directory
TEMPLATE_FOLDER = 'templates'
DAEMON_BLUEPRINT = Blueprint('daemon.routes.blueprint', __name__, template_folder=TEMPLATE_FOLDER)

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["SECRET_KEY"] = "xc7rx86xaxa4stLxd5xdbx18Sx1e"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'user.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
db.init_app(app)
app.register_blueprint(DAEMON_BLUEPRINT)

class MyForm(FlaskForm):
    name = StringField('Full Name:')
    uname = StringField('Username:')
    asset = StringField('Asset Tag:')
    mac = StringField('MAC Address:')
    mac_remove = StringField('MAC Address:')

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)


class LoginForm(FlaskForm):
    u = StringField('Username: ', validators=[DataRequired()])
    p = PasswordField('Password: ', validators=[DataRequired()])

#initialize and setup login_manager for login workflow
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.init_app(app)
login_manager.login_view = "login"

# set user session
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)


@DAEMON_BLUEPRINT.route('/', methods=['GET', 'POST'])
@login_required
def index():
    """main page/form for adding/viewing/removing entries from sys_map.csv"""
    pxe_form = MyForm()
    mac_remove_i = pxe_form.data['mac_remove']
    name_i = pxe_form.data['name']
    uname_i = pxe_form.data['uname']
    asset_i = pxe_form.data['asset']
    mac_i = pxe_form.data['mac']
    if pxe_form.validate_on_submit() and pxe_form.data['mac_remove']:
        remove_one(mac_remove_i)
    elif pxe_form.validate_on_submit() and name_i and uname_i and \
        asset_i and mac_i:
        add_to_list(name_i, uname_i, asset_i, mac_i)

    content = the_list()
    return render_template('index.html', form=pxe_form, contents=content)

@DAEMON_BLUEPRINT.route('/login', methods=['GET', 'POST'])
def login():
    """sets up and authenticates user"""
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.u.data).first()
        if user is None or not check_password_hash(user.password, form.p.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user)
        return redirect(url_for('index'))
    return render_template('login.html', form=form)


@DAEMON_BLUEPRINT.route("/logout")
@login_required
def logout():
    """logs the user out from the session and deletes cookie"""
    logout_user()
    return redirect(url_for('login'))

实施.py

import logging
import random
import time

from cmdlineutil.daemon import Daemon
from cmdlineutil.property_manager import PropertyManager, Property
from pxeadmin.daemon.dependencies import build_dependencies

LOG = logging.getLogger(__name__)


class PxeAdmin(Daemon):
    """Entry point for python daemon applications."""
    name = 'pxe-admin-app'

    def __init__(self):
        super(PxeAdmin, self).__init__(PxeAdmin.name)

        # bunch of stuff that's irrelevant

    def daemon_loop(self):
        """Implement the looping behaviour of our daemon here.

            This function will be called repeatedly until the daemon exits.

            The web process is run in a seperate thread so if you have no other
            behaviour than serving pages then you can just sleep a few seconds here.

            Leaving this completely blank is not recommended as it will be repeatedly
            called with no delay.
        """
        i = random.randint(0, 490)
        LOG.info('Pxe Admin is ALIVE. Here\'s a random number %s', str(i))
        time.sleep(10)

Tags: andthenamefrompyimportformapp