[关闭]
@ranger-01 2018-03-18T16:19:56.000000Z 字数 1549 阅读 899

Web 框架做了哪些事情

web_server


1. Web work flow

上一篇文章中,我们知道web工作刘如下:

the web client <-> the web server <-> the socket <-> (uwsgi protocol)uWSGI(WSGI) <-> Python

并用例子说明了,application server(uWSGI)要做的事情:
image_1c8pfcqt750j25vcogdo13c02g.png-43.8kB

  1. 从输入中获取数据构造env字典(handle_one_request, parse_request),里面一般包括:

    • PATH_INFO:
    • HTTP_HOST,
    • SERVER_PORT
    • REQUEST_METHOD
    • QUERY_STRING(GET),
    • CONTENT_LENGTH(POST),
    • wsgi.input(POST请求中,框架会从这个句柄中获取POST请求携带的data)
    • GET request
      image_1c8pei3921tgb1gc96pb771hei9.png-79.9kB
    • POST request
      image_1c8pept201b2b20eubas1g1f3km.png-66.8kB
  2. 根据application返回的output,构造http response

    • application先调用start_response构造response header
      image_1c8pfu82u15ucd651d38id289u3a.png-24kB
    • application server在把output,添加在后面,行成response
      image_1c8pfrupn16be48n1j0nho313bf2t.png-63kB

2. 框架做的事情

  1. URL mapping

    • 创建URL map
      image_1c8rqodng15rj1pmulrr1fmb1mto9.png-28.3kB
    • 添加路由
      image_1c8rqsq9tffji15tavv5asu4m.png-45.5kB
    • URL map详情

      1. ROUTES_SIMPLE = {
      2. 'GET' {
      3. 'URL': handler
      4. },
      5. 'POST': {
      6. 'URL': handler
      7. }
      8. }
      9. ROUTES_REGEXP = {
      10. 'GET' [
      11. [Pattern object, handler],
      12. [Pattern object, handler]
      13. ]
      14. 'POST': [
      15. [Pattern object, handler],
      16. [Pattern object, handler]
      17. ]
      18. }

      image_1c8rr1rlr16m91vd1shg1f6k107g13.png-99.8kB

    • URL match

      1. def match_url(url, method='GET'):
      2. url = '/' + url.strip().lstrip("/")
      3. # Search for static routes first
      4. route = ROUTES_SIMPLE.get(method,{}).get(url,None)
      5. if route:
      6. return (route, {})
      7. # Now search regexp routes
      8. routes = ROUTES_REGEXP.get(method,[])
      9. for i in xrange(len(routes)):
      10. match = routes[i][0].match(url)
      11. if match:
      12. handler = routes[i][9]
      13. if i > 0 and OPTIMIZER and random.random() <= 0.001:
      14. # Every 1000 requests, we swap the matching route with its predecessor.
      15. # Frequently used routes will slowly wander up the list.
      16. routes[i-1], routes[i] = routes[i], routes[i-1]
      17. return (handler, match.groupdict())
      18. return (None, None)
  2. Request and Response的封装
    • Request
      image_1c8rs9g1m1bsgiik635bep3vk9.png-69.5kB
    • Response
      image_1c8rsbtlb1i0v1mt7129ua8i1drtm.png-51kB
  3. template 引擎
    • 模板引擎:相当于构造了一个函数,输入是模板需要的变量,输出是html
      image_1c8rv999c1a24i7nm6q91d1se713.png-60.7kB
  4. 错误,异常处理
    • 设置错误处理函数
      image_1c8rvocj2jpou8b6k51p3i18ll1t.png-70.3kB
    • 根据错误的不同,output显示不一样的信息:例如:500则显示traceback;其他显示有用的msg
      image_1c8rvncdf16q536a1pc31ehr1b7b1g.png-48kB

3. 框架还可以做的事情

  1. 安全支持:放CSRF, XSS, SQL\命令行注入
  2. session支持: token
  3. 权限管控: has_permission
  4. ORM支持
  5. admin后台管理
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注