百度amis+fastapi构建后台管理系统(五)——后端登录页面

1,136 阅读2分钟

后台登录页面分为两个部分

  • 返回登录HTML
  • 处理登录逻辑

返回登录HTML页面

app/amis/utils.py工具页面,渲染模板

from string import Template


def amis_templates(template_path: str, encoding="utf8") -> Template:
    """页面模板"""
    with open(template_path, encoding=encoding) as f:
        return Template(f.read())

导航栏 app/amis/common/aside.py

aside = {
    "type": "nav",
    "stacked": "true",
    "expandIcon": {"type": "icon", "icon": "fas fa-building"},
    "links": [
        {"label": "主页", "to": "/html/index", "icon": "fa fa-th"},
    ],
}

工具栏 app/amis/common/toolbar.py

toolbar = {
    "type": "button",
    "label": "退出登录",
    "onClick": 'localStorage.removeItem("admins_token");',
    "actionType": "link",
    "link": "/html/login",
}

返回HTML

app/amis/html.py

from fastapi import APIRouter
from fastapi.responses import HTMLResponse
from app.amis.utils import amis_templates

# 导航栏/边栏
from app.amis.common.aside import aside

# 工具栏右侧用户名位置
from app.amis.common.toolbar import toolbar

SERVER_URL = "http://127.0.0.1:7899"

html_router = APIRouter()


@html_router.get("/login", name="登录")
async def login():
    template_path = "templates/login.html"
    return HTMLResponse(
        amis_templates(template_path).safe_substitute(
            {"serverUrl": SERVER_URL}
        )
    )


# 主页
@html_router.get("/index", name="主页")
def index_html():
    test_json = {
        "type": "page",
        "title": "后台系统",
        "body": "这里是系统主页",
        "toolbar": toolbar,
        "aside": aside,
    }
    template_path = "templates/page.html"
    return HTMLResponse(
        amis_templates(template_path).safe_substitute(
            {"site_title": "主页", "AmisSchemaJson": test_json}
        )
    )

处理登录逻辑

可以借鉴fastapi文档中的OAuth2 实现密码哈希与 Bearer JWT 令牌验证 - FastAPI (tiangolo.com)实现

这里我实现一个简单的

from fastapi.responses import JSONResponse

from fastapi import Depends, APIRouter, HTTPException
from fastapi.security import OAuth2PasswordRequestForm

from sqlalchemy.orm import Session

login_router = APIRouter()

@login_router.post("/login", name="用户登陆")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    if not form_data.username or not form_data.password:
        # 根据前端设定,会跳转到登录页
        raise HTTPException(status_code=400, detail="用户名或密码不能为空")  
    if form_data.username != "admin" and form_data.password != "password":
        raise HTTPException(status_code=406, detail="用户名或密码错误")
    res = {
        "status": 0, 
        "msg": "success", 
        "data": {
            "access_token": "xxxxxx", 
            "token_type"="bearer"
            }
        }
    return JSONResponse(res)

路由

需要HTML的路由和api的路由

app/api/apis.py

from fastapi import APIRouter
from app.amis.html import html_router

from app.api.login import login_router

api_router = APIRouter()

# html页面
api_router.include_router(html_router, prefix="/html", tags=["html"])
# api页面
api_router.include_router(login_router, prefix="/api", tags=["login"])

由此,后台系统基本部分已经完成