连接数据库

概述

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

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

插件初始化方法

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

示例

以mysql-connector连接mysql为例:

requirements.txt

sqlalchemy
mysql-connector

controller.py

from lessweb.plugin.dbplugin import DbServ

def book_detail(serv: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.dbplugin import DbPlugin
from controller import book_detail

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

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