Python全栈 项目(HTTPServer、PiP使用)
import gevent
# 在socket导入之前使用
from gevent import monkey
monkey.patch_all()
from socket import *
from time import ctime
def server(port):
s = socket()
s.bind(('0.0.0.0',port))
s.listen(5)
while True:
c,addr = s.accept()
print("Connect from",addr)
gevent.spawn(handler,c)
#处理客户端请求
def handler(c):
while True:
data = c.recv(1024).decode()
if not data:
break
print("Receive:",data)
c.send(ctime().encode())
c.close()
if __name__ == "__main__":
server(8888)
class CallTest(object):
def __call__(self,a,b):
print("This is call test")
print("a =",a,"b =",b)
test = CallTest()
test(1,2)
#coding=utf-8 '''
module: HTTPServer.py
name : Paris
time : 2018-8-28
功能 :httpserver部分
modules:
Python3.5 、socket、sys
threading、re、setting
'''
from socket import *
import sys
from threading import Thread
import re
from setting import * #处理http请求类
class HTTPServer(object):
def __init__(self,application):
self.sockfd = socket()
self.sockfd.setsockopt\
(SOL_SOCKET,SO_REUSEADDR,1)
#获取模块接口
self.application = application def bind(self,host,port):
self.host = host
self.port = port
self.sockfd.bind((self.host,self.port))
#启动服务器
def serve_forever(self):
self.sockfd.listen(10)
print("Listen the port %d..."%self.port)
while True:
connfd,addr = self.sockfd.accept()
print("Connect from",addr)
handle_client = Thread\
(target = self.client_handler,\
args = (connfd,))
handle_client.setDaemon(True)
handle_client.start() def client_handler(self,connfd):
#接收浏览器request
request = connfd.recv(4096)
#可以分析请求头和请求体
request_lines = request.splitlines()
#获取请求行
request_line = request_lines[0].decode('utf-8') #获取请求方法和请求内容
pattern = r'(?P<METHOD>[A-Z]+)\s+(?P<PATH_INFO>/\S*)'
try:
env = re.match(pattern,request_line).groupdict()
except:
response_headlers = "HTTP/1.1 500 SERVER ERROR\r\n"
response_headlers += "\r\n"
response_body = "server error"
response = response_headlers + response_body
connfd.send(response.encode()) # method,filename = \
# re.findall(r'^([A-Z]+)\s+(/\S*)', request_line)[0] #将解析内容合成字典给web frame使用
# env = {'METHOD':method,'PATH_INFO':filename}
# print(env) #将env给Frame处理,得到返回内容
response = self.application(env) #发送给客户端
if response:
connfd.send(response.encode())
connfd.close() if __name__ == "__main__":
#将要使用的模块导入进来
sys.path.insert(1,MODULE_PATH)
m = __import__(MODULE)
application = getattr(m,APP) httpd = HTTPServer(application)
httpd.bind(HOST,PORT)
httpd.serve_forever()
setting:
# setting.py #httpserver配置文件
HOST = '0.0.0.0'
PORT = 8000 #设置要使用的模块和应用
MODULE_PATH = "." #设置Frame模块路径
MODULE = 'WebFrame' #设置模块名称
APP = 'app' #使用的应用
#coding=utf-8
from views import *
'''
WebFrame.py
WebFrame 框架
用于处理server解析请求
''' #设置静态文件夹路径
STATIC_DIR = "./static" #应用
class Application(object):
def __init__(self,urls):
self.urls = urls def __call__(self,env):
method = env.get("METHOD",'GET')
path = env.get("PATH_INFO",'/') #请求内容 if method == 'GET':
if path == '/' or path[-5:] == '.html':
response = self.get_html(path)
else:
response = self.get_data(path)
elif method == 'POST':
pass return response def get_html(self,path):
if path == '/':
get_file = STATIC_DIR + "/index.html"
else:
get_file = STATIC_DIR + path
try:
fd = open(get_file)
except IOError :
#没有找到请求网页
responseHeaders = "HTTP/1.1 404 not found\r\n"
responseHeaders += '\r\n'
response_body = "Sorry,the page not found"
else:
responseHeaders = "HTTP/1.1 200 OK\r\n"
responseHeaders += '\r\n'
response_body = fd.read()
finally:
response = responseHeaders + response_body
return response def get_data(self,path):
for url,handler in self.urls:
if path == url:
response_headers = "HTTP/1.1 200 OK\r\n"
response_headers += '\r\n'
response_body = handler()
return response_headers + response_body response_headers = "HTTP/1.1 404 not found\r\n"
response_headers += '\r\n'
response_body = "Sorry ,not found the data"
return response_headers + response_body urls = [
('/time',show_time),
('/hello',say_hello),
('/bye',say_bye),
] app = Application(urls)
# views.py
# 具体处理模块
import time def show_time():
return time.ctime() def say_hello():
return "hello world" def say_bye():
return "Good Bye"
try:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
except ImportError:
from http.server import BaseHTTPRequestHandler,HTTPServer class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.headers) #请求头
print(self.path) #请求内容
fd = open('test.html','rb')
content = fd.read()
#组织response
self.send_response(200)
self.send_header('Content-Type','text/html')
self.end_headers()
self.wfile.write(content) def do_POST(self):
pass address = ('0.0.0.0',8080)
#生成httpserver对象
httpd = HTTPServer(address,RequestHandler)
httpd.serve_forever() #启动服务器
Python全栈 项目(HTTPServer、PiP使用)的更多相关文章
- Python全栈 项目(电子词典、协程、pdb调试)
后面我就不截图了 大家还是看原文吧 https://yq.aliyun.com/articles/629534 . ................. ...
- 老男孩Python全栈第2期+课件笔记【高清完整92天整套视频教程】
点击了解更多Python课程>>> 老男孩Python全栈第2期+课件笔记[高清完整92天整套视频教程] 课程目录 ├─day01-python 全栈开发-基础篇 │ 01 pyth ...
- Python全栈开发【面向对象进阶】
Python全栈开发[面向对象进阶] 本节内容: isinstance(obj,cls)和issubclass(sub,super) 反射 __setattr__,__delattr__,__geta ...
- Python全栈开发【面向对象】
Python全栈开发[面向对象] 本节内容: 三大编程范式 面向对象设计与面向对象编程 类和对象 静态属性.类方法.静态方法 类组合 继承 多态 封装 三大编程范式 三大编程范式: 1.面向过程编程 ...
- 战争热诚的python全栈开发之路
从学习python开始,一直是自己摸索,但是时间不等人啊,所以自己为了节省时间,决定报个班系统学习,下面整理的文章都是自己学习后,认为重要的需要弄懂的知识点,做出链接,一方面是为了自己找的话方便,一方 ...
- Win10构建Python全栈开发环境With WSL
目录 Win10构建Python全栈开发环境With WSL 启动WSL 总结 对<Dev on Windows with WSL>的补充 Win10构建Python全栈开发环境With ...
- python 全栈开发,Day117(popup,Model类的继承,crm业务开发)
昨日内容回顾 第一部分:权限相关 1. 权限基本流程 用户登录成功后获取权限信息,将[权限和菜单]信息写入到session. 以后用户在来访问,在中间件中进行权限校验. 为了提升用户体验友好度,在后台 ...
- python 全栈开发,Day99(作业讲解,DRF版本,DRF分页,DRF序列化进阶)
昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确. - API (IOS,安卓,PC,微信小程序...) - vue.js等框架编写前端时,会比之前写jQuery ...
- python 全栈开发,Day98(路飞学城背景,django ContentType组件,表结构讲解)
昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确. - API (IOS,安卓,PC,微信小程序...) - vue.js等框架编写前端时,会比之前写jQuery ...
随机推荐
- Linux tmux 使用指南
注意:本文内容适用于 Tmux 2.3 及以上的版本,但是绝大部分的特性低版本也都适用,鼠标支持.VI 模式.插件管理在低版本可能会与本文不兼容. Tmux 快捷键 & 速查表 启动新会话: ...
- 前端面试题(copy)
前端开发面试知识点大纲: HTML&CSS: 对Web标准的理解.浏览器内核差异.兼容性.hack.CSS基本功:布局.盒子模型.选择器优先级及使用.HTML5.CSS3.移动端适应. Jav ...
- 锐捷交换机实验案例:vlan间互访的配置与验证
组网需求: 1.如下图所示,某用户内网被划分为VLAN 10.VLAN 20.VLAN 30,以实现相互间的2 层隔离: 2.3 个VLAN 对应的IP 子网分别为192.168.10.0/24 .1 ...
- 『C++』Temp_2018_12_26_02
#include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> ...
- detach()之大坑:detach会引起局部变量失效引起线程对内存的非法访问题。
detach()之大坑:detach会引起局部变量失效引起线程对内存的非法访问题.一:传递临时对象作为线程参数(1.1)要避免的陷阱(解释一)(1.2)要避免的陷阱(解释一)事实一:只要用临时构造的A ...
- Mysql存储引擎myisam与inndb的区别?
最近在研究Mysql存储引擎这块,说白了就是如何存储数据.如何为存储的数据建立索引和如何更新.查询数据等技术的实现方法,在此做一个大概总结: 其实在工作中用的最多也就是MYISAM和INNODB,IN ...
- ES基础知识与高频考点梳理
知识点梳理目录列表 变量类型 JS的数据类型分类和判断 值类型和引用类型 原型与原型链(继承) 原型和原型链的定义 继承写法 作用域和闭包 执行上下文 this 闭包是什么 异步 同步VS异步 异步和 ...
- eval函数的作用
eval函数的作用是去掉字符串最外侧的引号,并按照Python的语法执行去掉引号后的字符内容. [实例1] x=eval("12+36")print(x) #结果为48此例中,去 ...
- Python3 urllib 与 Python2 urllib的变化
Infi-chu: http://www.cnblogs.com/Infi-chu/ Py2.x: Urllib库 Urllin2库 Py3.x: Urllib库 变化: 在Pytho2.x中使用im ...
- c语言数据结构(一)
第一章 绪论 一.数据与数据结构 数据:所有能被输入到计算机中,且被计算机处理的符号的集合计算机操作的对象的总称.是计算机处理的信息的某种特定的符号表示形式. 数据元素:数据中的一个“个体”,数据 ...