连接数据库

概述

lessweb内置databaseplugin插件,可使用sqlalchemy管理和操作数据库。

注意:lessweb默认没有依赖sqlalchemy,需要自己手动安装。

插件初始化方法

class DatabasePlugin:
    def __init__(self, uri, echo=True, autoflush=True, autocommit=False, patterns=('.*',)):
      ...

示例

以mysql-connector连接mysql为例:

requirements.txt

sqlalchemy
mysql-connector

controller.py

from lessweb import Service
from lessweb.plugin.databaseplugin import DbServ

def book_detail(serv:Service[DbServ], id:int):
    ret = serv().db.execute('SELECT * FROM TblBook WHERE id=:id', {'id': id}).first()
    return str(ret)

index.py

from lessweb import Application
from lessweb.plugin.databaseplugin import DatabasePlugin
from controller import book_detail

database_plugin = DatabasePlugin('mysql+mysqlconnector://root:pwd@localhost:3306/proj')

app = Application()
app.add_plugin(database_plugin)
app.add_get_mapping('/book/{id}', book_detail)
app.run()