zoukankan      html  css  js  c++  java
  • Django基础

    Web框架

    框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来表演。

    对于所有的Web应用本质上就是一个socket服务端,用户的浏览器就是一个socket客户端。

    import socket
    
    def handle_request(client):
    
        buf = client.recv(1024)
        client.send("HTTP/1.1 200 OK
    
    ".encode("utf8"))
        client.send("<h1 style='color:red'>Hello, yuan</h1>".encode("utf8"))
    
    def main():
    
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('localhost',8001))
        sock.listen(5)
    
        while True:
            connection, address = sock.accept()
            handle_request(connection)
            connection.close()
    
    if __name__ == '__main__':
    
        main()
    View Code

    最简单的Web应用就是先把HTML用文件保存好,用一个现成的HTTP服务器软件,接收用户请求,从文件中读取HTML,返回。

    如果要动态生成HTML,就需要把上述步骤自己来实现。不过,接受HTTP请求、解析HTTP请求、发送HTTP响应都是苦力活,如果我们自己来写这些底层代码,还没开始写动态HTML呢,就得花个把月去读HTTP规范。

          正确的做法是底层代码由专门的服务器软件实现,我们用Python专注于生成HTML文档。因为我们不希望接触到TCP连接、HTTP原始请求和响应格式,所以,需要一个统一的接口,让我们专心用Python编写Web业务。

    这个接口就是WSGI:Web Server Gateway Interface。

    ------------------------Do a web  framework ourselves----------------------

    step 1:

    from wsgiref.simple_server import make_server
    
    
    def application(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'<h1>Hello, web!</h1>']
    
    
    httpd = make_server('', 8080, application)
    
    print('Serving HTTP on port 8000...')
    # 开始监听HTTP请求:
    httpd.serve_forever()
    View Code

    注意:

    整个application()函数本身没有涉及到任何解析HTTP的部分,也就是说,底层代码不需要我们自己编写,
    我们只负责在更高层次上考虑如何响应请求就可以了。
    
    application()函数必须由WSGI服务器来调用。有很多符合WSGI规范的服务器,我们可以挑选一个来用。
    
    Python内置了一个WSGI服务器,这个模块叫wsgiref    
        
        
    application()函数就是符合WSGI标准的一个HTTP处理函数,它接收两个参数:
    
            //environ:一个包含所有HTTP请求信息的dict对象;
            
            //start_response:一个发送HTTP响应的函数。
    
    在application()函数中,调用:
    
    start_response('200 OK', [('Content-Type', 'text/html')])
    
    就发送了HTTP响应的Header,注意Header只能发送一次,也就是只能调用一次start_response()函数。
    start_response()函数接收两个参数,一个是HTTP响应码,一个是一组list表示的HTTP Header,每
    个Header用一个包含两个str的tuple表示。
    
    通常情况下,都应该把Content-Type头发送给浏览器。其他很多常用的HTTP Header也应该发送。
    
    然后,函数的返回值b'<h1>Hello, web!</h1>'将作为HTTP响应的Body发送给浏览器。
    
    有了WSGI,我们关心的就是如何从environ这个dict对象拿到HTTP请求信息,然后构造HTML,
    通过start_response()发送Header,最后返回Body。
    View Code

    step 2:

    print(environ['PATH_INFO'])
        path=environ['PATH_INFO']
        start_response('200 OK', [('Content-Type', 'text/html')])
        f1=open("index1.html","rb")
        data1=f1.read()
        f2=open("index2.html","rb")
        data2=f2.read()
    
        if path=="/yuan":
            return [data1]
        elif path=="/alex":
            return [data2]
        else:
            return ["<h1>404</h1>".encode('utf8')]
    View Code

    step3

    from wsgiref.simple_server import make_server
    
    def f1():
        f1=open("index1.html","rb")
        data1=f1.read()
        return [data1]
    
    def f2():
        f2=open("index2.html","rb")
        data2=f2.read()
        return [data2]
    
    def application(environ, start_response):
    
        print(environ['PATH_INFO'])
        path=environ['PATH_INFO']
        start_response('200 OK', [('Content-Type', 'text/html')])
    
    
        if path=="/yuan":
            return f1()
    
        elif path=="/alex":
            return f2()
    
        else:
            return ["<h1>404</h1>".encode("utf8")]
    
    
    httpd = make_server('', 8502, application)
    
    print('Serving HTTP on port 8084...')
    
    # 开始监听HTTP请求:
    httpd.serve_forever()
    View Code

    step4:

    from wsgiref.simple_server import make_server
    
    
    def f1(req):
        print(req)
        print(req["QUERY_STRING"])
    
        f1=open("index1.html","rb")
        data1=f1.read()
        return [data1]
    
    def f2(req):
    
        f2=open("index2.html","rb")
        data2=f2.read()
        return [data2]
    
    import time
    
    def f3(req):        #模版以及数据库
    
        f3=open("index3.html","rb")
        data3=f3.read()
        times=time.strftime("%Y-%m-%d %X", time.localtime())
        data3=str(data3,"utf8").replace("!time!",str(times))
    
    
        return [data3.encode("utf8")]
    
    
    def routers():
    
        urlpatterns = (
            ('/yuan',f1),
            ('/alex',f2),
            ("/cur_time",f3)
        )
        return urlpatterns
    
    
    def application(environ, start_response):
    
        print(environ['PATH_INFO'])
        path=environ['PATH_INFO']
        start_response('200 OK', [('Content-Type', 'text/html')])
    
    
        urlpatterns = routers()
        func = None
        for item in urlpatterns:
            if item[0] == path:
                func = item[1]
                break
        if func:
            return func(environ)
        else:
            return ["<h1>404</h1>".encode("utf8")]
    
    httpd = make_server('', 8518, application)
    
    print('Serving HTTP on port 8084...')
    
    # 开始监听HTTP请求:
    
    httpd.serve_forever()
    View Code
  • 相关阅读:
    vue使用elementui合并table
    使用layui框架导出table表为excel
    vue使用elementui框架,导出table表格为excel格式
    前台传数据给后台的几种方式
    uni.app图片同比例缩放
    我的博客
    【C语言】取16进制的每一位
    SharePoint Solution 是如何部署的呢 ???
    无效的数据被用来用作更新列表项 Invalid data has been used to update the list item. The field you are trying to update may be read only.
    SharePoint 判断用户在文件夹上是否有权限的方法
  • 原文地址:https://www.cnblogs.com/liangying666/p/9740034.html
Copyright © 2011-2022 走看看