zoukankan      html  css  js  c++  java
  • web框架本质

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

    HTTP:

      无状态、短连接(connect--请求--响应--断开)

    TCP:

      不断开

    WEB应用:

      浏览器(socket客户端,直接使用chrome、ie等)

        2.访问网站ip+端口

          sk.socket()

          sk.connect((ip+端口))

          sk.send('hello')

        5.接收到‘wellcome’

        6.连接断开

      网站(socket服务端,需要我们写代码)

          1.监听自己的IP+端口

          while True:

            #等待用户连接

            3.收到'hello'

            4.响应‘wellcome’

            用户断开

    服务端最本质代码1.0

    import socket

    sock = socket.socket()

    sock.bind(('127.0.0.1', 8080))

    sock.listen(5)

    while True:

      conn,addr = sock.accetp()  # hang住:阻塞等待连接

      #获取用户发送的数据

      data = conn.recv(8096)

      conn.send(b'wellcome123')

      conn.close()

     ============================================>

    升级,按照HTTP协议规则 1.1

    HTTP协议:

      发送request:

        1. request headers:

          GET(POST) /index?p=123 HTTP/1.1  # 用 分割

          Host: 127.0.0.1:8000

          Connection: keep-alive

          ......................

        2.request body:  #  请求头和请求体用两个/r/n分割

          如果发送POST请求,那数据会放在请求体中。

          P=123

      响应:

        1.response headers响应头

          HTTP/1.1 200 OK

          Set-Cookie: SessionID=13242342342

          ............

        2.response body响应体

          网站返回给访问者的页面内容(浏览器把返回的字符串解析):<html>.........</html>

     ==============================================================>

    继续升级,返回动态页面

    while True:

      conn,addr = sock.accetp()  # hang住:阻塞等待连接

      #获取用户发送的数据

      data = conn.recv(8096)

      data = str(data, encoding='utf-8')

      # 得到请求头和请求体

      headers, bodys = data.split(' ')  

       # 得到请求头里的数  

      # GET  /index  HTTP/1.1

      # Host: 127.0.0.1:8000

      temp_list = headers.split(' ')  

      #分割请求头第一行,得到方法,url等

      #方法 GET,  URL /index, HTTP/1.1  

      method,url,protocal = temp_list[0].split('  ')

      #按http协议返回response headers

      conn.send(b'HTTP/1.1 200 OK ')

      # 根据URL匹配路由

      if url == '/index':

        #如果匹配到路由,返回指定的页面,实现动态返回

        conn.send(b'.......123')

      else:

        #如果没有匹配到路由返回404页面

        conn.send(b'404 not found')

      conn.close()

     ====================================================================>

    继续升级,根据路由调用函数并根据用户请求数据在函数中进行逻辑处理,返回动态页面。(已经近似django的处理)

    # 接受用户请求相关所有信息,然后在函数中进行逻辑处理。

    def f1(request):

      return b'f1'

    def f2(request):

      return b'f2'

    routers = [

      ('/xxx', f1),

      ('/ooo', f2),

    ]

    def run():

      sock = socket.socket()

      sock.bind(('127.0.0.1', 8080))

      sock.listen(5)

      while True:

        conn,addr = sock.accetp()  # hang住:阻塞等待连接

        #获取用户发送的数据

        data = conn.recv(8096)

        data = str(data, encoding='utf-8')

        # 得到请求头和请求体

        headers, bodys = data.split(' ')  

         # 得到请求头里的数  

        # GET  /index  HTTP/1.1

        # Host: 127.0.0.1:8000

        temp_list = headers.split(' ')  

        #分割请求头第一行,得到方法,url等

        #方法 GET,  URL /index, HTTP/1.1  

        method,url,protocal = temp_list[0].split('  ')

        #按http协议返回response headers

        conn.send(b'HTTP/1.1 200 OK ')

        # 遍历routers,进行路由匹配

        func_name = None

        for item in routers:

          if item[0] = url:

            func_name = item[1]

            break

        if func_name:

          # 把用户提交的数据data传给函数

          response = func_name(data)

        else:

          response = '404 not found'

        

        conn.send(response)

        conn.close()

    if __name__ == '__main__':

      run()   

     ====================================================================>

    继续升级,根据路由调用函数并根据用户请求数据在函数中进行逻辑处理,返回动态页面。(已经近似django的处理)

    根据用户请求需要,从数据库读取数据,并放在html模板标签中返回动态页面

    index.html

    <html lang='en'>

    <head>

      <meta charset='utf-8'>

      <title></title>

    </head>

    <body>

      <h1>用户登录</h1>

      <form>

        <p><input type='text' placeholder='用户名' / ><p>

        <p><input type='password' placeholder='密码' / ><p>

      </form>

    </body>

    </html>

    def f1(request):

      f = open('index.html', 'rb')

      data = f.read()

      f.close()

      return data

     ======================================================>

    继续升级,后台从数据库取数,前端展示加入动态模板功能,本质是对模板内特定字符串标签占位符的替换

    index.html

    <html lang='en'>

    <head>

      <meta charset='utf-8'>

      <title></title>

    </head>

    <body>

      <h1>用户登录</h1>

      <table>@@sw@@</table>

    </body>

    </html>

    操作数据库

    index.html
    
    <html lang='en'>
    
    <head>
    
      <meta charset='utf-8'>
    
      <title></title>
    
    </head>
    
    <body>
    
      <h1>用户登录</h1>
    
      <form>
    
        <table>@@sw@@</table>
    
      </form>
    
    </body>
    
    </html>
    -------------------------------
    import pymysql
    # 创建连接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
    # 创建游标,并把游标设置为字典类型
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
      
    # 执行SQL,并返回收影响行数
    # effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
    #执行SQL
    cursor.execute("select id,username,password from userinfo") 
    #得到字典类型的user列表
    user_list = cursor.fetchall()
    
    # 提交,不然无法保存新建或者修改的数据
    #conn.commit()
    # 关闭游标
    cursor.close()
    # 关闭连接
    conn.close()
    
    
    content_list=[]
    for row in user_list:
        tp = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %(row['id'],row['username'],row['password'])
        content_list.append(tp)
    content="".join(content_list)
    
    def f1(request):
        f = open('index.html', 'r',encoding='utf-8')
        data = f.read()
        f.close()
        data.replace('@@sw@@', content)

    content_list=[]
    for row in user_list:
    tp = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %(row['id'],row['username'],row['password'])
    content_list.append(tp)
    content="".join(content_list)

    def f1(request):
    f = open('index.html', 'r',encoding='utf-8')
    data = f.read()
    f.close()
    data = data.replace('@@sw@@', content)

    return bytes(data,encoding='utf-8')

        

  • 相关阅读:
    MD5 SHA1 CRC32
    tf 常用函数 28原则
    matplotlib 28原则
    markdown 基本语法
    tf 数据读取
    django 自定义身份认证
    代理部署
    社区发现算法问题&&NetworkX&&Gephi
    机器学习中的数学——拉格朗日乘子法
    过拟合(Overfitting)和正规化(Regularization)
  • 原文地址:https://www.cnblogs.com/yanjidong/p/14214018.html
Copyright © 2011-2022 走看看