Python BaseHTTPServer保存cu发送的文件

2024-04-25 13:13:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个python代码:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os

PORT_NUMBER = 8080

#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):

    store_path = os.path.dirname(os.path.realpath(__file__)) + '\copyFile'
    print store_path
    # handler for the GET requests
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        # Send the html message
        self.wfile.write("Hello World !")
        return

    # handeler for POST request
    def do_POST(self):
        length = self.headers['content-length']
        data = self.rfile.read(int(length))
        with open(self.store_path, 'w') as fh:
            fh.write(data.decode())

        self.send_response(200)

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER

    #Wait forever for incoming htto requests
    server.serve_forever()

except keyboardInterrupt:
    print '^C received, shutting down the web server'
server.socket.close()

我试图创建一个简单的pythonwebserver来保存发布到本地路径的文件。我用curl将文件发送到服务器,并使用以下行:curl -F file="myfile.txt" http://localhost:8080

结果并不像我预期的那样:

^{pr2}$

我能做些什么来解决这个问题?在

我检查了this link但它没有帮助:(


Tags: thepathstorefromselfsendnumberfor
1条回答
网友
1楼 · 发布于 2024-04-25 13:13:34

好的,这里发生的是,您已经启动了HTTPServer,它创建了一个侦听传入连接的线程。当它获得一个有效的连接时,它将创建一个请求处理程序的实例,该实例将根据传入连接的输入调用适当的方法。在

BaseHTTPRequestHandler将在后台处理传入的数据,并提供一些有用的变量来访问数据。正在发送的数据从标准输入中检索。因为BaseHTTPRequestHandler是相当基本的,它只会为您做这么多。此流中的原始数据可以在self.rfile文件对象。这是你会发现你的查询字符串,JSON或二进制文件。在

现在您可以编写自己的解析器来检索这些数据,但这可能很复杂,而且已经有模块可以帮助您完成这项工作。有一个名为cgi的标准Python模块,它可以让您更轻松地完成任务。您可以找到有关此模块here的信息。在

检索文件需要执行以下操作:

import cgi

...

class myHandler(BaseHTTPRequestHandler):

    ...

    def do_POST(self):
        form = cgi.FieldStorage(
                 fp=self.rfile,
                 headers=self.headers,
                 environ={"REQUEST_METHOD": "POST",
                          "CONTENT_TYPE": self.headers['Content-Type']})

         uploaded_file = form.getvalue("file")
         if uploaded_file:
             with open(self.store_path, "wb") as fh:
                 fh.write(uploaded_file.file.read())

        ...

BaseHTTPRequestHandler实际上并不为您解析POST中的数据,因此我们需要向FieldStorage对象提供正确解析数据所需的信息。我们需要向它提供包含原始数据和请求中包含的头的文件。我们还需要给它提供关于请求的详细信息的环境,因为BaseHTTPRequestHandler不解析POST,这些变量没有添加到默认环境中,这就是我们创建自己的字典的原因。我会考虑看一下CGIHTTPServer,它将封装一些这种行为。在

一旦您创建了表单,我们就可以使用“safe”getter来检索我们的数据。如果关键字不存在,则此方法将返回None。您还可以使用以下方法检索数据:

^{pr2}$

这两个方法都返回FieldStorage或MiniFieldStorage对象。这些细节可以在cgi模块的链接中找到。但是Python中的一个杀手特性是help方法。E、 g

^{3}$

这将列出一个手册页,提供您需要了解的有关FieldStorage对象的所有详细信息。在

另外,在Python中构建路径时,最好使用os.path.join()为正在运行的系统安全地创建一个有效的路径。所以与其说台词:

store_path = os.path.dirname(os.path.realpath(__file__)) + '\copyFile'

我将用以下内容代替:

store_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'copyFile')

相关问题 更多 >