一、简单的Bottle框架

1)bottle框架简介

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

bottle简介

2)bottle框架的组成部分

、路由系统,将不同请求交由指定函数处理
、模板系统,将模板中的特殊语法渲染成字符串,值得一说的是Bottle的模板引擎可以任意指定:Bottle内置模板、mako、jinja2、cheetah
、公共组件,用于提供处理请求相关的信息,如:表单数据、cookies、请求头等
、服务,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- -*- from bottle import template,Bottle root = Bottle() @root.route('/hello')
def index():
# return "Hello World"
return template('<b>Hello {{ name }}</b>!',name="user") root.run(host='localhost',port=)

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- -*-
from bottle import template, Bottle
from bottle import static_file
root = Bottle() @root.route('/hello/')
def index():
return template('<b>Root {{name}}</b>!', name="Alex") from framwork_bottle import app01
from framwork_bottle import app02 root.mount('app01', app01.app01)
root.mount('app02', app02.app02) root.run(host='localhost', port=)

总路由编辑

二级路由编辑

#!/usr/bin/env python
# -*- coding:utf- -*-
from bottle import template, Bottle app01 = Bottle() @app01.route('/hello/', method='GET')
def index():
return template('<b>App01</b>!')

二级路由

三、模板系统

1)配置模板使用路径

import bottle
bottle.TEMPLATE_PATH.append('./templates/')

2)模板语言的常用方法

2.1)前后端结合

路由传值给前端模板

@root.route('/index/',method="GET")
def index():
user_list = [
{'id':,'name':'root','age':},
{'id':,'name':'root','age':},
{'id':,'name':'root','age':},
{'id':,'name':'root','age':},
]
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','')}}</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)常用方法归纳

、单值
、单行Python代码
、Python代码快
、Python、Html混合

示例

<h1>、单值</h1>
{{name}} <h1>、单行Python代码</h1>
% s1 = "hello" <h1>、Python代码块</h1>
<%
# A block of python code
name = name.title().strip()
if name == "Alex":
name="seven"
%> <h1>、Python、Html混合</h1> % if True:
<span>{{name}}</span>
% end
<ul>
% for item in name:
<li>{{item}}</li>
% end
</ul>

html模板语音归纳

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

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

默认值

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

#!/usr/bin/env python
# -*- coding:utf- -*-
from bottle import template, Bottle,SimpleTemplate
root = Bottle() def custom():
return '' @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=)

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

五、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- -*-
from bottle import Bottle
root = Bottle() @root.route('/hello/')
def index():
return "Hello World"
# 默认server ='wsgiref',性能最差,测试专用
root.run(host='localhost', port=, server='wsgiref')

main.py

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

六、数据库操作

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

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

python之Bottle框架的更多相关文章

  1. 关于python的bottle框架跨域请求报错问题的处理

    在用python的bottle框架开发时,前端使用ajax跨域访问时,js代码老是进入不了success,而是进入了error,而返回的状态却是200.url直接在浏览器访问也是正常的,浏览器按F12 ...

  2. Python的Bottle框架中实现最基本的get和post的方法的教程

    这篇文章主要介绍了Python的Bottle框架中实现最基本的get和post的方法的教程,Bottle框架在Python开发者中的人气很高,需要的朋友可以参考下 1.GET方式: # -*- cod ...

  3. Python之Bottle框架使用

    本文主要包含的内容是Bottle框架介绍和安装使用. 一.Bottle框架介绍 Bottle是一个快速小巧,轻量级的 WSGI 微型 web 框架.同时Bottle也是一个简单高效的遵循WSGI的微型 ...

  4. 让python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE等请求

    这两天在用python的bottle框架开发后台管理系统,接口约定使用RESTful风格请求,前端使用jquery ajax与接口进行交互,使用POST与GET请求时都正常,而Request Meth ...

  5. python bottle框架

    python bottle框架 简介: Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. Bottl ...

  6. Python开发者须知 —— Bottle框架常见的几个坑

    Bottle是一个小巧实用的python框架,整个框架只有一个几十K的文件,但却包含了路径映射.模板.简单的数据库访问等web框架组件,而且语法简单,部署方便,很受python开发者的青睐.Pytho ...

  7. Python自动化运维之29、Bottle框架

    Bottle 官网:http://bottlepy.org/docs/dev/index.html Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除 ...

  8. python bottle框架(WEB开发、运维开发)教程

    教程目录 一:python基础(略,基础还是自己看书学吧) 二:bottle基础 python bottle web框架简介 python bottle 框架环境安装 python bottle 框架 ...

  9. python 实现web框架simfish

    python 实现web框架simfish 本文主要记录本人利用python实现web框架simfish的过程.源码github地址:simfish WSGI HTTP Server wsgi模块提供 ...

随机推荐

  1. postman发送json请求

    简介: postman是一个很好的http模拟器,在测试rest服务时是很好用的工具,可以发送get.post.put等各种请求. 发送json的具体步骤: 1.选择post请求方式,同时将heade ...

  2. jenkin、SVN、archery集成openLDAP

    jenkins: 1.下载.安装插件 LDAP .Matrix Authorization Strategy 2. 系统管理 —> 全局安全配置 点击 启用安全,并且选择 LDAP 认证,这里有 ...

  3. 【转】收集 jetty、tomcat、jboss、weblogic 的比较

    jetty Jetty 是一个开源的servlet容器,它为基于Java的web容器,例如JSP和servlet提供运行环境.Jetty是使用Java语言编写的,它的API以一组JAR包的形式发布.开 ...

  4. Unity之Application.runInBackground = true

    默认是False, 设置 Application.runInBackground = true; 则 void OnApplicationPause(bool pause) 不再起作用

  5. java bean validation 参数验证

    一.前言 二.几种解决方案 三.使用bean validation 自带的注解验证 四.自定义bean validation 注解验证 一.前言 在后台开发过程中,对参数的校验成为开发环境不可缺少的一 ...

  6. layui禁用侧边导航栏点击事件

    layui是一款优秀的前端模块化css框架,作者是贤心 —— 国内的一位前端大佬. 我用layui做过两个完整的项目,对她的感觉就是,这货非常适合做后台管理界面,且基于jquery,很容易上手.当然, ...

  7. (转)css选择器及其优先级

    文章主要介绍什么是CSS选择器,CSS选择器的分类以及CSS选择器的优先级三部分内容,希望能够帮助到正在学习CSS的童鞋,有什么不足的地方欢迎大家批评指正. 一.什么是CSS选择器? CSS选择器又被 ...

  8. 使用SqlBulkCopy批量插入数据,测试20万条用时5秒

    using System;using System.Collections.Generic;using System.Linq;using System.Text; using System.Data ...

  9. Django xadmin 根据登录用户过滤数据

    在adminx.py文件对应的的class中添加如下代码: def queryset(self): qs = super(taskAdmin, self).queryset() if self.req ...

  10. how2j网站前端项目——天猫前端(第一次)学习笔记5

    收拾好心情,现在开始学习第5个页面——购物车页面! 一.结算按钮 这个还是比较简单的,我自己看着站长的样子模仿了一个: 有个地方不会做,就是全选前面的复选框,站长的框里面是白色的,我搞不来. 二.订单 ...