用于保存文件的简单 Python Web 服务器 [英] Simple Python Webserver to save file

查看:47
本文介绍了用于保存文件的简单 Python Web 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a simple python webserver to save text that is Posted to a file called store.json which is in the same folder as the python script. Here is half of my code, can someone tell me what the rest should be?

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()

推荐答案

这里是总体思路:

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%

这篇关于用于保存文件的简单 Python Web 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