web框架--bottle

本文详细介绍了Web框架的概念以及Bottle框架的基本功能,包括路由、请求方法、静态文件处理、错误处理和模板使用。Bottle是一个轻量级的Python Web框架,它使得开发Web应用变得更加简单快捷。通过示例代码展示了如何使用Bottle进行动态路由、请求响应、错误处理以及模板渲染。此外,还解释了模板语法和其实现原理。

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

web框架

在了解的bottle的时候,我有一个疑问:web框架是什么? 为了解决什么问题使这种框架产生?
我首先整体了解了一下bottle的功能,再去网上查找了一些web框架的信息(web框架理解参考文章)。下边是我的理解:

  1. web框架启动后提供一个web服务
  2. web框架对web的各个过程进行了封装。我们知道http协议是一种请求-响应模型。在整个完成过程中,我们需要确定 methods,url(http://ip:port:/uri),header,body,response,response code等信息。这些都由web框架完成

bottle

bottle 是一个快速而简单的、由 Python 包装为一个单一文件的Web 框架.主要功能有:

  • 请求静态路由
  • 请求动态路由,路由中可包含参数,正则表达
  • 指定请求方法,默认为get
  • 路由静态文件
  • 错误页面
  • 自定义header
  • cookie的处理
  • 指定更改编码
  • 状态码的处理
  • 页面重定向
  • 下载文件
  • 使用模板定义输出页面

bottle的简单使用

示例

from bottle import route,run,post,get,request,static_file,error

@route('/he/:name')
def index(name = "world"):
    # return '<a href="/login">Go to Hello World Page</a>'
    return '<strong>hello {}!'.format(name)

# id是路径中的一个变量,这里表示其值可以是纯数字,一种正则形式
@route('/china/:id#[0-9]+#')
def hh(id):
    return 'object id {}'.format(id)
 
@route("/file/:filename")
def server_file(filename):
    return static_file(filename=filename,root='C:\Users\zhangaj\Desktop')

@route('/post_test', method='POST')
def post_test():
    data = request.body.read()
    logging.info(str(data,encoding='utf8'))
    return '接收成功,数据为:'+ str(data,encoding='utf8')

route
  • route() 以括号里的内容作为路径,将下边的函数和其绑定起来,即通过修饰器实现。路径可以有参数,正则表达式
  • 参数的形式:老版的格式 :name,新版格式<name>
  • 正则的使用:老版的格式:name#regexp#,新版本格式<name:re:regexp>
  • 若返回的有链接,会跳转到另一个页面 见前两个例子。
  • 第三个例子是一个加载静态文件的例子,使用函数static_file
  • 默认使用methodget,可指定。见例子4
    在这里插入图片描述
context= confluence_data.send_content()
@get("/")
def send():
    if context == 2:
        return "没有获取到页面内容,可能是月份页面不存在"
    elif context == 1:
        return "没有获取到页面内容,可能是标签不存在"
    else:
        return '''<form method = "POST">
                <input type="submit" value="发送" />
                </form>''' + context
@post("/")
def send_post():
    return Email.send_mail(context=context)


@get('/login')
def login_form():
    return '''<form method = "POST">
                <input name="name" type="text" />
                <input name="password" type="password" />
                <input type="submit" value="Login" />
                <input type="submit" value="Logout" />
                </form>'''
#@route('/login', method = 'POST')
@post('/login')
def login():
    name = request.forms.get('name')
    password = request.forms.get('password')
    if check_login(name, password):
        return '<p>Your login was correct</p>'
    else:
        return '<p>Login failed</p>'
        
@error(404)
def error404(error):
    return "nothing in there"
# if __name__ =="__main__":
run(host="localhost",port=1234,reloader=True)
  • 不同的请求也可以使用如@get(),@post()这样的方式,和使用route()指定method作用相同
  • 同一个路径可以绑定不同的方法,且一个函数可以绑定多个路径(这个没有举例)
  • error()解析错误,可修改错误返回值。即修改状态码
  • run()运行,启动一个web服务。输入ip和端口就可以在生成页面访问啦,参数reloader=True表示重载工具

模板的使用

示例:

from bottle import route,run,template

@route('/dps/slave/:entid#[0-9]+#')
def DpsPushConfigInfo(entid=None):
    keys = "getDpsPushConfigInfo:hset:getConfigHash:" + entid
    content = list()
    for field in cli.hkeys(keys):
        content.append([keys.split(':')[-1], field, cli.hget(name=keys, key=field)])
    data = {"data": content}
    return template('dps', data)

解析

  • 使用模板需引入包templateview,这里使用的是前者;
  • 调用方法:在函数结束的时候,调用即可。第一个参数模板文件的名字,其后是需要导入模板的参数(使用字典对)模板的路径为views/下

模板示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>dps</title>
</head>

<body>
<table border="1">
    <thead><th>节点</th><th>企业</th></thead>
%for slave,entid in data:
    <tr><td>{{slave}}</td><td>
         %for list_id in entid:
        <p><a href="/dps/slave/{{list_id}}">{{list_id}}</a></p>
        %end
    </td></tr>
    %end
 </table>
</body>
</html>

解析(模板的官网地址):

  • 语法符合html的语法;
  • 变量用{{}}表示起来,大括号内允许使用任何python表达式,只要它的计算结果为字符串或具有字符串表示形式的内容即可;
  • 一行python代码,用%表示
  • python代码块,用<% %>表示

参考链接:

官网地址:https://bottlepy.org/docs/dev/

buttle文章: https://blog.youkuaiyun.com/huithe/article/details/8087645

模板文章http://www.linuxyw.com/586.html

https://www.kancloud.cn/yubang/bottle/84217

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值