Python基于 BaseHTTPRequestHandler 创建简单Web服务

2024-03-27 05:44

本文主要是介绍Python基于 BaseHTTPRequestHandler 创建简单Web服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

启动一个最基础的 WEB 服务

创建文件 server.py

# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServerhostName = "localhost"
serverPort = 8080class MyServer(BaseHTTPRequestHandler):def do_GET(self):self.send_response(200)self.send_header("Content-type", "text/html")self.end_headers()self.wfile.write(bytes("<html><body><p>Request: %s</p></body></html>" % self.path, "utf-8"))if __name__ == "__main__":webServer = HTTPServer((hostName, serverPort), MyServer)print("Server started http://%s:%s" % (hostName, serverPort))try:webServer.serve_forever()except KeyboardInterrupt:passwebServer.server_close()print("Server stopped.")

启动命令

python3 server.py

区分访问路径

do_GET方法内, 使用 self.path 变量区分

def do_GET(self):if self.path == '/':self.send_response(200)self.send_header("Content-type", "text/html")self.end_headers()self.wfile.write(bytes("<html><body><p>Request: %s</p></body></html>" % self.path, "utf-8"))elif self.path == '/upload':self.send_response(200)self.send_header("Content-type", "text/html")self.end_headers()self.wfile.write(bytes("<html><body><p>Request: %s</p></body></html>" % self.path, "utf-8"))

处理 POST 请求

实现do_POST方法

def do_POST(self):content_length = int(self.headers['Content-Length'])file_content = self.rfile.read(content_length)# Do what you wish with file_content#print file_content# Respond with 200 OKself.send_response(200)self.send_header("Content-type", "text/html")self.end_headers()self.wfile.write(bytes("<html><body><p>Request: %s</p></body></html>" % self.path, "utf-8"))

处理请求参数和 COOKIE 等

添加以下引用

from functools import cached_property
from http.cookies import SimpleCookie
from urllib.parse import parse_qsl, urlparse

在 MyServer 类下添加以下处理方法

    @cached_propertydef url(self):return urlparse(self.path)@cached_propertydef query_data(self):return dict(parse_qsl(self.url.query))@cached_propertydef post_data(self):content_length = int(self.headers.get("Content-Length", 0))return self.rfile.read(content_length)@cached_propertydef form_data(self):return dict(parse_qsl(self.post_data.decode("utf-8")))@cached_propertydef cookies(self):return SimpleCookie(self.headers.get("Cookie"))

处理 Multipart 文件上传

需要引入

from urllib.parse import parse_qs, parse_qsl, urlparse
import cgi

对请求根据 content-type 分别处理

    def parse_POST(self):print(self.headers)ctype, pdict = cgi.parse_header(self.headers['content-type'])if ctype == 'multipart/form-data':print("file request")pdict['boundary'] = bytes(pdict['boundary'], "utf-8")postvars = cgi.parse_multipart(self.rfile, pdict)elif ctype == 'application/x-www-form-urlencoded' or 'application/json':   print("non-file request")length = int(self.headers['content-length'])postvars = parse_qs(self.rfile.read(length).decode('utf8'),keep_blank_values=1)elif ctype == 'application/octet-stream':print("octet stream header")postvars = {}else:print("nothing")postvars = {}a = self.rfileprint(dir(a))print(a.peek())return postvars

do_POST 中调用

    def do_POST(self):postvars = self.parse_POST()print(postvars)

一个接收文件并调用 PaddleOCR 识别的WEB服务例子

