使用bottle進行web開發(1):hello world

來源:互聯網
上載者:User

標籤:local   _id   action   convert   程式   ddd   gen   pos   還需   

 

 為什麼使用bottle?因為簡單,就一個py檔案,和其他模組沒有依賴,3000多行代碼。

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

 

既然開始學習,就安裝它吧。

pip3 install bottle

ok

第一個代碼:

from bottle import route,run,template@route(‘/hello/<name>‘)def index(name):    return template(‘<b>Hello {{name}}</b>!‘,name=name)run(host=‘localhost‘,port=8080)

運行ok

從這段代碼可以i看出來,bottle雖小,支援不差,包括route,template等,都支援。

而最後一行代碼的run,實際上,就是啟動一個內建的web server。3000多行代碼,還包括一個這個,厲害。

 

 

處於簡單的目的,我們後續學習,大部分時候,都是用一個module-level的裝飾器route()去定義路由。這會把routes都加入到一個全域的預設程式,當第一次調用route()的時候,Bottle的一個進程會被建立。

實際上,更應該代碼是這樣的;

from bottle import Bottle, runapp = Bottle()@app.route(‘/hello‘)def hello():return "Hello World!"run(app, host=‘localhost‘, port=8080)

上面的,route基本都是靜態,下面,我們介紹動態路由:

動態路由相對靜態路由來說,用的更廣泛,一次性匹配更多的url:

比如/hello/<name>可以匹配:/hello/wcf /hello/hanyu /hello/whoami 但是不匹配:/hello /hello/ /hello/wcf/ddd

舉例如下;

@route(‘/wiki/<pagename>‘) # matches /wiki/Learning_Pythondef show_wiki_page(pagename):...@route(‘/<action>/<user>‘) # matches /follow/defnulldef user_api(action,

這裡,還需要關注動態路由的Filters(我稱之為匹配器,目前有4種,可以增加更多),具體是:

:int matches (signed) digits only and converts the value to integer.
? :float similar to :int but for decimal numbers.
? :path matches all characters including the slash character in a non-greedy way and can be used to match more
than one path segment.
? :re allows you to specify a custom regular expression in the config field. The matched value is not modified

 

舉例

from flask import Flaskapp = Flask(__name__)@app.route(‘/user/<int:user_id>‘def user(user_id):    return ‘Hello,%d‘ %user_idif __name__ == ‘__main__‘:    app.run(debug=True)
#coding:utf-8from flask import Flaskfrom werkzeug.routing import BaseConverter#定義正則轉換器的類class RegexConverter(BaseConverter):    def __init__(self,url_map,*items):        super(RegexConverter, self).__init__(url_map)        self.regex=items[0]app = Flask(__name__)#執行個體化app.url_map.converters[‘regex‘]=RegexConverter@app.route(‘/user/<regex("([a-z]|[A-Z]){4}"):username>‘, methods=[‘POST‘, ‘GET‘])def user(username):    return ‘Hello,%s‘ % usernameif __name__ == ‘__main__‘:    app.run(debug=True)

 

代碼如下;

 

使用bottle進行web開發(1):hello world

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.