简单的Python Web服务器来保存文件

时间:2012-10-30 19:10:46

标签: python-3.x webserver

我正在尝试制作一个简单的python网络服务器,将Post文本保存到名为store.json的文件中,该文件与python脚本位于同一文件夹中。这是我的代码的一半,有人可以告诉我剩下的应该是什么吗?

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class StoreHandler(BaseHTTPRequestHandler):
def do_GET(self):
    try:
        if self.path == "/store.json":
            f = open(curdir + sep + "store.json") #self.path has /test.html
            self.send_response(200)
            self.send_header('Content-type','text/json')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
            return
        return
    except IOError:
        self.send_error(404,'File Not Found: %s' % self.path)
def do_POST(self):
    //if the url is 'store.json' then
    //what do I do here?

def main():
    try:
        server = HTTPServer(('', 80), StoreHandler)
        print 'started...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()
if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:29)

以下是一般概念:

from os import curdir
from os.path import join as pjoin

from http.server import BaseHTTPRequestHandler, HTTPServer

class StoreHandler(BaseHTTPRequestHandler):
    store_path = pjoin(curdir, 'store.json')

    def do_GET(self):
        if self.path == '/store.json':
            with open(self.store_path) as fh:
                self.send_response(200)
                self.send_header('Content-type', 'text/json')
                self.end_headers()
                self.wfile.write(fh.read().encode())

    def do_POST(self):
        if self.path == '/store.json':
            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)


server = HTTPServer(('', 8080), StoreHandler)
server.serve_forever()
$ curl -X POST --data "one two three four" localhost:8080/store.json
$ curl -X GET localhost:8080/store.json    
one two three four%

答案 1 :(得分:9)

重要的是,您必须从原始发布的数据中正确构建cgi.FieldStorage,例如

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

之后很容易转储文件,这是一个简单的处理程序,它在do_GET上显示一个表单,用于上传用户选择的任何文件,并在表单POST时将该文件保存到do_POST中的/ tmp

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

import cgi

class StoreHandler(BaseHTTPRequestHandler):
    def do_POST(self):

        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })
        filename = form['file'].filename
        data = form['file'].file.read()
        open("/tmp/%s"%filename, "wb").write(data)

        self.respond("uploaded %s, thanks"%filename)

    def do_GET(self):
        response = """
        <html><body>
        <form enctype="multipart/form-data" method="post">
        <p>File: <input type="file" name="file"></p>
        <p><input type="submit" value="Upload"></p>
        </form>
        </body></html>
        """        

        self.respond(response)

    def respond(self, response, status=200):
        self.send_response(status)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-length", len(response))
        self.end_headers()
        self.wfile.write(response)  

另请注意,self.respond不是我刚添加的标准方法,可以快速返回一些响应。