我正在写一个程序来生成一个能够接受用户输入的网页。我需要接受用户输入的任何内容,然后在网页上打印出一个语句,大意是“Hello firstname!"。只是我不知道如何从网页中获取输入的数据并将其传递回python。
到目前为止,我一直尝试使用post方法,但我认为有些东西配置不正确,因为它在网站上生成了以下错误。“错误代码501,不支持的方法(POST)”
下面是我在服务器端使用的代码,一个非常简单的小python脚本。这整个折磨是我学习python的努力的一部分,如果解决方案可以用python来解释,我会非常感激。
然而,如果有某种方法可以在html中打印用户输入,我不会反对,因为无论如何,它都会被传递回python的网页。
# Python 3 server example
`from http.server import BaseHTTPRequestHandler, HTTPServer #clarify from command Hypothesis: Code doesn't require the entire http module so it's only importing the BaseHttp and HTTPServer classes, classes can be imported without the modle they're from?
import time #Why is time imported if it's not used? Hypothesis: the send response method on line 10 states among other things to send the current date. Thus time is needed to determine current date?
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler): #What is __init__ not used in this class? Still need to clarify "self" value.
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>Hello world! This is a webpage!</p>", "utf-8"))
self.wfile.write(bytes("<p> And hello to you! Please enter your name below!</p>", "utf-8"))
self.wfile.write(bytes("""<form action="webpage.py" method="post">
<label for="name">Please enter your name:</label><br>
<input type="text" id="name" name="name"><br>
<input type = "submit" value = "Click me!">
</form>
""", "utf-8" )) #if this throws an error try inserting "utf-8" at the very end as a seperate string
self.wfile.write(bytes())
self.wfile.write(bytes("</body></html>", "utf-8"))
if __name__ == "__main__": #Identify use of __name__ dunder
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt: #Why does this exception exist if no code is present. Hypothesis: Given this is demonstration code it's just to keep it from crashing if you input something in the console?
pass
webServer.server_close()
print("Server stopped.")
#TODO: Insert a form that will ask for a user's name, insert a button. When the button is pushed raise a flag e.g button_clicked, use an if statement to print the entered nanme when this flag is raised.`
字符串
1条答案
按热度按时间whlutmcx1#
您的代码中可能有一些问题导致了501错误。
首先,在HTML表单中检查action属性是否设置为“filename.py“,这可能会导致不支持的方法错误。action属性应该指向您想要处理表单提交的端点。在您的情况下,它是相同的Python脚本,因此您可以将其保留为空或将其设置为“/"。
其次,你需要在MyServer类中实现do_POST方法来处理POST请求。目前,你只有do_GET方法。将以下方法添加到你的类中:
此代码读取POST请求的内容,提取用户输入,然后将其包含在响应中。