case1:

import socketdef handle_request(conn):  # 处理数据返回buff = conn.recv(1024)print(buff)conn.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8"))  # HTTP规范html = """<html><head></head><body><h1> hello my world </h1></body><html>"""conn.send(html.encode("utf8"))def main():sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.bind(("localhost", 8000))  # 绑定Ip,端口sock.listen(5)  # 启动监听print("启动服务器,等待客户端连接……")while True:conn, address = sock.accept()handle_request(conn)conn.close()if __name__ == "__main__":main()

case2:

import socketdef handle_request(conn):  # 处理数据返回buff = conn.recv(1024)print(buff)conn.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8"))  # HTTP规范# html = """#     <html>#         <head></head>#         <body>#             <h1> hello my world </h1>#         </body>#     <html># """with open("demo.html") as f:html = f.read()conn.send(html.encode("utf8"))def main():sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.bind(("localhost", 8000))  # 绑定Ip,端口sock.listen(5)  # 启动监听print("启动服务器,等待客户端连接……")while True:conn, address = sock.accept()handle_request(conn)conn.close()if __name__ == "__main__":main()

再新建一个html文件,文件名为“demo.html”,里面代码如下:

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<body><h1> hello my beautiful world.</h1>
</body>
</html>

运行main(),






case1:从Python文档,搜索WEGI,复制Example代码:

在make_server()函数,补全IP地址,这里用"0.0.0.0"即任何的IP过来都可以访问

with make_server('0.0.0.0', 8000, hello_world_app) as httpd:print("Serving on port 8000...")

然后run

from wsgiref.simple_server import make_server# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):# print("请求:environ", environ)  # 查看环境变量environ的值,environ是一个字典for k, v in environ.items():   # 解包环境变量environ,更方便地看值print(k, ":", v)status = '200 OK'  # HTTP Statusheaders = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headersstart_response(status, headers)# The returned object is going to be printedreturn [b"Hello World"]with make_server('0.0.0.0', 8000, hello_world_app) as httpd:print("Serving on port 8000...")# Serve until process is killedhttpd.serve_forever()

截取environ的部分值,如下:

case2:在上面case1里加一句代码,

    query_string = environ.get("QUERY_STRING")print(query_string)

然后run,启动WSGI,然后到浏览器地址栏端口号后面,加一些内容,然后回车:

可以看到控制台就取到了浏览器的url值

from wsgiref.simple_server import make_server# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):# print("请求:environ", environ)  # 查看环境变量environ的值# for k, v in environ.items():   # 解包环境变量environ,更方便地看值#     print(k, ":", v)query_string = environ.get("QUERY_STRING")print(query_string)status = '200 OK'  # HTTP Statusheaders = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headersstart_response(status, headers)# The returned object is going to be printedreturn [b"Hello World"]with make_server('0.0.0.0', 8000, hello_world_app) as httpd:print("Serving on port 8000...")# Serve until process is killedhttpd.serve_forever()

case3:在上面case1里加一句代码,

    path_info = environ.get("PATH_INFO", "未找到")print(path_info)

然后run,启动WSGI,然后到浏览器地址栏端口号后面,加一些内容,然后回车:

可以看到控制台就取到了浏览器的url值

from wsgiref.simple_server import make_server# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):# print("请求:environ", environ)  # 查看环境变量environ的值# for k, v in environ.items():   # 解包环境变量environ,更方便地看值#     print(k, ":", v)# query_string = environ.get("QUERY_STRING")# print(query_string)path_info = environ.get("PATH_INFO", "未找到")print(path_info)status = '200 OK'  # HTTP Statusheaders = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headersstart_response(status, headers)# The returned object is going to be printedreturn [b"Hello World"]with make_server('0.0.0.0', 8000, hello_world_app) as httpd:print("Serving on port 8000...")# Serve until process is killedhttpd.serve_forever()

引申:case1和case2,我们在浏览器的各种行为能被localhost所解析,即当我们在浏览器URL输入不同的内容,WSGI传输URL到localhost寻找相应的内容,如果找到了就给我们返回结果。正如,点击百度首页的新闻,跳转到新闻页面;点击地图,跳转到地图页面。

WSGI实现页面访问

首先,在pycharm里新建三个HTML文件,



然后在主程序中添加调用的代码,

from wsgiref.simple_server import make_server# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).def index():with open("index.html", "rb") as f:index_info = f.read()return [index_info]def login():with open("login.html", "rb") as f:login_info = f.read()return [login_info]def notfund():with open("notfund.html", "rb") as f:notfund_info = f.read()return [notfund_info]def hello_world_app(environ, start_response):# print("请求:environ", environ)  # 查看环境变量environ的值# for k, v in environ.items():   # 解包环境变量environ,更方便地看值#     print(k, ":", v)# query_string = environ.get("QUERY_STRING")# print(query_string)# path_info = environ.get("PATH_INFO", "未找到")# print(path_info)status = '200 OK'  # HTTP Statusheaders = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headersstart_response(status, headers)path = environ.get("PATH_INFO")if path == "/index":return index()elif path == "/login":return login()else:return notfund()with make_server('0.0.0.0', 8000, hello_world_app) as httpd:print("Serving on port 8000...")# Serve until process is killedhttpd.serve_forever()

