在 Python 中获取 HTTP GET 变量 [英] Fetching HTTP GET variables in Python
问题描述
我正在尝试在 Python 脚本中设置 HTTP 服务器.到目前为止,我让服务器自己工作,代码类似于下面,来自 这里.
I'm trying to set up a HTTP server in a Python script. So far I got the server it self to work, with a code similar to the below, from here.
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
print("Just received a GET request")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write('Hello world')
return
def log_request(self, code=None, size=None):
print('Request')
def log_message(self, format, *args):
print('Message')
if __name__ == "__main__":
try:
server = HTTPServer(('localhost', 80), MyHandler)
print('Started http server')
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
server.socket.close()
但是,我需要从 GET 请求中获取变量,所以如果请求 server.py?var1=hi
,我需要 Python 代码将 var1
放入一个 Python 变量并对其进行处理(如打印).我该怎么办?对于 Python 专业人士来说,这可能是一个简单的问题,但这位 Python 初学者不知道该怎么做!提前致谢!
However, I need to get variables from the GET request, so if server.py?var1=hi
is requested, I need the Python code to put var1
into a Python variable and process it (like print it). How would I go about this? Might be a simple question to you Python pros, but this Python beginner doesn't know what to do! Thanks in advance!
推荐答案
print urlparse.parse_qs(os.environ['QUERY_STRING'])
或者如果你关心顺序或重复,urlparse.parse_qsl()
.
Or if you care about order or duplicates, urlparse.parse_qsl()
.
在 Python 3 中导入: from urllib.parse import urlparse
这篇关于在 Python 中获取 HTTP GET 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!