使用 BaseHTTPRequestHandler 编写响应正文

发布于 2024-12-08 04:16:46 字数 1720 浏览 2 评论 0原文

我正在玩一点 Python 3.2.2,想编写一个简单的 Web 服务器来远程访问一些数据。该数据将由 Python 生成,因此我不想使用 SimpleHTTPRequestHandler,因为它是文件服务器,而是我自己的处理程序。

我从互联网上复制了一些示例,但我陷入困境,因为响应输出流拒绝写入正文内容

这是我的代码:

import http.server
import socketserver

PORT = 8000

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        print(self.wfile)
        self.wfile.write("<html><head><title>Title goes here.</title></head>")
        self.wfile.write("<body><p>This is a test.</p>")
        # If someone went to "http://something.somewhere.net/foo/bar/",
        # then s.path equals "/foo/bar/".
        self.wfile.write("<p>You accessed path: %s</p>" % self.path)
        self.wfile.write("</body></html>")
        self.wfile.close()

try:
    server = http.server.HTTPServer(('localhost', PORT), MyHandler)
    print('Started http server')
    server.serve_forever()
except KeyboardInterrupt:
    print('^C received, shutting down server')
    server.socket.close()

编写响应正文的正确代码应该是什么?

多谢。

编辑:

错误是:

...
  File "server.py", line 16, in do_GET
    self.wfile.write("<html><head><title>Title goes here.</title></head>")
  File "C:\Python32\lib\socket.py", line 297, in write
    return self._sock.send(b)
TypeError: 'str' does not support the buffer interface

I'm playing a little with Python 3.2.2 and want to write a simple web server to access some data remotely. This data will be generated by Python so I don't want to use the SimpleHTTPRequestHandler as it's a file server, but a handler of my own.

I copied some example from the internet but I'm stuck because the response outputstream refuses to write the body content.

This is my code:

import http.server
import socketserver

PORT = 8000

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        print(self.wfile)
        self.wfile.write("<html><head><title>Title goes here.</title></head>")
        self.wfile.write("<body><p>This is a test.</p>")
        # If someone went to "http://something.somewhere.net/foo/bar/",
        # then s.path equals "/foo/bar/".
        self.wfile.write("<p>You accessed path: %s</p>" % self.path)
        self.wfile.write("</body></html>")
        self.wfile.close()

try:
    server = http.server.HTTPServer(('localhost', PORT), MyHandler)
    print('Started http server')
    server.serve_forever()
except KeyboardInterrupt:
    print('^C received, shutting down server')
    server.socket.close()

What should be a correct code for writing the response body?

Thanks a lot.

Edit:

The error is:

...
  File "server.py", line 16, in do_GET
    self.wfile.write("<html><head><title>Title goes here.</title></head>")
  File "C:\Python32\lib\socket.py", line 297, in write
    return self._sock.send(b)
TypeError: 'str' does not support the buffer interface

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

捂风挽笑 2024-12-15 04:16:46

Python3 中的字符串类型与 Python 2.x 中的字符串类型不同。使用

self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>/html>","utf-8")) 

或将其转换为字节

self.wfile.write("<html><head><title>Title goes here.</title></head></html>".encode("utf-8"))

In Python3 string is a different type than that in Python 2.x. Cast it into bytes using either

self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>/html>","utf-8")) 

or

self.wfile.write("<html><head><title>Title goes here.</title></head></html>".encode("utf-8"))
甜扑 2024-12-15 04:16:46

对于 Python 3,请在字符串文字前加上 b 前缀:

self.wfile.write(b"<foo>bar</foo>")

For Python 3, prefix the string literals with a b:

self.wfile.write(b"<foo>bar</foo>")
寒尘 2024-12-15 04:16:46

根据您的代码#comments,您可能正在寻找 self.headers.getheaders('referer'),即:

if 'http://www.icamefromthissite.com/' in self.headers.getheaders('referer'):
    do something

based on your code #comments you're probably looking for self.headers.getheaders('referer'), ie:

if 'http://www.icamefromthissite.com/' in self.headers.getheaders('referer'):
    do something
身边 2024-12-15 04:16:46

使用Python 3.X时只需使用这个

self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))

Just use this when using Python 3.X

self.wfile.write(bytes("<body><p>This is a test.</p>", "utf-8"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文