• 自定义Web框架


    一、框架

    通过python标准库提供的wsgiref模块开发一个自己的Web框架

    #!/usr/bin/env python
    #coding:utf-8
    from wsgiref.simple_server import make_server
     
    def index():
        return 'index'
     
    def login():
        return 'login'
     
    def routers():
         
        urlpatterns = (
            ('/index/',index),
            ('/login/',login),
        )
         
        return urlpatterns
     
    def RunServer(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        url = environ['PATH_INFO']
        urlpatterns = routers()
        func = None
        for item in urlpatterns:
            if item[0] == url:
                func = item[1]
                break
        if func:
            return func()
        else:
            return '404 not found'
         
    if __name__ == '__main__':
        httpd = make_server('', 8000, RunServer)
        print "Serving HTTP on port 8000..."
        httpd.serve_forever()
    

    2、模板引擎

    在上一步骤中,对于所有的login、index均返回给用户浏览器一个简单的字符串,在现实的Web请求中一般会返回一个复杂的符合HTML规则的字符串,所以我们一般将要返回给用户的HTML写在指定文件中,然后再返回。如:

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h1>Index</h1>
    
    </body>
    </html>
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form>
            <input type="text" />
            <input type="text" />
            <input type="submit" />
        </form>
    </body>
    </html>
    

      

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
     
    from wsgiref.simple_server import make_server
     
     
    def index():
        # return 'index'
        f = open('index.html')
        data = f.read()
        return data
     
     
    def login():
        # return 'login'
        f = open('login.html')
        data = f.read()
        return data
     
     
    def routers():
     
        urlpatterns = (
            ('/index/', index),
            ('/login/', login),
        )
     
        return urlpatterns
     
     
    def run_server(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        url = environ['PATH_INFO']
        urlpatterns = routers()
        func = None
        for item in urlpatterns:
            if item[0] == url:
                func = item[1]
                break
        if func:
            return func()
        else:
            return '404 not found'
     
     
    if __name__ == '__main__':
        httpd = make_server('', 8000, run_server)
        print "Serving HTTP on port 8000..."
        httpd.serve_forever()
    

     对于上述代码,虽然可以返回给用户HTML的内容以现实复杂的页面,但是还是存在问题:如何给用户返回动态内容?

    • 自定义一套特殊的语法,进行替换
    • 使用开源工具jinja2,遵循其指定语法

      

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h1>{{name}}</h1>
    
        <ul>
            {% for item in user_list %}
            <li>{{item}}</li>
            {% endfor %}
        </ul>
    
    </body>
    </html>
    

      

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
     
    from wsgiref.simple_server import make_server
    from jinja2 import Template
     
     
    def index():
        # return 'index'
     
        # template = Template('Hello {{ name }}!')
        # result = template.render(name='John Doe')
     
        f = open('index.html')
        result = f.read()
        template = Template(result)
        data = template.render(name='John Doe', user_list=['alex', 'eric'])
        return data.encode('utf-8')
     
     
    def login():
        # return 'login'
        f = open('login.html')
        data = f.read()
        return data
     
     
    def routers():
     
        urlpatterns = (
            ('/index/', index),
            ('/login/', login),
        )
     
        return urlpatterns
     
     
    def run_server(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        url = environ['PATH_INFO']
        urlpatterns = routers()
        func = None
        for item in urlpatterns:
            if item[0] == url:
                func = item[1]
                break
        if func:
            return func()
        else:
            return '404 not found'
     
     
    if __name__ == '__main__':
        httpd = make_server('', 8000, run_server)
        print "Serving HTTP on port 8000..."
        httpd.serve_forever()
    

      遵循jinja2的语法规则,其内部会对指定的语法进行相应的替换,从而达到动态的返回内容,

          对于模板引擎的本质,参考另外一篇博客:白话tornado源码之褪去模板外衣的前戏

  • 相关阅读:
    第五周笔记
    第四周笔记——复制文件(可读时间)
    第三周笔记
    java第6次作业
    java第五次作业
    java第四次作业
    java第三次作业
    第一周Java笔记
    计划进度表
    第六次作业
  • 原文地址:https://www.cnblogs.com/yizhixiaowenzi/p/6554199.html
Copyright © 2020-2023  润新知