bottle

来源:https://www.cnblogs.com/JcrLive/archive/2020/03/03/12404737.html
-Advertisement-
Play Games

Bottle是一個快速、簡潔、輕量級的基於WSIG的微型Web框架,此框架只由一個 .py 文件,除了Python的標準庫外,其不依賴任何其他模塊。 1 pip install bottle 2 easy_install bottle 3 apt-get install python-bottle ...


Bottle是一個快速、簡潔、輕量級的基於WSIG的微型Web框架,此框架只由一個 .py 文件,除了Python的標準庫外,其不依賴任何其他模塊。

1 pip install bottle
2 easy_install bottle
3 apt-get install python-bottle
4 wget http://bottlepy.org/bottle.py
安裝

Bottle框架大致可以分為以下部分:

  • 路由系統,將不同請求交由指定函數處理
  • 模板系統,將模板中的特殊語法渲染成字元串,值得一說的是Bottle的模板引擎可以任意指定:Bottle內置模板、makojinja2cheetah
  • 公共組件,用於提供處理請求相關的信息,如:表單數據、cookies、請求頭等
  • 服務,Bottle預設支持多種基於WSGI的服務
 1 server_names = {
 2     'cgi': CGIServer,
 3     'flup': FlupFCGIServer,
 4     'wsgiref': WSGIRefServer,
 5     'waitress': WaitressServer,
 6     'cherrypy': CherryPyServer,
 7     'paste': PasteServer,
 8     'fapws3': FapwsServer,
 9     'tornado': TornadoServer,
10     'gae': AppEngineServer,
11     'twisted': TwistedServer,
12     'diesel': DieselServer,
13     'meinheld': MeinheldServer,
14     'gunicorn': GunicornServer,
15     'eventlet': EventletServer,
16     'gevent': GeventServer,
17     'geventSocketIO':GeventSocketIOServer,
18     'rocket': RocketServer,
19     'bjoern' : BjoernServer,
20     'auto': AutoServer,
21 }
服務
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from bottle import template, Bottle
 4 root = Bottle()
 5  
 6 @root.route('/hello/')
 7 def index():
 8     return "Hello World"
 9     # return template('<b>Hello {{name}}</b>!', name="xxx")
10  
11 root.run(host='localhost', port=8080)
基本使用

一、路由系統

路由系統是的url對應指定函數,當用戶請求某個url時,就由指定函數處理當前請求,對於Bottle的路由系統可以分為一下幾類:

1 @root.route('/hello/')
2 def index():
3     return template('<b>Hello {{name}}</b>!', name="xxx")
靜態路由
 1 @root.route('/wiki/<pagename>')
 2 def callback(pagename):
 3     ...
 4  
 5 @root.route('/object/<id:int>')
 6 def callback(id):
 7     ...
 8  
 9 @root.route('/show/<name:re:[a-z]+>')
10 def callback(name):
11     ...
12  
13 @root.route('/static/<path:path>')
14 def callback(path):
15     return static_file(path, root='static')
動態路由
 1 @root.route('/hello/', method='POST')
 2 def index():
 3     ...
 4  
 5 @root.get('/hello/')
 6 def index():
 7     ...
 8  
 9 @root.post('/hello/')
10 def index():
11     ...
12  
13 @root.put('/hello/')
14 def index():
15     ...
16  
17 @root.delete('/hello/')
18 def index():
19     ...
method 路由
 1 # app01.py
 2 
 3 #!/usr/bin/env python
 4 # -*- coding:utf-8 -*-
 5 from bottle import template, Bottle
 6 
 7 app01 = Bottle()
 8 
 9 @app01.route('/hello/', method='GET')
10 def index():
11     return template('<b>App01</b>!')
12 
13 
14 
15 
16 #app02.py
17 
18 #!/usr/bin/env python
19 # -*- coding:utf-8 -*-
20 from bottle import template, Bottle
21 
22 app02 = Bottle()
23 
24 
25 @app02.route('/hello/', method='GET')
26 def index():
27     return template('<b>App02</b>!')
28 
29 
30 
31 
32 
33 #!/usr/bin/env python
34 # -*- coding:utf-8 -*-
35 from bottle import template, Bottle
36 from bottle import static_file
37 root = Bottle()
38  
39 @root.route('/hello/')
40 def index():
41     return template('<b>Root {{name}}</b>!', name="xxx")
42  
43 from framwork_bottle import app01
44 from framwork_bottle import app02
45  
46 root.mount('app01', app01.app01)
47 root.mount('app02', app02.app02)
48  
49 root.run(host='localhost', port=8080)
二級路由

二、模板系統

模板系統用於將Html和自定的值兩者進行渲染,從而得到字元串,然後將該字元串返回給客戶端。我們知道在Bottle中可以使用 內置模板系統、makojinja2cheetah等,以內置模板系統為例:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>{{name}}</h1>
</body>
</html>
a.html
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from bottle import template, Bottle
 4 root = Bottle()
 5  
 6 @root.route('/hello/')
 7 def index():
 8     # 預設情況下去目錄:['./', './views/']中尋找模板文件 a.html
 9     # 配置在 bottle.TEMPLATE_PATH 中