server.py

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, parse_qsl, urlparse
import cgi
import json
import paddleocr_helperhostName = "localhost"
serverPort = 8080class MyServer(BaseHTTPRequestHandler):def parse_POST(self):print(self.headers)ctype, pdict = cgi.parse_header(self.headers['content-type'])if ctype == 'multipart/form-data':print("file request")pdict['boundary'] = bytes(pdict['boundary'], "utf-8")postvars = cgi.parse_multipart(self.rfile, pdict)elif ctype == 'application/x-www-form-urlencoded' or 'application/json':   print("non-file request")length = int(self.headers['content-length'])postvars = parse_qs(self.rfile.read(length).decode('utf8'),keep_blank_values=1)elif ctype == 'application/octet-stream':print("octet stream header")postvars = {}else:print("nothing")postvars = {}a = self.rfileprint(dir(a))print(a.peek())return postvarsdef do_GET(self):if self.path == '/':self.send_response(200)self.send_header("Content-type", "text/html")self.end_headers()self.wfile.write(bytes("<html><body><p>Request: %s</p></body></html>\r\n" % self.path, "utf-8"))def do_POST(self):postvars = self.parse_POST()#print(postvars)#print(type(postvars['file']))result = {}try:result = paddleocr_helper.parse_and_lookup(postvars['file'][0])except:print("Error occurred")result = {"code": 1,"message": "error","data": None}pass# Respond with 200 OKself.send_response(200)self.send_header("Content-type", "application/json")self.end_headers()#self.wfile.write(bytes("<html><body><p>Request: %s</p></body></html>\r\n" % self.path, "utf-8"))self.wfile.write(bytes(json.dumps(result), "utf-8"))if __name__ == "__main__":webServer = HTTPServer((hostName, serverPort), MyServer)print("Server started http://%s:%s" % (hostName, serverPort))try:webServer.serve_forever()except KeyboardInterrupt:passwebServer.server_close()print("Server stopped.")

paddleocr_helper.py

import json
import re
import math
from paddleocr import PaddleOCRdef parse_image(imagedata):ocr = PaddleOCR(show_log=False, use_angle_cls=True, lang="ch") # need to run only once to download and load model into memoryresult = ocr.ocr(imagedata, cls=True)outputs = []for idx in range(len(result)):res = result[idx]output = []for line in res:ocr_result = {'boxes' : line[0],'text'  : line[1][0],'score' : line[1][1]}output.append(ocr_result)outputs.append(output)return outputsdef lookup_invoice_number(ocr_blocks):block_no = Noneblock_numbers = []for ocr_block in ocr_blocks:#print(ocr_block['text'])regex_result = re.compile('(票据号码|柔据号码|桑据号码|柔线号码|柔楼号码|系热号码):(\d+)').search(ocr_block['text'])if not regex_result is None:#print('----> ' + regex_result.group(2))return regex_result.group(2)regex_result = re.compile('N(?:.*?)(\d{8,})').search(ocr_block['text'])if not regex_result is None:#print('----> ' + regex_result.group(1))return regex_result.group(1)if re.match('No(\.|:|:)', ocr_block['text']):#print('- No. block: {}'.format(ocr_block['text']))block_no = ocr_blockregex_result = re.compile('(\d{8,})').search(ocr_block['text'])if not regex_result is None:#print('- Num block: {}'.format(regex_result.group(1)))ocr_block['text'] = regex_result.group(1)block_numbers.append(ocr_block)if not block_no is None and not len(block_numbers) == 0:#print('- block_no:{}'.format(block_no))distance_min = Nonecandidate = Nonefor block_number in block_numbers:# calculate distance between number and Nodistance = calcu_distance(block_no['boxes'], block_number['boxes'])#print('- dist:{}, block:{}'.format(distance, block_number))print('- dist:{}, block:{}'.format(distance, block_number['text']))if (distance_min is None) or (distance < distance_min):distance_min = distancecandidate = block_number['text']return candidatereturn Nonedef parse_and_lookup(imagedata):invoice_numbers = []ocr_result = parse_image(imagedata)if len(ocr_result) > 0:for ocr_blocks in ocr_result:invoice_number = lookup_invoice_number(ocr_blocks)if (not invoice_number is None):invoice_numbers.append(invoice_number)resp = {"code": 0,"message": "succ","data": {"invoice_numbers": invoice_numbers}}return respdef calcu_distance(boxes1, boxes2):distance_min = Nonebox1 = Nonefor box in boxes1:distance = point_distance(box, boxes2[0])if (distance_min is None) or (distance < distance_min):distance_min = distancebox1 = boxfor box in boxes2:distance = point_distance(box, box1)if (distance_min is None) or (distance < distance_min):distance_min = distancereturn distance_mindef point_distance(point1, point2):x = point1[0] - point2[0]y = point1[1] - point2[1]qrt = math.sqrt(x**2 + y**2)return qrt

参考

  • https://realpython.com/python-http-server/

这篇关于Python基于 BaseHTTPRequestHandler 创建简单Web服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/851111

相关文章

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert