<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Day 5 - 編寫Web框架 在正式開始Web開發前,我們需要編寫一個Web框架。 為什么不選擇一個現成的Web框架而是自己從頭開發呢?我們來考察一下現有的流行的Web框架: **Django**:一站式開發框架,但不利于定制化; **web.py**:使用類而不是更簡單的函數來處理URL,并且URL映射是單獨配置的; **Flask**:使用@decorator的URL路由不錯,但框架對應用程序的代碼入侵太強; **bottle**:缺少根據URL模式進行攔截的功能,不利于做權限檢查。 所以,我們綜合幾種框架的優點,設計一個簡單、靈活、入侵性極小的Web框架。 ### 設計Web框架 一個簡單的URL框架應該允許以@decorator方式直接把URL映射到函數上: ``` # 首頁: @get('/') def index(): return '<h1>Index page</h1>' # 帶參數的URL: @get('/user/:id') def show_user(id): user = User.get(id) return 'hello, %s' % user.name ``` 有沒有@decorator不改變函數行為,也就是說,Web框架的API入侵性很小,你可以直接測試函數`show_user(id)`而不需要啟動Web服務器。 函數可以返回`str`、`unicode`以及`iterator`,這些數據可以直接作為字符串返回給瀏覽器。 其次,Web框架要支持URL攔截器,這樣,我們就可以根據URL做權限檢查: ``` @interceptor('/manage/') def check_manage_url(next): if current_user.isAdmin(): return next() else: raise seeother('/signin') ``` 攔截器接受一個`next`函數,這樣,一個攔截器可以決定調用`next()`繼續處理請求還是直接返回。 為了支持MVC,Web框架需要支持模板,但是我們不限定使用哪一種模板,可以選擇jinja2,也可以選擇mako、Cheetah等等。 要統一模板的接口,函數可以返回`dict`并配合@view來渲染模板: ``` @view('index.html') @get('/') def index(): return dict(blogs=get_recent_blogs(), user=get_current_user()) ``` 如果需要從form表單或者URL的querystring獲取用戶輸入的數據,就需要訪問`request`對象,如果要設置特定的Content-Type、設置Cookie等,就需要訪問`response`對象。`request`和`response`對象應該從一個唯一的ThreadLocal中獲取: ``` @get('/test') def test(): input_data = ctx.request.input() ctx.response.content_type = 'text/plain' ctx.response.set_cookie('name', 'value', expires=3600) return 'result' ``` 最后,如果需要重定向、或者返回一個HTTP錯誤碼,最好的方法是直接拋出異常,例如,重定向到登陸頁: ``` raise seeother('/signin') ``` 返回404錯誤: ``` raise notfound() ``` 基于以上接口,我們就可以實現Web框架了。 ### 實現Web框架 最基本的幾個對象如下: ``` # transwarp/web.py # 全局ThreadLocal對象: ctx = threading.local() # HTTP錯誤類: class HttpError(Exception): pass # request對象: class Request(object): # 根據key返回value: def get(self, key, default=None): pass # 返回key-value的dict: def input(self): pass # 返回URL的path: @property def path_info(self): pass # 返回HTTP Headers: @property def headers(self): pass # 根據key返回Cookie value: def cookie(self, name, default=None): pass # response對象: class Response(object): # 設置header: def set_header(self, key, value): pass # 設置Cookie: def set_cookie(self, name, value, max_age=None, expires=None, path='/'): pass # 設置status: @property def status(self): pass @status.setter def status(self, value): pass # 定義GET: def get(path): pass # 定義POST: def post(path): pass # 定義模板: def view(path): pass # 定義攔截器: def interceptor(pattern): pass # 定義模板引擎: class TemplateEngine(object): def __call__(self, path, model): pass # 缺省使用jinja2: class Jinja2TemplateEngine(TemplateEngine): def __init__(self, templ_dir, **kw): from jinja2 import Environment, FileSystemLoader self._env = Environment(loader=FileSystemLoader(templ_dir), **kw) def __call__(self, path, model): return self._env.get_template(path).render(**model).encode('utf-8') ``` 把上面的定義填充完畢,我們就只剩下一件事情:定義全局`WSGIApplication`的類,實現WSGI接口,然后,通過配置啟動,就完成了整個Web框架的工作。 設計`WSGIApplication`要充分考慮開發模式(Development Mode)和產品模式(Production Mode)的區分。在產品模式下,`WSGIApplication`需要直接提供WSGI接口給服務器,讓服務器調用該接口,而在開發模式下,我們更希望能通過`app.run()`直接啟動服務器進行開發調試: ``` wsgi = WSGIApplication() if __name__ == '__main__': wsgi.run() else: application = wsgi.get_wsgi_application() ``` 因此,`WSGIApplication`定義如下: ``` class WSGIApplication(object): def __init__(self, document_root=None, **kw): pass # 添加一個URL定義: def add_url(self, func): pass # 添加一個Interceptor定義: def add_interceptor(self, func): pass # 設置TemplateEngine: @property def template_engine(self): pass @template_engine.setter def template_engine(self, engine): pass # 返回WSGI處理函數: def get_wsgi_application(self): def wsgi(env, start_response): pass return wsgi # 開發模式下直接啟動服務器: def run(self, port=9000, host='127.0.0.1'): from wsgiref.simple_server import make_server server = make_server(host, port, self.get_wsgi_application()) server.serve_forever() ``` 把`WSGIApplication`類填充完畢,我們就得到了一個完整的Web框架。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看