一、Web基础

1.1 HTTP

HTTP(HyperText Transfer Protocol),超文本传输协议,利用TCP在Web服务器和客户端之间传输信息,客户端使用Web浏览器发起HTTP请求给Web服务器,Web服务器发送被请求的信息给客户端。
HTTP基本原理:
当在浏览器输入URL后,浏览器会先请求DNS服务器,获得请求站点的IP地址,然后发送一个HTTP Request给拥有该IP的主机,接着就会接收到服务器返回的HTTP Response,浏览器经过渲染后,以一种较好的状态呈现给用户。
image.png

1.2 Web服务器

Web 服务器的工作原理:
1.建立连接:客户端通过TCP/IP协议建立到服务器的TCP连接
2.请求过程:客户端向服务器发送HTTP协议请求包,请求服务器里的资源文档
3.应答过程:服务器向客户端发送HTTP协议应答包,如果请求的资源包含动态语言的内容跟,那么服务器会调用动态语言的解释引擎负责处理“动态内容”,并将处理后得到的数据返回给客户端。由客户端解释HTML文档,在客户端屏幕上渲染图形结果。
4.关闭连接:客户端与服务器断开。

1.3 创建静态服务器

创建一个静态服务器,通过该服务器,可以访问静态页面。

  1. #coding:utf-8
  2. import socket ##导入socket模块
  3. from multiprocessing import Process ##导入Process多进程模块
  4. HTML_ROOT_DIR = './views' ##设置静态文件根目录
  5. class HTTPServer(object):
  6. def __init__(self):
  7. ##初始化方法
  8. self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ##创建Socket对象,使用TCP/IP协议
  9. def start(self):
  10. ##开始方法
  11. self.server_socket.listen(128) ##设置最大连接数为128
  12. print('服务端等待客户端连接……')
  13. print(' '*50)
  14. ##执行死循环
  15. while True:
  16. client_socket,client_address = self.server_socket.accept() ##建立客户端连接
  17. print("[%s,%s]用户连接上了"%client_address)
  18. print(' '*50)
  19. ##实例化进程类
  20. handle_client_process = Process(target=self.handle_client, args=(client_socket,))
  21. handle_client_process.start() ##开启线程
  22. client_socket.close() ##关闭客户端Socket
  23. def handle_client(self,client_socket):
  24. ##处理客户端请求
  25. ##获取客户端请求
  26. request_data = client_socket.recv(1024) ##获取客户端请求数据
  27. print('request data:', request_data)
  28. request_line = request_data.splitlines() ##按照行('\r','\r\n','\n')分割
  29. ##输出每行信息
  30. for line in request_line:
  31. print(line)
  32. request_start_line = request_line[0] ##解析请求报文
  33. print(' '*50)
  34. print('*'*50)
  35. print(request_start_line.decode('utf-8'))
  36. try:
  37. file = open(HTML_ROOT_DIR+'/index.html','rb')
  38. except IOError:
  39. ##如果存在异常,返回404
  40. response_start_line = "HTTP/1.1 404 Not Found\r\n"
  41. response_headers = "Server:My Server\r\n"
  42. response_body = "The file is not found !"
  43. else:
  44. ##读取内容
  45. file_data = file.read()
  46. file.close()
  47. ##构造响应
  48. response_start_line = "HTTP/1.1 200 OK\r\n"
  49. response_headers = "Server:My Server\r\n"
  50. response_body = file_data.decode("utf-8")
  51. ##拼接返回数据
  52. response = response_start_line+response_headers+'\r\n'+response_body
  53. print("response data响应数据是:",response)
  54. client_socket.send(bytes(response,"utf-8")) ##向客户端返回响应数据
  55. client_socket.close() ##关闭客户端连接
  56. def bind(self,port):
  57. ##绑定端口
  58. self.server_socket.bind(('',port))
  59. def main():
  60. ##主函数
  61. http_server = HTTPServer() ##实例化HTTPServer类
  62. http_server.bind(8000) ##绑定端口
  63. http_server.start() ##调用start方法
  64. if __name__ == '__main__':
  65. main()
  1. <!DOCTYPE html>
  2. <html lang="utf-8">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <meta htt-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>
  8. 明日科技
  9. </title>
  10. <!--Bootstrap core CSS-->
  11. <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
  12. </head>
  13. <body class = 'bs-docs-home'>
  14. <!--Docs master nav-->
  15. <header class = 'navbar navbar-static-top bs-docs-nav' id = 'top'>
  16. <div class = 'container'>
  17. <a href = '/' class = 'navbar-brand'>明日学院</a>
  18. </div>
  19. <nav id = 'bs-navbar' class = 'collapse navbar-collapse'>
  20. <ul class = 'nav navbar-nav'>
  21. <li>
  22. <a href ='https://www.mingrisoft.com/selfCourse.html'>课程</a>
  23. </li>
  24. <li>
  25. <a href ='https://www.mingrisoft.com/book.html'>读书</a>
  26. </li>
  27. <li>
  28. <a href = 'https://www.mingrisoft.com/bbs.html'>社区</a>
  29. </li>
  30. <li>
  31. <a href = 'https://www.mingrisoft.com/servicecenter.html'>服务</a>
  32. </li>
  33. <li>
  34. <a href = '/contact.html'>contact us</a>
  35. </li>
  36. </ul>
  37. </nav>
  38. </header>
  39. <!-- Page Content of course!-->
  40. <main class="bs-docs-masthead" id="content" tabindex="-1">
  41. <div class="container">
  42. <span class="bs-docs-bootion bs-docs-bootion-lg bs-docs-bootion-outline">OS</span>
  43. <p class = 'lead'>Open Source China (OSC) founded in August 2008 is the largest open source community in China. It has more than 3 million registered members and Alexa ranking 837 in the world. OSC provides multiple channels including news, forum, code sharing, blogs, and translation, etc to help local developers study and utilize open soure technology .
  44. In 2013, OSC established a large scale software developement cloud to provide a full stack of SAAS services such as source code management, project management, team collabration, code review, demonstration PAAS platform, etc.
  45. We always spare no efforts to keep providing development cloud services to improve local open source eco-system.</p>
  46. <a href = '/contact.html' class="btn btn-outline-inverse btn-lg">联系我们</a>
  47. </div>
  48. </main>
  49. </body>
  50. </html>