然后到浏览器,在localhost:8000后面输入

回车,浏览器即显示我们预先在index.html里的内容



遗留问题:

    path = environ.get("PATH_INFO")if path == "/index":return index()elif path == "/login":return login()else:return notfund()

这里根据不同的路由返回对应的页面,是在代码里写死的,即硬编码,如果页面很多的话,就需要写很多映射的规则,有没有什么方式对这个路由进行改进呢?

PS: source, bilibili

Django:Web框架,WSGI,WSGI实现浏览器与服务器通信,路由route,WSGI实现页面访问相关推荐

  1. Django Web框架教学笔记-1

    <Django Web框架教学笔记> 目录 文章目录 <Django Web框架教学笔记> 目录 Django框架的介绍 Django的安装 Django框架开发 创建项目的指 ...

  2. Django web框架学习之旅(4)

    <Django Web 框架> 目录 Django shell的使用 admin 后台数据库管理 自定义后台管理数据表 修改后台Models的展现形式 模型管理器类 数据库表管理 数据表关 ...

  3. Django web 框架学习之旅(3)

    <Django Web 框架> 目录 静态文件 Django中的应用 - app 什么是应用(app) 创建应用app Django应用的结构组成 数据库 和 模型 Django下使用my ...

  4. Django Web框架的使用

    1.前言 Django是基于Python的重量级开源Web框架.Django拥有高度定制的ORM和大量的API,简单灵活的视图编写.优雅的url.适用于快速开发的模板以及强大的管理后台. Django ...

  5. Django web框架

    Web框架 web 框架本质  -  Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. HTTP协议 HTTP协议介绍HTTP协议对收发消息的格式要求每个HTTP ...

  6. Web框架中间件插件BurpSuite浏览器被动主动探针[武装浏览器]

    好东西 浏览器插件 Penetration Testing Kit 这个工具他集成了中间件,等版本信息,漏洞信息,url,标识头等信息,WAF/CDN识别,密匙等信息,多种信息的功能上集合的插件 UR ...

  7. 在IIS上部署基于django WEB框架的python网站应用

    django是一款基于python语言的WEB开源框架,本文给出了如何将基于django写的python网站部署到window的IIS上. 笔者的运行环境: Window xp sp3 IIS 5.1 ...

  8. Django web框架学习笔记

    Django1.11.4 版本支持Python3.5 3.6 1.Django安装 pip install django==1.11.4 2.验证是否安装成本 python import django ...

  9. python Django web 框架 (二十)之ORM

    Django之模型层第一篇:单表操作 一 ORM简介 我们在使用Django框架开发web应用的过程中,不可避免地会涉及到数据的管理操作(如增.删.改.查),而一旦谈到数据的管理操作,就需要用到数据库 ...

最新文章

  1. (拆点+最小路径覆盖) bzoj 2150
  2. hp-ux 11.23挂载ISO文件
  3. 安卓高手之路之图形系统(6)requestLayout的流程
  4. ​网页图表Highcharts实践教程标之添加题副标题版权信息
  5. python数据分析年薪百万_如何成为一个年薪 50 万以上的数据分析师?
  6. 关于ewebeditor行距
  7. Config Sharepoint 2013 Workflow PowerShell Cmdlet
  8. 3----结构体中使用柔性数组
  9. 【WebRTC---序篇】(一)为什么要使用WebRTC
  10. c++ map 多线程同时更新值 崩溃_深入理解并发安全的 sync.Map
  11. find_first_of()和 find_last_of() 【获取路径、文件名】
  12. (2环境架设)从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练
  13. java 怎么调用clojure_如何从Java调用Clojure宏?
  14. Windows域控设置IE主页 默认打开百度 【全域策略生效】
  15. sed 、awk用法
  16. form表单那点事儿(下) 进阶篇
  17. 数据库基础知识(思维导图)
  18. 未来房价涨or跌?大数据告诉你
  19. 【云栖大会精华汇】2017杭州云栖大会主论坛、分论坛在内的100+视频分享
  20. 高级Android开发进阶之路,你需要掌握的几个关键技术!

热门文章

  1. Unity UGUI实现鼠标拖动图片
  2. vue-router(2.0)
  3. JAVA的Date类与Calendar类
  4. WebDev.WebServer.exe遇到问题需要关闭
  5. 谈谈对水晶报表的看法
  6. oracle 自治事物,自治事务 - 努力创造未来! - BlogJava
  7. java中的等待_Java中更好的等待语法
  8. python 给类添加属性_python – 如何动态添加属性到类中?
  9. java聊天系统异常问题_【图片】写的socket编程实现窗口聊天出现空指针错误 在自己电脑没事【java吧】_百度贴吧...
  10. java stdout库_Java重写StdOut并将日语写入文件