【Python之路】特别篇--Bottle
Bottle
Bottle是一个快速、简洁、轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块。
Bottle框架大致可以分为以下部分:
路由系统,将不同请求交由指定函数处理
模板系统,将模板中的特殊语法渲染成字符串,值得一说的是Bottle的模板引擎可以任意指定:Bottle内置模板、mako、jinja2、cheetah
公共组件,用于提供处理请求相关的信息,如:表单数据、cookies、请求头等
服务,Bottle默认支持多种基于WSGI的服务
框架的基本使用:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
root = Bottle() @root.route('/hello/')
def index():
return "Hello World"
# return template('<b>Hello {{name}}</b>!', name="Alex") root.run(host='localhost', port=8080)
一、路由系统
路由系统是的url对应指定函数,当用户请求某个url时,就由指定函数处理当前请求,对于Bottle的路由系统可以分为一下几类:
静态路由
动态路由
请求方法路由
二级路由
1.静态路由
@root.route('/hello/')
def index():
return template('<b>Hello {{name}}</b>!', name="Alex")
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():
...
4.二级路由
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle app01 = Bottle() @app01.route('/hello/', method='GET')
def index():
return template('<b>App01</b>!')
app01.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle app02 = Bottle() @app02.route('/hello/', method='GET')
def index():
return template('<b>App02</b>!')
app02.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
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=8080)
二、模板系统
模板系统用于将Html和自定的值两者进行渲染,从而得到字符串,然后将该字符串返回给客户端。
我们知道在Bottle中可以使用 内置模板系统、mako、jinja2、cheetah等,以内置模板系统为例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>{{name}}</h1>
</body>
</html>
html文件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
root = Bottle() @root.route('/hello/')
def index():
# 默认情况下去目录:['./', './views/']中寻找模板文件 hello_template.html
# 配置在 bottle.TEMPLATE_PATH 中
return template('xx.html', name='alex') root.run(host='localhost', port=8080)
1、语法
单值
单行Python代码
Python代码快
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>
2、函数
include(sub_template, **variables)
# 导入其他模板文件
% include('header.tpl', title='Page Title')
Page Content
% include('footer.tpl')
rebase(name, **variables)
<html>
<head>
<title>{{title or 'No title'}}</title>
</head>
<body>
{{!base}}
</body>
</html>
base.html
# 导入母版
% rebase('base.html', title='Page Title')
<p>Page Content ...</p>
defined(name)
# 检查当前变量是否已经被定义,已定义True,未定义False
get(name, default=None)
# 获取某个变量的值,不存在时可设置默认值
setdefault(name, default)
# 如果变量不存在时,为变量设置默认值
扩展:自定义函数
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>自定义函数</h1>
{{ hello() }} </body>
</html>
hello.html
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', hello=custom) root.run(host='localhost', port=8080)
main.py
注:变量或函数前添加 【 ! 】,则会关闭转义的功能
三、公共组件
由于Web框架就是用来【接收用户请求】-> 【处理用户请求】-> 【响应相关内容】,对于具体如何处理用户请求,开发人员根据用户请求来进行处理,而对于接收用户请求和相应相关的内容均交给框架本身来处理,其处理完成之后将产出交给开发人员和用户。
【接收用户请求】
当框架接收到用户请求之后,将请求信息封装在Bottle的request中,以供开发人员使用
【响应相关内容】
当开发人员的代码处理完用户请求之后,会将其执行内容相应给用户,相应的内容会封装在Bottle的response中,然后再由框架将内容返回给用户
所以,公共组件本质其实就是为开发人员提供接口,使其能够获取用户信息并配置响应内容。
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中的response其实是一个LocalResponse对象,其中框架即将返回给用户的相关信息:
response
response.status_line
状态行 response.status_code
状态码 response.headers
响应头 response.charset
编码 response.set_cookie
在浏览器上设置cookie response.delete_cookie
在浏览器上删除cookie
实例:
from bottle import route, request
@route('/login')
def login():
return '''
<form action="/login" method="post">
Username: <input name="username" type="text" />
Password: <input name="password" type="password" />
<input value="Login" type="submit" />
</form>
'''
@route('/login', method='POST')
def do_login():
username = request.forms.get('username')
password = request.forms.get('password')
if check_login(username, password):
return "<p>Your login information was correct.</p>"
else:
return "<p>Login failed.</p>"
基本Form请求
<form action="/upload" method="post" enctype="multipart/form-data">
Category: <input type="text" name="category" />
Select a file: <input type="file" name="upload" />
<input type="submit" value="Start upload" />
</form> @route('/upload', method='POST')
def do_upload():
category = request.forms.get('category')
upload = request.files.get('upload')
name, ext = os.path.splitext(upload.filename)
if ext not in ('.png','.jpg','.jpeg'):
return 'File extension not allowed.' save_path = get_save_path_for_category(category)
upload.save(save_path) # appends upload.filename automatically
return 'OK'
上传文件
四、服务
对于Bottle框架其本身未实现类似于Tornado自己基于socket实现Web服务,所以必须依赖WSGI,默认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 Bottle
root = Bottle() @root.route('/hello/')
def index():
return "Hello World"
# 默认server ='wsgiref'
root.run(host='localhost', port=8080, server='wsgiref')
默认server="wsgiref",即:使用Python内置模块wsgiref,如果想要使用其他时,则需要首先安装相关类库,然后才能使用。如:
# 如果使用Tornado的服务,则需要首先安装tornado才能使用 class TornadoServer(ServerAdapter):
""" The super hyped asynchronous server by facebook. Untested. """
def run(self, handler): # pragma: no cover
# 导入Tornado相关模块
import tornado.wsgi, tornado.httpserver, tornado.ioloop
container = tornado.wsgi.WSGIContainer(handler)
server = tornado.httpserver.HTTPServer(container)
server.listen(port=self.port,address=self.host)
tornado.ioloop.IOLoop.instance().start()
PS:以上WSGI中提供了19种,如果想要使期支持其他服务,则需要扩展Bottle源码来自定义一个ServerAdapter
更多参见:http://www.bottlepy.org/docs/dev/index.html
【Python之路】特别篇--Bottle的更多相关文章
- python之路入门篇
一. Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,Guido开始写能够解释Python语言语法的解释器.Python这个名字,来 ...
- python之路基础篇
基础篇 1.Python基础之初识python 2.Python数据类型之字符串 3.Python数据类型之列表 4.Python数据类型之元祖 5.Python数据类型之字典 6.Python Se ...
- python之路——基础篇(2)模块
模块:os.sys.time.logging.json/pickle.hashlib.random.re 模块分为三种: 自定义模块 第三方模块 内置模块 自定义模块 1.定义模块 将一系列功能函数或 ...
- python之路第一篇
一.python环境的搭建 1.window下环境的搭建 (1).在 https://www.python.org/downloads/ 下载自己系统所需要的python版本 (2).安装python ...
- python之路第二篇(基础篇)
入门知识: 一.关于作用域: 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. if 10 == 10: name = 'allen' print name 以下结论对吗? ...
- Python之路(第九篇)Python文件操作
一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r",encoding = “utf ...
- Python之路(第二篇):Python基本数据类型字符串(一)
一.基础 1.编码 UTF-8:中文占3个字节 GBK:中文占2个字节 Unicode.UTF-8.GBK三者关系 ascii码是只能表示英文字符,用8个字节表示英文,unicode是统一码,世界通用 ...
- Python之路(第一篇):Python简介和基础
一.开发简介 1.开发: 开发语言: 高级语言:python.JAVA.PHP.C#..ruby.Go-->字节码 低级语言: ...
- Python之路(第四十一篇)线程概念、线程背景、线程特点、threading模块、开启线程的方式
一.线程 之前我们已经了解了操作系统中进程的概念,程序并不能单独运行,只有将程序装载到内存中,系统为它分配资源才能运行,而这种执行的程序就称之为进程.程序和进程的区别就在于:程序是指令的集合,它是 ...
随机推荐
- 在使用selenium时出现FileNotFoundError: [WinError 2] 系统找不到指定的文件。
今天在使用selenium出现这样的错: Traceback (most recent call last): File "E:\python\lib\site-packages\selen ...
- 屹今为止最好用的HTTP客户端命令行工具-接口调试神器HTTPie
一.思考❓❔ 1.你用过哪些http客户端调试工具? Postman 不够灵活 需要打开客户端, 麻烦 学习成本高 Jmeter 臃肿 麻烦 学习成本高 curl 参数多, 记不住 不够灵活 主要在L ...
- MySQL中的DML、DQL和子查询
一.MySQL中的DML语句 1.使用insert插入数据记录: INSERT INTO `myschool`.`student` (`studentNo`, `loginPwd`, `student ...
- JS基础_while循环
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 如何从git上批量拉取本地当前分支的所有代码
1 我本地有一个文件_netrc文件里面存储这git的相关信息,包括用户名和密码 你可以根据自己的git相关信息配置自己的信息 2 我当前的分支是dev,我要拉取当前分支下的所有代码,编写shell脚 ...
- TCP/IP网络知识
1.TCP/IP概念 TCP/IP不是单指一种传输协议,而是一组传输控制协议/互联网协议. 2.TCP/IP分层 (计算机网络中,实际应用的网络协议是TCP/IP协议族,TCP/IP的应用层大体上对应 ...
- Centos7搭建Docker部署LNMP
1.首先呢先更新yum源 yum update 2.1.安装docker存储库 yum install -y yum-utils \ device-mapper-persistent-data \ l ...
- 操作MongoDB好用的图形化工具,Robomongo -> 下载 -> 安装
一 下载 点击下载 -> https://robomongo.org/download 二 安装 直接下一步就行了 -> 择安装位置之后 -> 确认安装
- SmartBinding与kbmMW#2
前言 在之前的文章中,我介绍了SmartBinding作为Delphi的一个新的易于使用和智能的绑定框架.介绍了包括绑定对象,列表,常规数据和可视控件,以及如何使用导航器,所有这些都用代码做了演示. ...
- 【转】Qt 资源图片删除后,错误 needed by `debug/qrc_image.cpp'. Stop. 的终极解决办法
@2019-06-13 [小记] Qt项目做完了把资源文件夹下已经不用的图片文件删掉,运行时报错(编译不报错):No rule to make target `images/图片文件名', neede ...