成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

初識Bottle(二)

stormjun / 3046人閱讀

摘要:而其他的引擎,例如能夠幫我們進(jìn)行驗證登錄自此,官網(wǎng)的我們已經(jīng)大致有了了解后續(xù)我們可以選擇運用該框架實現(xiàn)一些簡單的應(yīng)用,或者可以深入研究其源碼,提升自身的編程水平

在初識Bottle(一)中,我們了解了Bottle的基本用法
在Bottle源碼閱讀(一)和Bottle源碼閱讀(二)可以查看個人對bottle源碼的相關(guān)閱讀筆記

下面繼續(xù)閱讀Bottle的官方文檔https://bottlepy.org/docs/dev...

1.路由靜態(tài)文件

在bottle中例如css等的文件是不會被自動加載的,因此需要自己定義callback函數(shù),通過調(diào)用使用

from bottle import static_file
@route("/static/")
def server_static(filename):
    return static_file(filename, root="/path/to/your/static/files")
2.錯誤頁

通過error裝飾器可以對相應(yīng)的錯誤碼自定義對應(yīng)的應(yīng)用函數(shù)

from bottle import error
@error(404)
def error404(error):
    return "Nothing here, sorry"
3.內(nèi)容返回

Bottl框架允許應(yīng)用函數(shù)返回如下類型的結(jié)果

Dictionaries字典:
python的字典通過框架被轉(zhuǎn)換為json字符串,而header中的Content-Type則會被設(shè)置為application/json

Empty Strings, False, None or other non-true values:
header中的Content-Length被設(shè)置為0

Unicode strings
Byte strings
Instances of HTTPError or HTTPResponse
File objects
Iterables and generators

4.改變默認(rèn)編碼

通過在應(yīng)用函數(shù)中改變response的屬性可以自定義

from bottle import response
@route("/iso")
def get_iso():
    response.charset = "ISO-8859-15"
    return u"This will be sent with ISO-8859-15 encoding."

@route("/latin9")
def get_latin():
    response.content_type = "text/html; charset=latin9"
    return u"ISO-8859-15 is also known as latin9."
5.靜態(tài)文件的使用

通過static_file接口,我們可以實現(xiàn)調(diào)用和下載

from bottle import static_file
@route("/images/")
def send_image(filename):
    return static_file(filename, root="/path/to/image/files", mimetype="image/png")

@route("/static/")
def send_static(filename):
    return static_file(filename, root="/path/to/static/files")
    
@route("/download/")
def download(filename):
    return static_file(filename, root="/path/to/static/files", download=filename)
6.HTTP ERRORS AND REDIRECTS

通過abort可以快速定義錯誤碼相應(yīng)的錯誤頁內(nèi)容
redirect實現(xiàn)重定向

from bottle import route, abort
@route("/restricted")
def restricted():
    abort(401, "Sorry, access denied.")
    
from bottle import redirect
@route("/wrong/url")
def wrong():
    redirect("/right/url")
7.RESPONSE

response對象包括了響應(yīng)的metadata例如狀態(tài)碼,headers,cookie等

response的狀態(tài)碼控制瀏覽器的行為,默認(rèn)200ok
response的header可以通過set_header()來設(shè)置,對同一個header項,還可以通過add_header添加額外內(nèi)容
cookie是保留在用戶瀏覽器的一些數(shù)據(jù),可以通過get_cookie和set_cookie來操作

@route("/hello")
def hello_again():
    if request.get_cookie("visited"):
        return "Welcome back! Nice to see you again"
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you"

cookie是容易被偽造的,所以Bottle框架提供了cookie的簽名機(jī)制,只需要提供一個secret的參數(shù)作為密鑰
Bottle會自動持久化和去持久化保存在cookie中的數(shù)據(jù),cookie不超過4k。
此時cookie仍然能從瀏覽器中查看到,而且是可以被復(fù)制的,所以最好不要將密鑰的信息放在用戶客戶端

