如何使用http.server python3打印换行符?

时间:2018-06-23 14:12:22

标签: python python-3.x http server

我正在尝试制作自己的小型Messenger服务器,该服务器可以通过PRG模式工作。我工作正常,但是每次收到新消息时,都无法在do_GET()中打印换行符。

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs


class MessageHandler(BaseHTTPRequestHandler):

    html_form = """
    <!DOCTYPE html>
    <title>Message Board</title>
    <form method="POST" action="http://localhost:8000/">
        <textarea name="message"></textarea>
        <br>
        <button type="submit">Post it!</button>
    </form>
    """

    messages = []

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write(self.html_form.encode())
        for m in self.messages:
            self.wfile.write((m+"\n").encode())


    def do_POST(self):
        # 1. How long was the message? (Use the Content-Length header.)
        length = int(self.headers.get('content-length', 0))
        # 2. Read the correct amount of data from the request.
        data = self.rfile.read(length).decode()
        # 3. Extract the "message" field from the request data.
        message = parse_qs(data)['message'][0]
        self.messages.append(message.replace('<', '&lt;'))
        # Send the "message" field back as the response.
        self.send_response(303)
        self.send_header('Location', '/')
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.end_headers()

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MessageHandler)
    httpd.serve_forever()

1 个答案:

答案 0 :(得分:0)

我找到了解决此问题的方法。显然,此“服务器”会在浏览器中打印所有内容,因此换行符必须采用HTML格式'<br>''<br />'