python之Bottle框架,,一、简单的Bottl


一、简单的Bottle框架

1)bottle框架简介

技术分享图片
安装 pip install bottleBottle是一个快速、简洁、轻量级的基于WSIG的微型Web框架。此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块。
bottle简介

2)bottle框架的组成部分

技术分享图片
1、路由系统,将不同请求交由指定函数处理2、模板系统,将模板中的特殊语法渲染成字符串,值得一说的是Bottle的模板引擎可以任意指定:Bottle内置模板、mako、jinja2、cheetah3、公共组件,用于提供处理请求相关的信息,如:表单数据、cookies、请求头等4、服务,Bottle默认支持多种基于WSGI的服务
bottle框架的组成部分

Bottle默认支持多种基于WSGI的服务

技术分享图片
server_names = {    ‘cgi‘: CGIServer,    ‘flup‘: FlupFCGIServer,    ‘wsgiref‘: WSGIRefServer,    ‘waitress‘: WaitressServer,    ‘cherrypy‘: CherryPyServer,    ‘paste‘: PasteServer,    ‘fapws3‘: FapwsServer,    ‘tornado‘: TornadoServer,    ‘gae‘: AppEngineServer,    ‘twisted‘: TwistedServer,    ‘diesel‘: DieselServer,    ‘meinheld‘: MeinheldServer,    ‘gunicorn‘: GunicornServer,    ‘eventlet‘: EventletServer,    ‘gevent‘: GeventServer,    ‘geventSocketIO‘:GeventSocketIOServer,    ‘rocket‘: RocketServer,    ‘bjoern‘ : BjoernServer,    ‘auto‘: AutoServer,}
WSGI的服务

3)框架的基本使用

技术分享图片
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import template,Bottleroot = Bottle()@root.route(‘/hello‘)def index():    # return "Hello World"    return template(‘<b>Hello {{ name }}</b>!‘,name="user")root.run(host=‘localhost‘,port=8080)
bottle简单使用

访问: http://localhost:8080/hello

4)对于form表单提前,python后端取值

技术分享图片
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>login</title></head><body>    <h1>Bottle登录系统</h1>    <form action="/login/" method="POST">        <input type="text" name="user" placeholder="用户名"/>        <input type="password" name="pwd" placeholder="密码"/>        <input type="submit" value="提交"/>    </form></body></html>
login.html技术分享图片
@root.route(‘/login/‘,method=["POST","GET"])def login():    if request.method == "GET":        return template(‘login.html‘)    else:        u = request.forms.get(‘user‘)        p = request.forms.get(‘pwd‘)        return redirect(‘/index/‘)
request.forms.get()取值

二 、路由系统

1)静态路由

技术分享图片
@root.route(‘/hello/‘)def index():    return template(‘<b>Hello {{name}}</b>!‘, name="User")
静态路由

2)动态路由

技术分享图片
@root.route(‘/wiki/<pagename>‘)def callback(pagename):    ... @root.route(‘/object/<id:int>‘)def callback(id):    ... @root.route(‘/show/<name:re:[a-z]+>‘)def callback(name):    ... @root.route(‘/static/<path:path>‘)def callback(path):    return static_file(path, root=‘static‘)
动态路由

3)请求方法路由

技术分享图片
@root.route(‘/hello/‘, method=‘POST‘)def index():    ... @root.get(‘/hello/‘)def index():    ... @root.post(‘/hello/‘)def index():    ... @root.put(‘/hello/‘)def index():    ... @root.delete(‘/hello/‘)def index():    ...    # 第一种,写在一起@root.route(‘/login/‘,method=["POST","GET"])def login():    if request.method == "GET":        return template(‘login.html‘)    else:        return redirect(‘/index/‘)        # 第二种,分开写@root.route(‘/login/‘,method="POST")def index():    return template(‘login.html‘)@root.route(‘/login/‘,method="GET")def index():    return template(‘login.html‘)
请求方法路由

4)二级路由,路由分发

主路由编辑

技术分享图片
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import template, Bottlefrom bottle import static_fileroot = Bottle() @root.route(‘/hello/‘)def index():    return template(‘<b>Root {{name}}</b>!‘, name="Alex") from framwork_bottle import app01from framwork_bottle import app02 root.mount(‘app01‘, app01.app01)root.mount(‘app02‘, app02.app02) root.run(host=‘localhost‘, port=8080)
总路由编辑

二级路由编辑

技术分享图片
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import template, Bottleapp01 = Bottle()@app01.route(‘/hello/‘, method=‘GET‘)def index():    return template(‘<b>App01</b>!‘)
二级路由

三、模板系统

1)配置模板使用路径

import bottlebottle.TEMPLATE_PATH.append(‘./templates/‘)

2)模板语言的常用方法

2.1)前后端结合

路由传值给前端模板

技术分享图片
@root.route(‘/index/‘,method="GET")def index():    user_list = [        {‘id‘:1,‘name‘:‘root‘,‘age‘:18},        {‘id‘:1,‘name‘:‘root‘,‘age‘:18},        {‘id‘:1,‘name‘:‘root‘,‘age‘:18},        {‘id‘:1,‘name‘:‘root‘,‘age‘:18},    ]    return template(‘index.html‘,name=‘superbody‘,user_list=user_list)
python后端传值

前端调用值

