I create app.py and auth_module.app to make a login panel example. When I run the server, the login page can display on main of template. Error user or password, system can mesage a error as app. When I input correct user and password, and click the 登录 button, the system remains and cannot display correct main content and still login page.
import panel as pn
# 初始化 Panel 扩展
pn.extension()
# 登录页面
def login_page():
username_input = pn.widgets.TextInput(name="用户名")
password_input = pn.widgets.PasswordInput(name="密码")
login_button = pn.widgets.Button(name="登录", button_type="primary")
login_message = pn.pane.Markdown("")
def login(event):
from auth_module import AuthModule
if AuthModule.authenticate(username_input.value, password_input.value):
pn.state.cookies["user"] = username_input.value # 设置 cookie
# pn.state.location.reload() # 刷新页面
print("这是设置了用户的cookies了,下面修改main的内容")
pn.state.location.href = "/app" # 重新加载主页面
# template.main.append(
# pn.pane.Markdown("##Welcome #you are a good man strong man")
# )
else:
login_message.object = "无效的用户名或密码,请重试。"
login_button.on_click(login)
return pn.Column(
pn.pane.Markdown("## 登录"),
username_input,
password_input,
login_button,
login_message,
)
# 主功能区
def main_page():
from auth_module import AuthModule
user = AuthModule.get_user(pn.state)
if user:
return pn.pane.Markdown(f"# 欢迎回来,{user}!")
else:
return login_page()
# FastListTemplate 模板
template = pn.template.FastListTemplate(
title="医院绩效管理系统",
main=[main_page()],
)
# 启动服务
template.servable()
auth_module.py
import panel as pn
# 模拟用户数据库
USER_DB = {"admin": "password123", "user1": "mypassword"}
class AuthModule:
login_url = "/login" # 定义登录页面的 URL
# 认证逻辑:检查用户名和密码
@staticmethod
def authenticate(username, password):
return USER_DB.get(username) == password
# Panel 要求的 get_user 方法
@staticmethod
def get_user(request):
# 如果用户已登录,返回用户名
return request.cookies.get("user", None)
# 获取登录页面 URL 的方法(可选实现)
@staticmethod
def get_login_url(request):
return AuthModule.login_url
# 登录处理逻辑
@staticmethod
def login_handler(request):
username = request.body.get("username")
password = request.body.get("password")
if AuthModule.authenticate(username, password):
# 登录成功,设置 cookie
response = pn.state.create_response()
response.cookies["user"] = username
response.write("Login successful")
return response
else:
# 登录失败
response = pn.state.create_response()
response.status_code = 401
response.write("Invalid username or password")
return response