Web应用与Web框架

Web应用程序是什么

Web应用程序是一种能够经过Web访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只须要有浏览器便可,不须要再安装其余软件。html

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

Web应用程序的优势

  • 网络应用程序不须要任何复杂的“展开”过程,你所须要的只是一个适用的浏览器;
  • 网络应用程序一般耗费不多的用户硬盘空间,或者一点都不耗费;
  • 它们不须要更新,由于全部新的特性都在服务器上执行,从而自动传达到用户端;
  • 网络应用程序和服务器端的网络产品都很容易结合,如 email 功能和搜索功能;
  • 由于它们在网络浏览器窗口中运行,因此大多数状况下它们是经过跨平台使用的 (例如 Windows,Mac,Linux 等等)

Web应用程序的缺点

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

B/S 架构优势

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

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

基于socket写一个web应用

import socket

def server_run():
    soc = socket.socket()
    soc.bind(('127.0.0.1', 8008))
    soc.listen(5)
    while True:
        conn, addr = soc.accept()
        recv_data = conn.recv(1024)
        print(recv_data)
        # 1 直接在send里写,发送给客户端
        # conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>hello web</h1><img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>')
        #2 打开一个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'))
        # 3 动态网页,字符串替换
        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()
<!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框架

'''
a: socket服务端
b: 根据url不一样返回不一样的内容
    url---视图函数
c: 字符串返回给用户
    特殊字符替换

Web框架种类:
a         b     c           Tornado
别人的a    b     c           django(a用的wsgiref)
别人a      b   别人c         flask(c用的jinja2)

另外一种分类:
    Django和其它

'''

# 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()

WebServer
<!-- 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>

web框架

Web 框架(Web framework)是一种开发框架,用来支持动态网站、网络应用和网络服务的开发。这大多数的web框架提供了一套开发和部署网站的方式,也为 Web 行为提供了一套通用的方法。Web 框架已经实现了不少功能,开发人员使用框架提供的方法而且完成本身的业务逻辑,就能快速开发 Web 应用了。浏览器和服务器的是基于 HTTP 协议进行通讯的。也能够说 Web 框架就是在以上十几行代码基础张扩展出来的,有不少简单方便使用的方法,大大提升了开发的效率。web

wsgiref模块

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

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

正确的作法是底层代码由专门的服务器软件实现,咱们用 Python 专一于生成 HTML 文档。由于咱们不但愿接触到 TCP 链接、HTTP 原始请求和响应格式,因此,须要一个统一的接口协议来实现这样的服务器软件,让咱们专心用 Python 编写 Web 业务。这个接口就是 WSGI:Web Server Gateway Interface。而 wsgiref 模块就是 python 基于 wsgi 协议开发的服务模块。django

from wsgiref.simple_server import make_server

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'<h1>Hello, 你好!</h1>']

httpd = make_server('', 8080, application)

print('Serving HTTP on port 8000...')
# 开始监听HTTP请求:
httpd.serve_forever()

本质上讲,这个文件就能够称为一个 web 框架。flask

相关文章
相关标签/搜索