Python全栈 项目(HTTPServer、PiP使用)
2021-07-11 12:05
标签:__name__ 前端 设置 search read 方法 ioerror 返回 sys Python全栈 项目(HTTPServer、PiP使用) 标签:__name__ 前端 设置 search read 方法 ioerror 返回 sys 原文地址:https://www.cnblogs.com/ParisGabriel/p/9551501.htmlimport 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
# 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() #启动服务器
上一篇:15、python 函数
文章标题:Python全栈 项目(HTTPServer、PiP使用)
文章链接:http://soscw.com/index.php/essay/103695.html