首页 > 编程语言 >python创建httpserver,并处理get、post请求

python创建httpserver,并处理get、post请求

时间:2024-01-18 09:03:07浏览次数:26  
标签:Control httpserver get python self send Access header headers

搭建一个简单的httpserver,用于测试数据通讯

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

data = {'result': 'this is a test'}
host = ('localhost', 8888)


class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))

        print('headers', self.headers)
        print("do post:", self.path, self.client_address, datas)

if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()

Qt这边可以这样子操作:


QNetworkAccessManager man;
void MainWindow::on_pushButton_clicked()
{
    QNetworkReply *mReply;

    QNetworkRequest request;
    request.setUrl(QUrl("http://127.0.0.1:8888"));

//    mReply = man.get(request);
//    connect(mReply, &QNetworkReply::finished, [=](){
//       qDebug() << "get these:" << mReply->readAll();

//       mReply->deleteLater();
//    });

    uchar tmpData[] = {0x12, 0x03, 0x04, 0x05, 0x06};
    QByteArray ba((const char*)tmpData, sizeof(tmpData));

    request.setUrl(QUrl("http://127.0.0.1:8888/abc/def"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "text");
    request.setRawHeader("self_defined_heade", "789456");
    mReply = man.post(request, ba);
    connect(mReply, &QNetworkReply::finished, [=](){
       qDebug() << "post finished:" << mReply->readAll();

       mReply->deleteLater();
    });


    qDebug() << "-----------------";
}

当要处理CORS时:

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

data = {'result': 'this is a test'}
host = ('localhost', 8888)


class Resquest(BaseHTTPRequestHandler):
    # def end_headers(self):
    #     self.send_header('Access-Control-Allow-Origin', '*')
    #     self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
    #     self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
    #     BaseHTTPRequestHandler.end_headers(self)

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()

        # Respond with an empty body to the pre-flight request
        self.wfile.write(b'')

    def do_GET(self):
        # self.send_response(200)
        self.send_response(400)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))

        print('headers', self.headers)
        print("do post:", self.path, self.client_address, datas)

        self.send_response(400)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())


if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()

标签:Control,httpserver,get,python,self,send,Access,header,headers
From: https://www.cnblogs.com/kn-zheng/p/17971708

相关文章

  • Python Matplotlib 实现基础绘图
    ​ 1、Matplotlib的三层结构Matplotlib是一个用于在Python中创建二维图表的库。为了更好地理解和使用Matplotlib,重要的是要了解其三层结构:容器层(ContainerLayer)、辅助显示层(HelperLayer)和图像层(ArtistLayer)。这些层级构成了Matplotlib的绘图体系结构。1)容器层(Conta......
  • stable Diffusion python 运行时抛出一个异常
    Python中的异常处理引言在编程过程中,我们经常会遇到各种错误和异常情况。为了提高程序的稳定性和可靠性,我们需要对这些异常情况进行处理。在Python中,异常处理是一个非常重要且常用的功能。异常的概念异常是程序中不正常的情况,例如:文件不存在、数组越界、除零错误等。当异常发生......
  • stable diffusion 运行时python意外退出 mac
    StableDiffusion运行时Python意外退出Mac实现指南简介在开发过程中,我们经常会遇到Python运行时意外退出的情况。这可能是由于代码错误、内存不足、依赖问题等原因导致的。本文将指导你如何在Mac系统上实现StableDiffusion运行时Python意外退出的解决方案。整体流......
  • LLaMA如何使用python调用
    使用Python调用LLaMA解决图像分类问题介绍LLaMA(LowLatencyModelAnalyzer)是一个用于分析和优化机器学习模型的开源工具。它可以帮助开发者在低延迟的环境中运行模型,并提供优化建议。本文将介绍如何使用Python调用LLaMA来解决一个具体的问题——图像分类。问题描述假设我们有......
  • stable diffusion python运行时抛出了一个异常
    实现“stablediffusionpython运行时抛出了一个异常”介绍在Python开发过程中,我们经常会遇到运行时抛出异常的情况。异常是程序在执行过程中发生的错误,如果不加以处理,就会导致程序终止或产生意想不到的结果。本文将教会你如何在Python中处理异常,并实现“stablediffusionpython......
  • whisper分句 python
    实现"whisper分句python"简介在本文中,我将向你介绍如何使用Python实现"whisper分句"功能。"whisper分句"是指将一段文字分成多个句子,每个句子都是以小写字母开始,并且紧跟着一个空格。这个功能可以在自然语言处理和文本分析中非常有用,例如对文本进行分词或者句子级别的情感分析......
  • stable Diffusion 启动崩溃 Python异常
    实现"stableDiffusion"启动崩溃Python异常概述在本文中,将介绍如何使用Python语言实现"stableDiffusion"启动崩溃的Python异常。我们将通过以下步骤来完成这个任务:引入所需的库和模块创建一个函数,用于触发异常在函数中添加稳定扩散操作实现异常处理逻辑测试代码......
  • Python 随笔第5小节
    '''列表可变序列可重复有序【】'''importoperator#创建列表的第一方式lst=['hello','word,',98]print(lst)print(lst[0],lst[-3])#顺着进行是01234567逆着数是-1-2-3-4#创建列表的第二种方式lst=list(['hello','wwww&#......
  • python SpeechRecognition Whisper
    Python语音识别库SpeechRecognitionWhisper![speech_recognition](引言语音识别是一种将人类语音转换为可理解的文本形式的技术。它在日常生活中的应用越来越广泛,例如语音助手、语言翻译、语音搜索等。Python是一种流行的编程语言,它提供了许多用于语音识别的库和工具。本文将介......
  • 从python 单机版爬虫 scrapy 到 分布式scrapy-redis 爬虫用最简单的步骤创建实例
    scrapy是很强大的模块化爬虫框架,具有很高的灵活性,使用频率很高,使用该框架能大大提高开发效率,scrapy-redis是在scrapy框架开发了组件,替换队列部分,实现多台服务器并行运行爬虫,提高爬取速度。下面是用最简单的例子从建立普通scrapy爬虫,然后数据保存mysql,最后简单替换几行就能使用s......