Web 应用

一、Web 应用程序是什么

Web 应用程序是一种可以通过 Web 访问的应用程序,程序的最大的好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要安装其他软件

应用程序有两种模式 C/SB/SC/S 是客户端/服务器端程序,也就是说这类一般独立运行,而 B/S 就是浏览器/服务器应用程序。这类应用程序一般借助于 IE 等浏览器来运行。Web 应用程序一般是 B/S 模式。Web 应用程序首先是“应用程序”,和用标准的程序语言,如 CC++等编写出来的程序没有什么本质上的不同,然而 Web 应用程序又有自己的独特的地方,就是它是基于 Web 的,而不是采用传统的方法运行的。总的来说,它是典型的浏览器/服务器架构的产物

1. Web 应用程序的优点

  • 网络应用程序不需要任何复杂的“展开”过程,你所需要的只是一个适用的浏览器
  • 网络应用程序通常耗费很少的用户硬盘空间,或者一点都不耗费
  • 它们不需要更新,因为它们所有新的特性都在服务器上执行,从而自动传达到用户端
  • 网络应用程序和服务器端的网络产品都很容易结合,如 email 功能和搜索功能
  • 因为它们在网络浏览器窗口中运行,所以大多数情况下它们是通过跨平台使用的(如:WindowsLinux 等)

2. Web 应用程序的缺点

  • 网络应用程序强调浏览器的适用性。如果浏览器方没有提供特定的功能,或者弃用特定的平台或操作系统版本(导致不适用),就会影响大量用户
  • 网络应用依靠互联网远程服务器端的应用文件。因此,当连接出问题时,应用将不能正常使用
  • 许多网络应用程序不是开源的,只能依赖第三方提供的服务,因此不能针对用户定制化、个性化,而且大多数情况下用户不能离线使用,因而损失了很多灵活性
  • 它们完全依赖应用服务商的可及性。如果公司倒闭,服务器停止使用,用户也无法追索以前的资料。对比而看,即使软件制造商倒闭了,传统的安装软件也可以继续运行,尽管不能再更新或有其他用户服务
  • 相似地,提供方公司对软件和其功能有了更大的控制权。只要他们愿意就能为软件添加新特性,即使用户想等bugs 先被解决再更新。跳过较差的软件版本也不可能了。公司可以强加不受欢迎的特性给用户,也可以随意减少带宽来削减开支
  • 公司理论上可以检索任何的用户行为。这有可能引起隐私安全问题

3. B/S 架构优点

浏览器/服务器架构(Browser/Server,简称 B/S)能够很好地应用在广域网上,成为越来越多的企业的选择。浏览器/服务器架构相对于其他几种应用程序体系结构,有如下三个方面的优点:

  • 这种架构采用 Internet 上标准的通信协议(通常是TCP/IP协议)作为客户机同服务器通信的协议。这样可以使位于 Internet 任意位置的人都能够正常访问服务器。对于服务器来说,通过相应的 Web 服务和数据库服务可以对数据进行处理。对外采用标准的通信协议,以便共享数据
  • 在服务器上对数据进行处理,就处理的结果生成网页,以方便客户端直接下载
  • 在客户机上对数据的处理被进一步简化,将浏览器作为客户端的应用程序,以实现对数据的显示。不再需要为客户端单独编写和安装其他类型的应用程序。这样,在客户端只需要安装一套内置浏览器的操作系统,直接安装一套浏览器,就可以实现服务器上数据的访问。而浏览器是计算机的标准设备

总的来说,本质上:浏览器是一个 socket 客户端,服务器是一个 socket 服务端

二、基于 Socket 写一个 Web 应用

Python 文件

import socket

