如何理解Python的web框架tornado文件裡面的使用者認證的self current user?

時間 2021-06-06 21:33:14

1樓:煌煌不安

1. self.current_user是用來活取get_currrent_user返回的值

在tornado的原始碼中

defget_current_user

(self

):"""Override to determine the current user from, e.g., a cookie."""

return

None

get_current_user一直返回None,如果沒有重寫它來獲得你想要的資料,那麼在伺服器端的self.current_user就一直是None。

例如我們可以在get_current_user中返回cookie來代表使用者已經登入過並在瀏覽器儲存了cookie,例如:

class

BaseHandler

(tornado

.web

.RequestHandler

):def

get_current_user

(self

):#取cookie

return

self

.get_cookie

(cookie_name

)class

SignInHandler

(BaseHandler

):def

get(

self

):#如果拿到的cookie不為None,表示使用者已經登入過

ifself

.current_user

:self

.redirect

(your_main_page

)else

:self

.render

(your_sign_in_page

)2. tornado.escape.xhtml_escape是用來轉義一些字元的。

Escapes a string so it is valid within HTML or XML.

Escapes the characters <, >, ", ', and &. When used in attribute values the escaped strings must be enclosed in quotes.

Changed in version 3.2: Added the single quote to the list of escaped characters.

在tornado的原始碼中是用python正規表示式按_XHTML_ESCAPE_DICT=

2樓:

你的 RequestHandler 裡寫乙個方法defget_current_user

(self

):return

"Someone"

只要這裡返回的不是 None,@authenticated decorator 就會認為是經過認證的,否則會跳轉到 self.settings['login_url'] 去。

所以需要做的事情完整起來是三件:

實現 login_url 登入流程,將使用者名稱存在 session 中——常見辦法是用 set_secure_cookie 把使用者名稱放在 cookie 中。

這裡你跑不了要做登入驗證啊身份管理啊等等等等。

在 get_current_user 中,去提取 login_url 儲存的這個使用者名稱。

如何理解 Web 語義化?

大堯 Semantic HTML 這有乙個前人總結的非常棒 今天搜Semantic HTMl搜到的,總結的很棒,看起來困難的話去看看維基百科的相關詞條,看看之前的歷史也挺有意思哈哈 Reco 那些給語義化唱歌的人,我們看看歷史。1.html5 kill xhtml 2.wikipedia kill ...

Python 有哪些好的 Web 框架?

王阿覺 我來推薦另外乙個Masonite,它是2019年編寫的Web框架,目前穩定的版本是2.3 乙個類PHP Larvel的Python框架,下面的鏈結是他的介紹文件 要翻 Introduction and Installation WilliamSYB Django大而全 Flask小而精 to...

如何理解 Python 的 Descriptor?

一起吃鰻魚飯啊 簡單來說,對與既支援函式式程式設計又支援物件導向式程式設計的語言來說,統一函式和類方法有兩種解決方案,一種是像Ruby一樣所有的callable都是類方法,或者像Python這樣,類方法只是帶有物件的特殊函式,descriptor就是為了解決這個而引入的。 影之心 描述器有三個特殊方...