image.png
上面的菜单栏可以链接到对应的超链接。

二、WSGI接口

2.1 介绍

GCI :https://www.yuque.com/lhuan/kb/fedi6h
FastCGI使用进程/线程池来处理一连串的请求,这些进程/线程由FastCGI服务器管理,而不是Web服务器,FastCGI致力于减少网页服务器与CGI程序之间交互的开销,从而使服务器可以同时处理多个网页请求。

https://docs.python.org/3/library/wsgiref.html
wsgi.readthedocs.io
WSGI(Web Server Gateway Interface),服务器网关接口,是Web 服务器和Web 应用程序或框架之间的一种简单又通用的接口。
从层级上来讲要比CGI/FastCGI高级。
WSGI中存在两种角色,接收请求的Server(服务器)和处理请求的Application(应用),它们底层是通过FastCGI沟通的,当Server收到一个请求后,可以通过Socket把环境变量和一个Callback回调函数传给后端Application,Application在完成页面组装后通过Callback把内容返回给Server,最后Server再将响应返回给Client。
image.png

2.2 定义WSGI接口

http://wsgi.tutorial.codepoint.net/application-interface
WSGI应用程序接口被实现为可调用对象、函数,方法,类或带有object.call()方法的实例。

  1. def application (environ,start_response):
  2. ##使用提供的环境字典构建响应主体
  3. response_body = 'Request method: %s' % environ['REQUEST_METHOD']
  4. ##HTTP响应代码和消息
  5. status = '200 OK'
  6. ##客户端期望的HTTP标头
  7. response_headers = [
  8. ('Content-Type', 'text/plain'),
  9. ('Content-Length', str(len(response_body)))
  10. ]
  11. ##发送到服务器
  12. start_response(status, response_headers)
  13. ##返回响应主体
  14. return [response_body]

environ:一个包含所有HTTP请求的字典对象
start_reponse:一个发送HTTP请求响应的函数
environ和start_reponse两个参数需要从服务器获取,application() 函数必须由WSGI服务器来调用。
很多服务器都符合WSGI规范,eg:Nginx服务器、Apache服务器等。

2.3 运行WSGI服务