def server_run():
    server = socket.socket()		# 默认是 TCP 协议
    server.bind(("127.0.0.1",8080))
    server.listen(5)
    while True:
        conn.addr = server.accept()
        recv_data = conn.recv(1024)
        '''
        第一种:直接在 send 里写,发送给客户端
        conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>hello web</h1><img src ="https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&hs=2&pn=2&spn=0&di=170170&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=3892521478%2C1695688217&os=733181249%2C216344720&simid=4289427427%2C709582725&adpicid=0&lpn=0&ln=1846&fr=&fmq=1593777124151_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fa0.att.hudong.com%2F56%2F12%2F01300000164151121576126282411.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fp7rtwg_z%26e3Bkwthj_z%26e3Bv54AzdH3Ftrw1AzdH3Fwa_cm_8d_a8naaaaa8m98c88d8c0m8dmdbd988_3r2_z%26e3Bip4s&gsm=2&rpstart=0&rpnum=0&islist=&querylist=&force=undefined"</img>')
        '''
        
        '''
        第二种:打开一个 html 文件,发送给客户端
        with open("index.html","r",encoding="utf-8") as f:
        	data = f.read()
        conn.send("HTTP/1.1 200 OK\r\n\r\n%s"%data).encode('utf-8')
        '''
        
        '''
        第三种:动态网页,字符串替换
        import time
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print(now)
        with open('index.html','r',encoding='utf-8') as f:
            data=f.read()
        data = data.replace('@@@',now)
        conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
        conn.close()
        '''
if __name__ == '__main__':
    server_run()

index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>@@@</h2>

<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg" alt="">
</body>
</html>

三、简单的 Web 框架

WebServer

import socket

import pymysql
def index(request):
    return '<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>'

def login(request):
    with open('login.html','r',encoding='utf-8') as f :
        data=f.read()
    return data

def time(request):
    import datetime
    now=datetime.datetime.now().strftime('%Y-%m-%d %X')
    with open('time.html','r',encoding='utf-8') as f :
        data=f.read()
    data=data.replace('@@time@@',now)
    return data

def user_list(request):
    # 创建连接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='lqz')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute("select id,name,password from user")
    user_list = cursor.fetchall()
    cursor.close()
    conn.close()
    tr_list=[]
    for row in user_list:
        tr='<tr><td>%s</td><td>%s</td><td>%s</td></tr>'%(row['id'],row['name'],row['password'])
        tr_list.append(tr)


    with open('user_list.html','r',encoding='utf-8') as f:
        data=f.read()
    data=data.replace('@@body@@',''.join(tr_list))
    return data

def user_list_new(request):
    # 创建连接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='lqz')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute("select id,name,password from user")
    user_list = cursor.fetchall()
    cursor.close()
    conn.close()
    with open('user_list_new.html','r',encoding='utf-8') as f:
        data=f.read()
    from jinja2 import Template
    template=Template(data)
    response=template.render(user_list=user_list)
    # response=template.render({'user_list':user_list})
    return response

urls = [
    ('/index', index),
    ('/login', login),
    ('/time', time),
    ('/user_list', user_list),
    ('/user_list_new', user_list_new),
]

def run():
    soc = socket.socket()
    soc.bind(('127.0.0.1', 8006))
    soc.listen(5)
    while True:
        conn, port = soc.accept()
        data = conn.recv(1024)
        # data=data.decode('utf-8')
        print(data)
        data = str(data, encoding='utf-8')
        request_list = data.split('\r\n\r\n')
        head_list = request_list[0].split('\r\n')
        method, url, htt = head_list[0].split(' ')
        # conn.send(b'hello web')
        conn.send(b'HTTP/1.1 200 OK \r\n\r\n')
        print(url)
        func_name = None
        for u in urls:
            if url == u[0]:
                func_name = u[1]
                break
        if func_name:
            response = func_name(data)
        else:
            response = '404 not found'

        conn.send(response.encode('utf-8'))
        conn.close()

if __name__ == '__main__':
    run()

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="">
        <p>用户名:<input type="text"></p>
        <p>密码:<input type="password"></p>
    </form>
</body>
</html>

time.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

@@time@@
</body>
</html>

user_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>

<table border="1">
    <thead>
        <tr>
            <th>id</th>
            <th>用户名</th>
            <th>密码</th>
        </tr>
    </thead>
    <tbody>
        @@body@@
    </tbody>
</table>

</body>
</html>

user_list_new.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>password</th>
            </tr>
        </thead>
        
        <tbody>
            {% for user in user_list%}
            <tr>
                <td>{{user.id}}</td>
                <td>{{user.name}}</td>
                <td>{{user.password}}</td>
            </tr>
            {%endfor%}
        </tbody>
    </table>
</body>
</html>
posted @ 2020-06-04 09:14  杼柚  阅读(260)  评论(0编辑  收藏  举报