#!/usr/bin/env python
# -*- coding: utf- -*- import socket
import select class MyRequest:
"""
从请求头请求体获取的信息封装的request对象中
"""
def __init__(self,data):
header_body=data.decode('utf-8')
header_str,body_str=header_body.split('\r\n\r\n')
header_list=header_str.split('\r\n')
method,url,protocal=header_list[].split(' ') header_dict={} for i in range(,len(header_list)):
k,v =header_list[i].split(':',)
header_dict[k]=v self.method=method
self.url=url
self.headers=header_dict class MyResponse:
"""
处理服务端要返回给浏览器的数据,相当于HTTPResponse或render
"""
def __init__(self,data):
self.data=data
self.base_data='HTTP/1.1 200 OK\r\n\r\n<html><head><meta charset="UTF-8"></head><body><h1>{0}</h1></body></html>'
def myrender(self):
return self.base_data.format(self.data).encode('utf-8') # 下面2个简单的视图函数
def index(request):
return MyResponse('index page').myrender() def login(request):
return MyResponse('login page').myrender() # 路由系统
routers=[
['/index',index],
['/login',login],
] sk=socket.socket()
sk.setblocking(False)
sk.bind(('127.0.0.1',))
sk.listen() inputs=[sk,] # 套接字接听对象,是socket或conn的一个或多个 while True:
rList,wList,eList=select.select(inputs,[],[],)
# 读,写,错误 3个列表
for server in rList:
if server==sk:
conn,addr=sk.accept()
inputs.append(conn)
else:
header_body_bytes=server.recv()
request=MyRequest(header_body_bytes)
view_method=None
for view_function in routers:
# 根据请求url通过路由交给不同的视乎函数处理
if request.url == view_function[]:
view_method=view_function[]
break
if not view_method:
response=MyResponse('').myrender()
else:
response=view_method(request)
server.sendall(response)
inputs.remove(server)
server.close()
#!/usr/bin/env python
# -*- coding: utf-8 -*- from wsgiref.simple_server import make_server # 下面2个视图函数
def indexfunc(request):
f=open(r'templates/index.html','rb')
data=f.read()
f.close()
print('执行了indexfunc')
return [data] def loginfunc(request):
request_method=request.get('REQUEST_METHOD')
if request_method=='GET':
f = open(r'templates/login.html', 'rb')
data = f.read()
f.close()
print('执行了login')
return [data] # 路由
routers=[
('/index',indexfunc),
('/login',loginfunc),
] drouters=dict(routers) def application(environ,start_response):
start_response('200 ok',[('Content-Type','text/html')])
path=environ.get('PATH_INFO')
print(path)
if drouters.get(path):
print('yeah')
return drouters.get(path)(environ)
else: return [b'<h1>404<h1>'] t=make_server('127.0.0.1',8989,application)
t.serve_forever()

  

写一个Python 1、通过select实现的最简单的web框架2、通过wsgiref实现的web框架的更多相关文章

  1. 写一个python的服务监控程序

    写一个python的服务监控程序 前言: Redhat下安装Python2.7 rhel6.4自带的是2.6, 发现有的机器是python2.4. 到python网站下载源代码,解压到Redhat上, ...

  2. 如何手动写一个Python脚本自动爬取Bilibili小视频

    如何手动写一个Python脚本自动爬取Bilibili小视频 国庆结束之余,某个不务正业的码农不好好干活,在B站瞎逛着,毕竟国庆嘛,还让不让人休息了诶-- 我身边的很多小伙伴们在朋友圈里面晒着出去游玩 ...

  3. 写一个python脚本监控在linux中的进程

    在虚拟机中安装Linux中的CentOS7系统 https://baijiahao.baidu.com/s?id=1597320700700593557&wfr=spider&for= ...

  4. 写一个Python的windows服务

    1. 安装pywin32和pyinstaller pip install pywin32 pip install pyinstaller 2.写一个服务Demo # -*- coding: utf-8 ...

  5. 写一个python 爬虫爬取百度电影并存入mysql中

    目标是利用python爬取百度搜索的电影 在类型 地区 年代各个标签下 电影的名字 评分 和图片连接 以及 电影连接 首先我们先在mysql中建表 create table liubo4( id in ...

  6. 如何写一个Python万能装饰器,既可以装饰有参数的方法,也可以装饰无参数方法,或者有无返回值都可以装饰

    Python中的装饰器,可以有参数,可以有返回值,那么如何能让这个装饰器既可以装饰没有参数没有返回值的方法,又可以装饰有返回值或者有参数的方法呢?有一种万能装饰器,代码如下: def decorate ...

  7. 写一个python小程序

    在windows环境下进行操作 window+R 输入cmd  创建一个文件夹 mkdir pytxt 创建一个py文件 py.py  用notepad或者记事本等工具进行编辑 或 首先声明pytho ...

  8. Hello Python!用 Python 写一个抓取 CSDN 博客文章的简单爬虫

    网络上一提到 Python,总会有一些不知道是黑还是粉的人大喊着:Python 是世界上最好的语言.最近利用业余时间体验了下 Python 语言,并写了个爬虫爬取我 csdn 上关注的几个大神的博客, ...

  9. 手写一个python迭代器

    分析 我们都知道一个可迭代对象可以通过iter()可以返回一个迭代器. 如果想要一个对象称为可迭代对象,即可以使用for,那么必须实现__iter __()方法. 在一个类的实例对象想要变成迭代器,就 ...

随机推荐

  1. 【Android Studio安装部署系列】三、Android Studio项目目录结构

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 简单介绍下Android studio新建项目的目录结构. 常用项目结构类型 在Android Studio中,提供了以下几种项目结 ...

  2. 理解 Linux 中 `ls` 的输出

    ls 的输出会因各 Linux 版本变种而略有差异,这里只讨论一般情况下的输出. 下面是来自 man page 关于 ls 的描述: $ man ls ls - list directory cont ...

  3. redis使用场景和java测试案例

    redis数据结构和使用场景 strings lists sets sort sets hashes strings token session validateCode 分布锁 lists 最近联系 ...

  4. spring aop中pointcut表达式完整版

    spring aop中pointcut表达式完整版 本文主要介绍spring aop中9种切入点表达式的写法 execute within this target args @target @with ...

  5. httpclient绕过证书验证进行HTTPS请求

    http请求是我们常用的一种web应用的应用层协议,但是由于它的不安全性,现在正在逐渐向https协议过渡.https协议是在http的基础上进行了隧道加密,加密方式有SSL和TLS两种.当serve ...

  6. Vmware安装CentOs7+gitlab(一)

    本篇文章主要介绍了VMware安装Centos7超详细过程(图文),具有一定的参考价值,感兴趣的小伙伴们可以参考一下 1.软硬件准备 软件:推荐使用VMwear,我用的是VMwear 12 镜像:Ce ...

  7. PHP制作个人博客-广告位添加与调用 推荐文章数据调取

    上一节博客的导航我们已经动态调取,这一节我们主讲一下如何根据页面布局,后台添加广告位,及模板上动态调取广告.博客推荐文章的数据调用. 首先我们在云码博客的后台添加10条左右的测试数据,thinkcmf ...

  8. js实现浏览器调用电脑的摄像头拍照

    <!DOCTYPE html> <html lang="en"> <head> <style> * { margin: ; padd ...

  9. Dotnetcore 开发速记

    1.System.InvalidOperationException:"Internal connection fatal error." 全球固定模式,坑爹 https://gi ...

  10. Windows下建立ArcGIS Server集群

    原创文章,转载须标明出处自: http://www.cnblogs.com/gisspace/p/8269525.html -------------------------------------- ...