@route("/login")
def do_login():
    username = request.forms.get("username")
    password = request.forms.get("password")
    if check_login(username, password):
        response.set_cookie("account", username, secret="some-secret-key")
        return template("

Welcome {{name}}! You are now logged in.

", name=username) else: return "

Login failed.

" @route("/restricted") def restricted_area(): username = request.get_cookie("account", secret="some-secret-key") if username: return template("Hello {{name}}. Welcome back.", name=username) else: return "You are not logged in. Access denied."
8.REQUEST

request 對象包括了Cookies, HTTP header, HTML

等一系列可以操作的對象

from bottle import request, route, template

@route("/hello")
def hello():
    name = request.cookies.username or "Guest"
    return template("Hello {{name}}", name=name)

Bottle使用FormsDict存儲表單數(shù)據(jù)和cookie數(shù)據(jù),而FormsDict的特定就是既具備了普通字典的操作方法,又能將key作為對象的屬性,具體如下name既是字典的key又是cookies的屬性

name = request.cookies.name

# is a shortcut for:

name = request.cookies.getunicode("name") # encoding="utf-8" (default)

# which basically does this:

try:
    name = request.cookies.get("name", "").decode("utf-8")
except UnicodeError:
    name = u""

同時,F(xiàn)ormsDict還能對單個key存儲多個值

for choice in request.forms.getall("multiple_choice"):
    do_something(choice)

request的query string會被分解為多個鍵值對,而通過request.query可以直接獲得查詢字符串對應(yīng)鍵的值

from bottle import route, request, response, template
@route("/forum")
def display_forum():
    forum_id = request.query.id
    page = request.query.page or "1"
    return template("Forum ID: {{id}} (page {{page}})", id=forum_id, page=page)

上傳文件時,我們需要在表單添加enctype="multipart/form-data", 同時將type設(shè)置為file


  Category:      
  Select a file: 
  

文件上傳到服務(wù)端后

@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"

通過BaseRequest.body我們可以直接獲取原始的請求體,也可以獲取environ

@route("/my_ip")
def show_ip():
    ip = request.environ.get("REMOTE_ADDR")
    # or ip = request.get("REMOTE_ADDR")
    # or ip = request["REMOTE_ADDR"]
    return template("Your IP is: {{ip}}", ip=ip)
9.模板

Bottle內(nèi)建了前端模板引擎,在官網(wǎng)給出的這個例子中,會加載./views/中的hello_template.tpl

@route("/hello")
@route("/hello/")
def hello(name="World"):
    return template("hello_template", name=name)
或者
@route("/hello")
@route("/hello/")
@view("hello_template")
def hello(name="World"):
    return dict(name=name)
%if name == "World":
    

Hello {{name}}!

This is a test.

%else:

Hello {{name.title()}}!

How are you?

%end

模板在編譯后會被緩存到內(nèi)存中,修改后需要執(zhí)行bottle.TEMPLATES.clear()清除緩存模板

10.PLUGINS

Bottle提供了一系列的第三方引擎,這些能夠有效地減少重復(fù)性工作
官網(wǎng)使用SQLitePlugin作為例子,在每一次調(diào)用需要與數(shù)據(jù)庫進(jìn)行交互的callback函數(shù)時,該引擎會自動創(chuàng)建連接和關(guān)閉連接。而其他的引擎,例如’auth‘能夠幫我們進(jìn)行驗證登錄

from bottle import route, install, template
from bottle_sqlite import SQLitePlugin

install(SQLitePlugin(dbfile="/tmp/test.db"))

@route("/show/")
def show(db, post_id):
    c = db.execute("SELECT title, content FROM posts WHERE id = ?", (post_id,))
    row = c.fetchone()
    return template("show_post", title=row["title"], text=row["content"])

@route("/contact")
def contact_page():
    """ This callback does not need a db connection. Because the "db"
        keyword argument is missing, the sqlite plugin ignores this callback
        completely. """
    return template("contact")
sqlite_plugin = SQLitePlugin(dbfile="/tmp/test.db")
install(sqlite_plugin)

uninstall(sqlite_plugin) # uninstall a specific plugin
uninstall(SQLitePlugin)  # uninstall all plugins of that type
uninstall("sqlite")      # uninstall all plugins with that name
uninstall(True)          # uninstall all plugins at once

自此,Bottle官網(wǎng)的tutorial我們已經(jīng)大致有了了解
后續(xù)我們可以選擇運用該框架實現(xiàn)一些簡單的應(yīng)用,或者可以深入研究其源碼,提升自身的編程水平

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/38445.html

相關(guān)文章

  • 初識 Bottle (一)

    摘要:安裝是一個輕量型的不依賴于任何第三方庫的框架,整個框架只有一個文件。向打聲招呼吧新建一個文件在瀏覽器或者,,得到結(jié)果當(dāng)使用裝飾器綁定路由時,實際是使用了的默認(rèn)應(yīng)用,即是的一個實例。 1. 安裝 bottle是一個輕量型的不依賴于任何第三方庫的web框架,整個框架只有bottle.py一個文件。 wget http://bottlepy.org/bottle.py 2. 向bottl...

    mengbo 評論0 收藏0
  • Bottle源碼閱讀(一)

    摘要:在初識一中,我們了解了框架的基本用法。在本篇文章中,我們通過源碼來探究一些基本原理。因此下一步就是研究我們寫的應(yīng)用函數(shù)是如何被封裝成適配的 在初識bottle(一)中,我們了解了bottle框架的基本用法。在本篇文章中,我們通過源碼來探究一些基本原理。 1. run的實現(xiàn) 所有的框架請求響應(yīng)都基于一個原理http請求 --> wsgi服務(wù)器 --> wsgi接口(實際就是框架中自定義...

    whidy 評論0 收藏0
  • Bottle源碼閱讀(

    摘要:在源碼閱讀一中,我們了解了如何接收請求,處理請求以及如何檢測模塊變化重啟。接下來我們看一下源碼是怎么實現(xiàn)的經(jīng)過封裝后,最終獲得的是具備有一些屬性的裝飾器當(dāng)為時,將的屬性傳遞給,使其具備相同的屬性。 在《Bottle源碼閱讀(一)》中,我們了解了bottle如何接收請求,處理請求以及如何檢測模塊變化重啟server。在ServerHandler類中的run函數(shù)中,application接...

    zzbo 評論0 收藏0
  • Bottle框架中的裝飾器類和描述符應(yīng)用

    摘要:最近在閱讀微型框架的源碼,發(fā)現(xiàn)了中有一個既是裝飾器類又是描述符的有趣實現(xiàn)。所以第三版的代碼可以這樣寫第三版的代碼沒有使用裝飾器,而是使用了描述符這個技巧。更大的問題來自如何將描述符與裝飾器結(jié)合起來,因為是一個類而不是方法。 最近在閱讀Python微型Web框架Bottle的源碼,發(fā)現(xiàn)了Bottle中有一個既是裝飾器類又是描述符的有趣實現(xiàn)。剛好這兩個點是Python比較的難理解,又混合在...

    Panda 評論0 收藏0
  • 使用python抓取百度漂流瓶妹紙照片

    摘要:無意中發(fā)現(xiàn)貼吧也出了個漂流瓶的東西,隨手翻了翻發(fā)現(xiàn)居然有好多妹子圖,閑來無事于是就想寫個爬蟲程序把圖片全部抓取下來。具體獲取一頁內(nèi)容的如下看參數(shù)很容易明白,就是當(dāng)前頁碼,就是當(dāng)前頁中包含的漂流瓶數(shù)量。 showImg(https://segmentfault.com/img/bVLUTV?w=638&h=808); 無意中發(fā)現(xiàn)貼吧也出了個漂流瓶的東西,隨手翻了翻發(fā)現(xiàn)居然有好多妹子圖,閑...

    bang590 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<