使用python的wsgiref模块可以不考虑服务器和客户端的连接、数据的发送和接收问题,而专注于逻辑的实现,仅供开发和测试使用。
创建一个views文件夹,里面放置下面的文件
course.html
application.py 用于实现Web应用程序的WSGI处理函数
web_server.py 用于启动WSGI服务器,加载application() 函数

  1. ##index.html
  2. <!DOCTYPE html>
  3. <html lang="utf-8">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <meta htt-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <title>
  9. 明日科技
  10. </title>
  11. <!--Bootstrap core CSS-->
  12. <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
  13. </head>
  14. <body class = 'bs-docs-home'>
  15. <!--Docs master nav-->
  16. <header class = 'navbar navbar-static-top bs-docs-nav' id = 'top'>
  17. <div class = 'container'>
  18. <a href = '/' class = 'navbar-brand'>明日学院</a>
  19. </div>
  20. <nav id = 'bs-navbar' class = 'collapse navbar-collapse'>
  21. <ul class = 'nav navbar-nav'>
  22. <li>
  23. <a href ='/course.html'>课程</a>
  24. </li>
  25. <li>
  26. <a href ='https://www.mingrisoft.com/book.html'>读书</a>
  27. </li>
  28. <li>
  29. <a href = 'https://www.mingrisoft.com/bbs.html'>社区</a>
  30. </li>
  31. <li>
  32. <a href = 'https://www.mingrisoft.com/servicecenter.html'>服务</a>
  33. </li>
  34. <li>
  35. <a href = '/contact.html'>contact us</a>
  36. </li>
  37. </ul>
  38. </nav>
  39. </header>
  40. <!-- Page Content of course!-->
  41. <main class="bs-docs-masthead" id="content" tabindex="-1">
  42. <div class="container">
  43. <span class="bs-docs-bootion bs-docs-bootion-lg bs-docs-bootion-outline">OS</span>
  44. <p class = 'lead'>Open Source China (OSC) founded in August 2008 is the largest open source community in China. It has more than 3 million registered members and Alexa ranking 837 in the world. OSC provides multiple channels including news, forum, code sharing, blogs, and translation, etc to help local developers study and utilize open soure technology .
  45. In 2013, OSC established a large scale software developement cloud to provide a full stack of SAAS services such as source code management, project management, team collabration, code review, demonstration PAAS platform, etc.
  46. We always spare no efforts to keep providing development cloud services to improve local open source eco-system.</p>
  47. <a href = '/contact.html' class="btn btn-outline-inverse btn-lg">联系我们</a>
  48. </div>
  49. </main>
  50. </body>
  51. </html>
  1. ##course.html
  2. <!DOCTYPE html>
  3. <html lang="utf-8">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <meta htt-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <title>
  9. 明日科技
  10. </title>
  11. <!--Bootstrap core CSS-->
  12. <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
  13. </head>
  14. <body class = 'bs-docs-home'>
  15. <!--Docs master nav-->
  16. <header class = "navbar navbar-static-top bs-docs-nav" id="top">
  17. <div class = "container">
  18. <div class = "navbar-header">
  19. <a href = "/"class="navbar-brand">明日学院</a>
  20. </div>
  21. <nav id = "bs-navbar" class = "collapse navbar-collapse">
  22. <ul class = "nav navbar-nav">
  23. <li >
  24. <a href = "/curse.html">课程</a>
  25. </li>
  26. <li >
  27. <a href = "/curse.html">课程</a>
  28. </li>
  29. <li >
  30. <a href = "/curse.html">课程</a>
  31. </li>
  32. <li >
  33. <a href = "/curse.html">课程</a>
  34. </li>
  35. <li >
  36. <a href = "/contact.html">课程</a>
  37. </li>
  38. </ul>
  39. </nav>
  40. </div>
  41. </header>
  42. <!--Page content of course!-->
  43. <main class="bs-docs-masthead" id = "content" tanindex = "-1">
  44. <div class="container">
  45. <div class="jumbotron">
  46. <h1 style = "color: #573e7d;">明日课程</h1>
  47. <p style = "color:antiquewhite">lhuanlhuanlhuan</p>
  48. <p><a class = "btn btn-primary btn-lg " href="http://www.baidu.com" role="button">开始学习</a></p>
  49. </div>
  50. </div>
  51. </main>
  52. </body>
  53. </html>
  1. ##application.py
  2. ##用于实现Web应用程序的WSGI处理函数
  3. def application(environ, start_response):
  4. start_response("200 OK",[('Content-Type','text/html')]) ##响应信息
  5. file_name = environ['PATH_INFO'][1:] or 'index.html' ##获取URL参数
  6. HTML_ROOT_DIR = './views/' ##设置HTML文件目录
  7. try:
  8. file = open(HTML_ROOT_DIR+file_name,'rb') ##打开文件
  9. except IOError:
  10. response = "The file is not found!" ##如果异常,返回404
  11. else:
  12. file_data = file.read() ##读取文件内容
  13. file.close() ##关闭文件
  14. response = file_data.decode('utf-8') ##构造响应数据
  15. return [response.encode('utf-8')] ##返回数据
  1. ##web_server.py
  2. ##从wsgiref模块导入
  3. from wsgiref.simple_server import make_server
  4. ##导入编写的application函数
  5. from application import application
  6. ##创建一个服务器,IP地址为空,端口为8090,处理函数是application
  7. httpd = make_server('',8090,application)
  8. print("Serving HTTP on port 8090...")
  9. ##开始监听HTTP请求
  10. httpd.serve_forever()

image.png点击课程跳转到下面的界面。
image.png
image.png

三、Web框架

3.1 介绍

Web框架是用来简化Web开发的软件框架,常用功能:管理路由、访问数据库、管理会话和Cookines、创建模板来显示HTML、促进代码的重用。

3.2 常用web框架

WSGI(服务器网关接口),是Web服务器和Web应用程序或框架之间的一种简单而通用的接口,只要遵循WSGI接口规则,就可以自主开发Web框架。

3.2.1 Django

使用最广泛,有世界上最大的社区和最多的包,文档完善,提供了一站式的解决方案,包括缓存、ORM、管理后台、验证、表单处理等,使得开发复杂的数据库驱动的网站变得简单,但是Django系统耦合度较高,替换掉内置的功能比较麻烦。

3.2.2 Flask

Flask是一个轻量级的Web应用框架,把Werkzeug或Jinja黏合再一起,很容器被拓展,有很完善的文档,容易使用。
使用装饰器来定义路径。

3.2.3 Bottle

是一个新的微框架,只有4500行代码,除了Python标准库之外,没有其他的依赖。
文档详细,使用装饰器来定义路径。

3.2.4 Tornado

Tornado不只是一个框架,还是一个Web服务器。
一开始为FriendFeed开发,后来在2009年也给Facebook使用,是为了解决实时服务诞生的,使用了异步阻塞IO,运行速度非常快。