10     return template('a.html', name='xxx')
11  
12 root.run(host='localhost', port=8888)
a.py
'''
單值
單行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 == "xxx":
        name="seven"
%>
 
 
<h1>4、Python、Html混合</h1>
 
% if True:
    <span>{{name}}</span>
% end
<ul>
  % for item in name:
    <li>{{item}}</li>
  % end
</ul>
語法
include(sub_template, **variables)
# 導入其他模板文件
 
% include('header.html', title='Page Title')
Page Content
% include('footer.html')



rebase(name, **variables)
<html>
<head>
  <title>{{title or 'No title'}}</title>
</head>
<body>
  {{!base}}
</body>
</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>
    {{ xxx() }}

</body>
</html>





#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle,SimpleTemplate
root = Bottle()


def custom():
    return '123123'


@root.route('/hello/')
def index():
    # 預設情況下去目錄:['./', './views/']中尋找模板文件 a.html
    # 配置在 bottle.TEMPLATE_PATH 中
    return template('a.html', name='alex', xxx=custom)

root.run(host='localhost', port=8080)







# 變數或函數前添加 【 ! 】,則會關閉轉義的功能
函數

三、公共組件

由於Web框架就是用來【接收用戶請求】-> 【處理用戶請求】-> 【響應相關內容】,對於具體如何處理用戶請求,開發人員根據用戶請求來進行處理,而對於接收用戶請求和相應相關的內容均交給框架本身來處理,其處理完成之後將產出交給開發人員和用戶。

【接收用戶請求】

當框架接收到用戶請求之後,將請求信息封裝在Bottle的request中,以供開發人員使用

【響應相關內容】

當開發人員的代碼處理完用戶請求之後,會將其執行內容相應給用戶,相應的內容會封裝在Bottle的response中,然後再由框架將內容返回給用戶

所以,公共組件本質其實就是為開發人員提供介面,使其能夠獲取用戶信息並配置響應內容。

 1 # Bottle中的request其實是一個LocalReqeust對象,其中封裝了用戶請求的相關信息:
 2 
 3 request.headers
 4     # 請求頭信息
 5  
 6 request.query
 7     # get請求信息
 8  
 9 request.forms
10     # post請求信息
11  
12 request.files
13     # 上傳文件信息
14  
15 request.params
16     # get和post請求信息
17  
18 request.GET
19     # get請求信息
20  
21 request.POST
22     # post和上傳信息
23  
24 request.cookies
25     # cookie信息
26      
27 request.environ
28     # 環境相關相關
request
 1 # Bottle中的request其實是一個LocalResponse對象,其中框架即將返回給用戶的相關信息:
 2 
 3 response
 4     response.status_line
 5         # 狀態行
 6  
 7     response.status_code
 8         # 狀態碼
 9  
10     response.headers
11         # 響應頭
12  
13     response.charset
14         # 編碼
15  
16     response.set_cookie
17         # 在瀏覽器上設置cookie
18          
19     response.delete_cookie
20         # 在瀏覽器上刪除cookie
response
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,
}


# 使用時,只需在主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,如果想要使用其他時,則需要首先安裝相關類庫,然後才能使用。



#bottle.py源碼
# 如果使用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()



#以上WSGI中提供了19種,如果想要使期支持其他服務,則需要擴展Bottle源碼來自定義一個ServerAdapter


http://www.bottlepy.org/docs/dev/index.html

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 這節課,我們來學習一下SpringBoot的環境配置,在SpringBoot中,所有的配置都寫在application.properties中: 我們啟動項目,預設埠是8080,我們現在給他配置一個8088: server.port=8088 運行啟動類,然後在瀏覽器地址欄訪問上一節中的控制器: ...
  • 在開始之前,我們需要去創建一個SpringBoot項目,大家可以去 http://start.spring.io/ 這個網站生成一個項目。 如圖,這邊可以對SpringBoot項目進行詳細設置: 下麵這個web一定要勾選: SpringBoot版本號選擇1.5.10 全部設置好了以後,就點擊這個按鈕 ...
  • 1.引子 大家好,在接下里的半個多小時,我會給大家詳細的介紹SpringBoot的基本使用,相信學完這門課程以後,你會對SpringBoot有一個清晰的認識,並且能夠運用這門比較新穎的技術開發一些小程式。我也希望,這門課程能夠對大家入門SpringBoot框架起到一個良好的助推作用。 在開始之前,我 ...
  • 最近做項目測試的發現,訪問Url返回的時間與資料庫中的不相同,環境是Spring boot+MyBatis+Mysql(阿裡雲伺服器),經過一番折騰,得到瞭解決 問題描述 我是直接使用IDEA的資料庫控制台,往資料庫中某個表插入了數據,該表存在著一個欄位date,此欄位是插入數據的時候由資料庫自動賦 ...
  • 接下來我們就從後置處理器和BeanFactoryAware的角度來看看AnnotationAwareAspectJAutoProxyCreator的Bean定義類創建完成後都做了什麼。 ...
  • 一、編程語言簡介 機器語言 電腦能直接理解的就是二進位指令,所以機器語言就是直接用二進位編程,這意味著機器語言是直接操作硬體的,因此機器語言屬於低級語言, 此處的低級指的是底層、貼近電腦硬體(貼近代指需要詳細瞭解電腦硬體細節、直接控制硬體) 彙編語言 是一種用於電子電腦、微處理器、微控制器或 ...
  • 首先提供兩個XML文件 XML代碼如下: 1、Example.xml <?xml version="1.0" encoding="ISO-8859-1"?> <chart> <series title="Series1" type="Point" color="#FF0000"> <points c ...
  • 一、編程語言介紹 編程語言的分類: 機器語言(奴隸的母語):直接用二進位數0,1構成的指令去編寫程式,即用電腦能夠直接理解的二進位指令編寫程式,電腦可以無障礙理解。 優點:執行效率最高 缺點:開發效率最低、跨平臺性差 彙編語言:用英文標簽取代二進位去編寫程式 優點:執行效率高 缺點:開發效率低、 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...