gpt4 book ai didi

python-3.x - 简单的 Python Web 服务器来保存文件

转载 作者:行者123 更新时间:2023-12-03 00:02:52 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的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()

最佳答案

总体思路如下:

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-3.x - 简单的 Python Web 服务器来保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com