国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

簡單介紹Python下自己編寫web框架的一些要點

2020-02-23 01:00:43
字體:
來源:轉載
供稿:網友

在正式開始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中獲?。?/p>

@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')            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临邑县| 永胜县| 九寨沟县| 资源县| 修文县| 尼勒克县| 东平县| 太谷县| 牙克石市| 武陟县| 米泉市| 烟台市| 郁南县| 元谋县| 龙江县| 平阴县| 邳州市| 娱乐| 全南县| 谢通门县| 聂荣县| 衡阳县| 平利县| 常山县| 咸宁市| 大方县| 上栗县| 仁化县| 安塞县| 永仁县| 珠海市| 桑植县| 濮阳市| 海兴县| 克拉玛依市| 湛江市| 西充县| 高雄市| 集安市| 余干县| 讷河市|