先创建服务端:
上代码:
#参考文章 https://gist.github.com/nitaku/10d0662536f37a087e1b
#关于 http.server 语法,参考这里https://docs.python.org/3/library/http.server.html ,
"""
We also need to convert response to bytes as following. Without it we get error , TypeError: a bytes-like object is required, not 'str'
def do_GET(self):
self._set_headers()
response = json.dumps({'hello': 'world', 'received': 'ok'})
response = bytes(response, 'utf-8')
self.wfile.write(response)
出现了一个语法错误,参考上面的批注,需要把结果数据转化为Bytes 模式才行。
怀疑是函数self.wfile.write() 里面入参必须是bytes
关于bytes 函数,参考这里https://www.w3school.com.cn/python/ref_func_bytes.asp
定义和用法
bytes() 函数返回字节对象。
它可以将对象转换为字节对象,或创建指定大小的空字节对象。
bytes() 和 bytearray() 之间的区别在于,bytes() 返回一个不能修改的对象,而 bytearray() 返回一个可以修改的对象。
bytes(x, encoding, error)
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import time
class Server(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_HEAD(self):
self._set_headers()
# GET sends back a Hello world message
def do_GET(self):
self._set_headers()
string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
response = json.dumps({'currentTime': string})
response = bytes(response,'utf-8')
self.wfile.write(response)
def run(server_class=HTTPServer, handler_class=Server, port=80):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting httpd on port {0}...'.format(port))
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
运行效果:
客户端模拟curl 读写:
用postman 从internet 读取,测试效果
直接用request 做个客户端,发现报格式错误。明天继续做。