技术分享图片
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>index</title></head><body><ul>    <!--for循环-->    {{name}}    % for item in user_list:    <li>{{item[‘id‘]}}-{{item[‘name‘]}}</li>    % end    <!--自定义常量-->    % laogao = "guaizi"    {{laogao}}</ul><!--有值就取,没值就默认--><div>{{get(‘age‘,‘123‘)}}</div></body></html>
index.html

2.2)include 引用文件的标签

技术分享图片
<h1>{{title}}</h1>
被引用的文件,tpl.html技术分享图片
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <!--引用文件,赋值-->    % include(‘tpl.html‘,title=‘搞事情‘)</body></html>
index.html调用tpl.html

2.3)rebase引用文件的标签

技术分享图片
<html><head>  <title>{{title or ‘No title‘}}</title></head><body>  {{!base}}</body></html>
base.html

导入基础模板

% rebase(‘base.tpl‘, title=‘Page Title‘)<p>Page Content ...</p>

2.4)常用方法归纳

1、单值2、单行Python代码3、Python代码快4、Python、Html混合

示例

技术分享图片
<h1>1、单值</h1>{{name}} <h1>2、单行Python代码</h1>% s1 = "hello"  <h1>3、Python代码块</h1><%    # A block of python code    name = name.title().strip()    if name == "Alex":        name="seven"%>  <h1>4、Python、Html混合</h1> % if True:    <span>{{name}}</span>% end<ul>  % for item in name:    <li>{{item}}</li>  % end</ul>
html模板语音归纳

2.5)如果没有该值的情况下的默认值设置

技术分享图片
# 检查当前变量是否已经被定义,已定义True,未定义Falsedefined(name)# 获取某个变量的值,不存在时可设置默认值get(name, default=None)<div>{{get(‘age‘,‘123‘)}}</div># 如果变量不存在时,为变量设置默认值setdefault(name, default)
默认值

2.6){{ wupeiqi() }} 。定义函数,python后端定义函数,html前端调用函数执行

技术分享图片
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import template, Bottle,SimpleTemplateroot = Bottle()def custom():    return ‘123123‘@root.route(‘/hello/‘)def index():    # 默认情况下去目录:[‘./‘, ‘./views/‘]中寻找模板文件 hello_template.html    # 配置在 bottle.TEMPLATE_PATH 中    return template(‘hello_template.html‘, name=‘alex‘, wupeiqi=custom)root.run(host=‘localhost‘, port=8080)
main.py技术分享图片
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title></head><body>    <h1>自定义函数</h1>    {{ wupeiqi() }}</body></html>
hello_template.html

2.6.1){{ !wupeiqi() }}。渲染引用的html标签

被调用的python函数

def custom():    return ‘<h1>hello world</h1>‘

前端使用

<body>    <h1>自定义函数</h1>    {{ !wupeiqi() }}</body>

2.7)替换模板。

技术分享图片
from  bottle import jinja2_template@root.route(‘/login/‘,method=["POST","GET"])def login():    return jinja2_template(‘login.html‘)
替换模板

jinja2_template模板与django模板使用一样

四、公共组件

1)request:Bottle中的request其实是一个LocalReqeust对象,其中封装了用户请求的相关信息

技术分享图片
request.headers    请求头信息 request.query    get请求信息 request.forms    post请求信息 request.files    上传文件信息 request.params    get和post请求信息 request.GET    get请求信息 request.POST    post和上传信息 request.cookies    cookie信息     request.environ    环境相关相关
请求信息

2)response:Bottle中的request其实是一个LocalResponse对象,其中框架即将返回给用户的相关信息

技术分享图片
response    response.status_line        状态行     response.status_code        状态码     response.headers        响应头     response.charset        编码     response.set_cookie        在浏览器上设置cookie             response.delete_cookie        在浏览器上删除cookie
View Code

五、Bottle支持的WSGI

技术分享图片
server_names = {    ‘cgi‘: CGIServer,    ‘flup‘: FlupFCGIServer,    ‘wsgiref‘: WSGIRefServer,    ‘waitress‘: WaitressServer,    ‘cherrypy‘: CherryPyServer,    ‘paste‘: PasteServer,    ‘fapws3‘: FapwsServer,    ‘tornado‘: TornadoServer,    ‘gae‘: AppEngineServer,    ‘twisted‘: TwistedServer,    ‘diesel‘: DieselServer,    ‘meinheld‘: MeinheldServer,    ‘gunicorn‘: GunicornServer,    ‘eventlet‘: EventletServer,    ‘gevent‘: GeventServer,    ‘geventSocketIO‘:GeventSocketIOServer,    ‘rocket‘: RocketServer,    ‘bjoern‘ : BjoernServer,    ‘auto‘: AutoServer,}
wsgi服务

使用时,只需在主app执行run方法时指定参数即可:

技术分享图片
#!/usr/bin/env python# -*- coding:utf-8 -*-from bottle import Bottleroot = Bottle() @root.route(‘/hello/‘)def index():    return "Hello World"# 默认server =‘wsgiref‘,性能最差,测试专用root.run(host=‘localhost‘, port=8080, server=‘wsgiref‘)
main.py

使用Python内置模块wsgiref,如果想要使用其他时,则需要首先安装相关类库,然后才能使用

六、数据库操作

可手写orm框架,或者pymysql使用

原文出处:https://www.cnblogs.com/wupeiqi/articles/5341480.html

python之Bottle框架

评论关闭