nimi_web框架初识

本文介绍了微型框架mini_web的基本使用方法,通过构建表格、处理数据、正则替换实现页面生成。讲解了添加、更新功能的实现细节,包括sql操作和条件判断。此外,还涉及了选项修改和中文支持的实现,提供了对mini_web框架的初步理解和实践心得。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近博主搬家,几天没更了,现在给大家分享一个很小型的框架mini_web,给大家讲述下里面的含义。

# 服务器给数据,返回数据给服务器
import re

from urllib.request import unquote  # 解码

# 定义空字典,用来存储路径跟对应的函数引用
from pymysql import connect

url_dict = dict()


# start_response用来框架给服务器传响应头的数据
# environ用来得到服务器传过来的文件路径
def application(environ, start_response):
    """返回具体展示的界面给服务器"""
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])  # 返回响应头

    # 根据不同的地址进行判断
    file_name = environ['file_name']

    for key, value in url_dict.items():
        match = re.match(key, file_name)  # 你的地址跟你的规则一致

        if match:
            # 匹配了
            return value(match)  # 调用匹配到的函数引用,返回匹配的页面内容

    else:
        # 说明没找到
        return "not page is find!"


# 这个装饰器传参,用来完成路由的功能
def route(url_address):  # url_address表示页面的路径
    """主要的目的自动添加路径跟匹配的函数到我们的url字典中"""

    def set_fun(func):
        def call_fun(*args, **kwargs):
            return func(*args, **kwargs)

        # 根据不同的函数名称去添加到字典中
        url_dict[url_address] = call_fun

        return call_fun

    return set_fun


#################################################上面是框架部分#############################################
#
# @route(r"/add/(\d+).html")   #这个地址,是一个正则的地址
# def index(match):  # match是正则匹配完的对象
# 	return "返回界面显示%s"%match.group(1)  # 返回网页的界面


# 显示首页
@route(r'/index.html')
def index(match):
    with open("./templates/index.html")as f:
        content_html = f.read()
    conn = connect(host='localhost', port=3306, password='mysql', user='root', charset='utf8',
                   database='stock_db')  # 网页一行的字符串
    cs1 = conn.cursor()
    sql = """select * from info;"""
    cs1.execute(sql)
    table_data = cs1.fetchall()
    cs1.close()
    conn.close()
    row_str = """<tr>
        <td>%s<td>
        <td>%s<td>
        <td>%s<td>
        <td>%s<td>
        <td>%s<td>
        <td>%s<td>
        <td>%s<td>
        <td>%s<td>
        <td>
            <input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="%s">
        </td>
        </tr>  """
    table_str = ""  # 表格字符串
    # 数据库有多少行就打印多少行
    for temp in table_data:
        table_str += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[1])
    # 替换一行的数据
    content_html = re.sub(r'\{%content%\}', table_str, content_html)
    return content_html


@route(r'/center.html')
def center(match):
    # 拿到网页内容
    # 拿到数据库内容
    # 拼接网页跟数据库内容
    # 展示拼接后的内容

    # 拿到网页内容
    with open('./templates/center.html') as f:
        content_html = f.read()
    conn = connect(host='localhost', port=3306, password='mysql', user='root', charset='utf8',
                   database='stock_db')  # 网页一行的字符串
    cs1 = conn.cursor()
    sql = """select  info.code,info.short,info.chg,info.turnover,info.price,info.highs,focus.note_info from info inner join focus on info.id =focus.info_id;"""
    cs1.execute(sql)
    table_data = cs1.fetchall()
    cs1.close()
    conn.close()
    row_str = """<tr>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>
                <a type="button" class="btn btn-default btn-xs" href="/update/%s.html"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
            </td>
            <td>
                <input type="button" value="删除" id="toDel" name="toDel" systemidvaule="%s">
            </td>
        </tr>"""
    table_str = ""
    for temp in table_data:
        table_str += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[0], temp[0])
        # 替换原来个人中心的界面
    content_html = re.sub(r'\{%content%\}', table_str, content_html)

    return content_html


@route(r'/add/(\d+).html')
def add(match):
    code = match.group(1)
    conn = connect(host='localhost', port=3306, password='mysql', user='root', charset='utf8',
                   database='stock_db')  # 网页一行的字符串
    cs1 = conn.cursor()
    sql = """select * from focus where info_id = (select id from info where code = %s)"""

    cs1.execute(sql, (code,))
    # youshuju
    if cs1.fetchone():
        cs1.close()
        conn.close()
        return '亲,数据已存在'
    else:
        sql = """insert into focus (info_id) (select id from info where code = %s);"""
        cs1.execute(sql, (code,))
        conn.commit()
        cs1.close()
        conn.close()
        return '添加成功'


