python WEB 开发
2021-03-09 11:27
阅读:735
YPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
标签:指针 temp return ora flat sockets ken exp linux
socketserver
重写处理函数
import http.server
import socketserver
import os,io
import urllib
from http import HTTPStatus
import email.utils
import datetime
import json
import data
PORT = 8000
class do_Handler(http.server.SimpleHTTPRequestHandler):
def do_app(self):
pass
def global_request(self):
#print("____________________global_request______start")
#print("self.requestline: ",self.requestline)
path=urllib.parse.unquote(self.path)
#print("path: ",path)
self.canshu={}
path=path.split("?")
if len(path)>1:
for i in path[1].split("&"):
self.canshu[i.split("=")[0]]=i.split("=")[1]
#print("canshu: ",canshu)
#print("self.request: ",self.request)
#print("self.command: ",self.command)
if self.command=="POST":
#print("POST_____________")
#print("int(self.headers[‘content-length‘]): ",int(self.headers[‘content-length‘]))
req_datas = self.rfile.read(int(self.headers[‘content-length‘])) #重点在此步!
#print("self.rfile.read(int(self.headers[‘content-length‘])): ",req_datas.decode())
for i in req_datas.decode().split("&"):
self.canshu[i.split("=")[0]]=i.split("=")[1]
#print("canshu: ",canshu)
#print("POST_____________end")
#print("canshu: ",self.canshu)
#print("self.client_address: ",self.client_address)
#print("self.server: ",self.server)
#print("self.headers: ",self.headers)
#print("____________________global_request______end")
"""
____________________global_request______start
self.requestline: POST /test/test/ttt HTTP/1.1
path: /test/test/ttt
canshu: {}
self.request:
self.command: POST
POST_____________
int(self.headers[‘content-length‘]): 32
self.rfile.read(int(self.headers[‘content-length‘])): username=postman&password=123456
canshu: {‘username‘: ‘postman‘, ‘password‘: ‘123456‘}
POST_____________end
self.client_address: (‘127.0.0.1‘, 52512)
self.server:
self.headers: Host: localhost:8000
Connection: keep-alive
Content-Length: 32
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Origin: chrome-extension://ojcehbbmmmlmlobapckckmgnhdmpmacc
Sec-Fetch-Site: none
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: _xsrf=2|21e063b3|84bfebbd08d32087174eee4a4d4d33ec|1607150430; username-localhost-8888="2|1:0|10:1607150550|23:username-localhost-8888|44:NjU1NzNlODUwYjQ0NDVmYzhmYzc3Zjg2MjQ1OGYzNTQ=|f787f4c6fb32f672faa8e72fa7bf68e7c8505085e331b7ec4915dd43ea7a533a"
____________________global_request______end
"""
return self.canshu
def do_GET(self):
self.global_request()
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
#self.do_app()
for i in self.urls.keys():
if i==self.path.split(‘?‘,1)[0]:
app=getattr(self,self.urls[i])
app()
def send_head(self):
path = self.translate_path(self.path)
#print("path",path,self.path)
f = None
if os.path.isdir(path):
pass#return self.list_directory(path)
if not os.path.isfile(path):
return None
ctype = self.guess_type(path)
try:
if os.path.exists(path):
if os.path.splitext(path)[1]==".py":
f = open(path, ‘rb‘)
else:
f = open(path, ‘rb‘)
except OSError:
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
return None
try:
fs = os.fstat(f.fileno())
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", ctype)
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified",
self.date_time_string(fs.st_mtime))
self.end_headers()
return f
except:
f.close()
raise
def do_POST(self):
self.global_request()
f = self.send_head()
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()
#self.do_app()
for i in self.urls.keys():
if i==self.path.split(‘?‘,1)[0]:
app=getattr(self,self.urls[i])
app()
class app(do_Handler):
urls={
"/test":"test",
"/":"hello",
"/py":"do_py",
"/data_json":"data_json"
}
def hello(self):
self.send_response(200)
self.send_header(‘Content-type‘, ‘text/html‘)
self.end_headers()
self.wfile.write(b"hello hello()\r\n")
"""f = io.BytesIO()
f.write(b"hello world\r\n")
f.seek(0)
if f:
try:
self.copyfile(f, self.wfile)
finally:
f.close()"""
def do_py(self):
self.send_response(200)
self.send_header(‘Content-type‘, ‘text/html‘)
self.end_headers()
self.wfile.write(b"hello do_py()\r\n")
def test(self):
print(self.canshu)
self.send_response(200)
self.send_header(‘Content-type‘, ‘text/html‘)
self.end_headers()
#self.wfile.write(b"hello test()\r\n")
self.wfile.write(json.dumps(self.canshu).encode("utf-8"))
def data_json(self):
self.send_response(200)
self.send_header(‘Content-type‘, ‘text/html‘)
self.end_headers()
self.wfile.write(data.get_dataB(self.canshu))
with socketserver.TCPServer(("", PORT), app) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
"""class tes:
def do_test(self):
print("do_test():")
method=getattr(tes,"do_test")
method(tes)"""
json数据通讯
knowledge={
"编程":{
"c":["指针","数组","函数"],
"python":{"包":["Tkinter","pandas"]},
"网页":["js","css","html"],
"算法":{"排序算法":["冒泡","堆排","PID"]},
"机器学习":"Tensorflow"
},
"计算机":{"软件":{"系统":["linux","Windows"]},
"硬件":{"单片机":["stc51","esp8266"]},
"网络":["FTP","HTTP"]},
"生活":{"兴趣":"航模","感想":["爱情","生活","理想"]}
}
import json
import md_html
knowledge_data1=[]
def bianli(knowledge,tab):
for i in knowledge.keys():
print(tab*"\t",i,type(i),tab)
if type(knowledge[i])==dict:
bianli(knowledge[i],tab+1)
if type(knowledge[i])==list:
for ii in knowledge[i]:
print((tab+1)*"\t",ii,type(ii),tab)
elif type(knowledge[i])==str:
print((tab+1)*"\t",knowledge[i],type(knowledge[i]),tab)
def bianli1(knowledge,tab):
for i in knowledge.keys():
#print(tab*"\t",i,type(i),tab)
try:
knowledge_data1[tab].append(i)
except IndexError:
knowledge_data1.append([])
knowledge_data1[tab].append(i)
if type(knowledge[i])==dict:
bianli1(knowledge[i],tab+1)
if type(knowledge[i])==list:
for ii in knowledge[i]:
#print((tab+1)*"\t",ii,type(ii),tab+1)
try:
knowledge_data1[tab+1].append(ii)
except IndexError:
knowledge_data1.append([])
knowledge_data1[tab+1].append(ii)
elif type(knowledge[i])==str:
#print((tab+1)*"\t",knowledge[i],type(knowledge[i]),tab+1)
try:
knowledge_data1[tab+1].append(knowledge[i])
except IndexError:
knowledge_data1.append([])
knowledge_data1[tab+1].append(knowledge[i])
md_data={}
with open("data.json","r",encoding="utf-8") as f:
md_data=json.load(f)
def get_dataB(canshu):
c=canshu["json"]
if c=="nr2_0":
return str(knowledge.keys())[10:-1].replace("‘","\"").encode("utf-8")
if c=="nr2_1":
global knowledge_data1
knowledge_data1=[]
bianli1(knowledge,0)
return str(knowledge_data1).replace("‘","\"").encode("utf-8")
if c=="nr_ml":
return str(md_data["blml"].keys())[10:-1].replace("‘","\"").encode("utf-8")
if c=="mdhtml":
return md_html.create_html(canshu["data"]).encode("utf-8")
html重构
import markdown
md=markdown.Markdown(extensions=[‘markdown.extensions.fenced_code‘,‘markdown.extensions.tables‘])#Markdown 类实例
#重复调用它的 convert() 和 reset() 函数
"""print(html1)
md.reset()"""
def md_Z_html(canshu):
with open(canshu,‘r‘,encoding="utf-8", errors="xmlcharrefreplace") as f:
text=f.read()
md.reset()
html = md.convert(text)
return html
h1="""
"""
style="""
"""
h2="""
Index.html
"""
js1="""
"""
h3="""
"""
def create_html(cansh):
mdhtml=md_Z_html(cansh)
return h1+style+h2+mdhtml+js1+h3
"""with open(‘test.html‘,‘w‘,encoding="utf-8") as f:
f.write(h1+style+h2+mdhtml+js1+h3)"""
python WEB 开发
标签:指针 temp return ora flat sockets ken exp linux
原文地址:https://www.cnblogs.com/createhm/p/14181541.html
上一篇:python——切片
下一篇:C语言输入时 EOF问题
评论
亲,登录后才可以留言!