@route(r'/del/(\d+).html')
def del_info(match):
    code = match.group(1)
    conn = connect(host='localhost', port=3306, password='mysql', user='root', charset='utf8',
                   database='stock_db')  # 网页一行的字符串
    cs1 = conn.cursor()
    sql = """delete from  focus where info_id = (select id from info where code = %s);"""
    cs1.execute(sql, (code,))
    conn.commit()
    cs1.close()
    conn.close()
    return '删除成功'


@route(r'/update/(\d+).html')
def update(match):
    with open('./templates/update.html')as f:
        content_html = f.read()
        # 替换我们的code
    code = match.group(1)
    content_html = re.sub(r'\{%code%\}', code, content_html)

    conn = connect(host='localhost', port=3306, password='mysql', user='root', charset='utf8',
                   database='stock_db')  # 网页一行的字符串
    cs1 = conn.cursor()
    sql = """select note_info from focus where info_id = (select id from info where code = %s)"""

    cs1.execute(sql, (code,))
    table_data = cs1.fetchall()
    # 备注信息
    note_info = table_data[0][0]
    cs1.close()
    conn.close()
    # 替换我们备注信息
    content_html = re.sub(r'\{%note_info\}', note_info, content_html)
    return content_html
@route(r'/update/(\d+)/(.*).html')
def update_info(match):
    code = match.group(1)
    content = unquote(match.group(2))
    conn = connect(host='localhost',port =3306,password='mysql',user='root',charset='utf8',database= 'stock_db')
    cs1 = conn.cursor()
    sql ="""update focus set note_info =%s where info_id = (select id from info where code = %s);"""
    cs1.execute(sql,(content,code))
    conn.commit()
    cs1.close()
    conn.close()
    return '更新成功'
思路其实不难,先分析index功能,index功能主要做的是把网站的首页呈现给大家,主要通过装饰器传参来完成一个路由功能,打开相应的文件路径,拿到网页的内容,再连接数据库执行sql语句,拿到数据库的内容,关闭数据库。然后运用谷歌游览器将网页上显示那一行具体信息的内容的前端代码复制下来,然后ctrl+r轻松替换为'%s'格式,
table_str = ""
	for temp in table_data:
		table_str += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[0], temp[0])

	# 替换原来的个人中心的界面
	content_html = re.sub(r'\{%content%\}', table_str, content_html)

	

这几句代码很关键,先写table_str=""表格字符串,然后昔日table_str += row_str 去接收表格的数据,然后for temp in table_data:数据库有多少数据就显示多少行,然后通过temp[]去把一行的一个字段提取出来,一共是9个数据,这样就是一行,然后table_str += row_str就是一页,之后把前端给我们的{content}通过正则的sub功能替换成table_str,这样一个页面就做好了。然后就是添加功能,

@route(r'/add/(\d+).html')
def add(match):
    code = match.group(1)
    conn = connect(host='localhost', port=3306, password='mysql', user='root', charset='utf8',
                   database='stock_db')  # 网页一行的字符串
    cs1 = conn.cursor()
    sql = """select * from focus where info_id = (select id from info where code = %s)"""

    cs1.execute(sql, (code,))
    # youshuju
    if cs1.fetchone():
        cs1.close()
        conn.close()
        return '亲,数据已存在'
    else:
        sql = """insert into focus (info_id) (select id from info where code = %s);"""
        cs1.execute(sql, (code,))
        conn.commit()
        cs1.close()
        conn.close()
        return '添加成功'

先通过正则获取到网页那对应行的编码,然后执行sql语句的子查询,记得把%s替换成正则获取到的编码,因为添加会有重复,所以用条件判断一下再执行sql的批量插入语句。之后是更新,先将修改界面读取出来,再将前端的{%code%}替换成我们自己的code,再根据code去替换我们的备注,note_info = table_data[0][0]这句话就是把备注信息拿出来,将{%note_info\}替换掉。

这个时候我们已经做完了更新界面的选项按钮的修改,接下来要再用一个函数去完成对应的选项内容的修改。先用group(1)去获取选项,再用group(2)去获取选项的内容,然后用sql语句将内容写入对应的选项。最后再在开头导入一个支持中文的模块,让他也支持中文输入。这样一个mini_web框架,就完成了。以上就是我对这个小框架的小小见解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值