#!/usr/bin/python3
import socketserver
from http.server import BaseHTTPRequestHandler
import time
import threading
def do_something(site_id, first, last, pass1):
print(site_id)
print(first)
print(last)
print(pass1)
#just to illustrate the point and print the variables
class MyHandler(BaseHTTPRequestHandler):
def do_POST(self): # !important to use 'do_POST' with Capital POST
global site_id, first, last, pass1 #those are still undefined at the module level ;) remember this for later
if self.path == '/do_something':
request_headers = self.headers
site_id = request_headers["m_site_name"]
first = request_headers["m_first_name"]
last = request_headers["m_last_name"]
pass1 = request_headers["m_device_name"]
do_something(site_id, first, last, pass1)
self.send_response(200)
self.end_headers() #as of P3.3 this is required
try:
httpd = socketserver.TCPServer(("localhost", 9001), MyHandler)
httpd.serve_forever()
finally:
httpd = socketserver.TCPServer(("localhost", 9001), MyHandler)
httpd.server_close()
#!/usr/bin/python3
import socketserver
from http.server import BaseHTTPRequestHandler
import time
import threading
def do_something(site_id, first, last, pass1):
print(site_id)
print(first)
print(last)
print(pass1)
#just to illustrate the point and print the variables
class MyHandler(BaseHTTPRequestHandler):
def do_POST(self): # !important to use 'do_POST' with Capital POST
global site_id, first, last, pass1 #those are still undefined at the module level ;) remember this for later
if self.path == '/do_something':
request_headers = self.headers
site_id = request_headers["m_site_name"]
first = request_headers["m_first_name"]
last = request_headers["m_last_name"]
pass1 = request_headers["m_device_name"]
do_something(site_id, first, last, pass1)
self.send_response(200)
self.end_headers() #as of P3.3 this is required
try:
httpd = socketserver.TCPServer(("localhost", 9001), MyHandler)
httpd.serve_forever()
finally:
httpd = socketserver.TCPServer(("localhost", 9001), MyHandler)
httpd.server_close()
@oetoni,我在使用时遇到超时错误:
但我在使用此代码时得到了正确的响应:
^{pr2}$它在网络浏览器上打印接收到的数据。 我在apacheweb服务器上使用这个脚本作为cgi脚本,可以通过web浏览器访问它。我没有将此脚本作为服务或应用程序运行。在
这个代码解决了我的问题。现在我可以用这个pythoncgi脚本将httppost数据存储到变量中。在
我的HTTP POST请求: http://your_server_url_or_IP/cgi-bin/python_script.py?m_site_name=MySite&m_first_name=anyname&m_last_name=anylastanme&m_device_name=anydeviceidorname
更新
根据你在下面发布的代码,这里有一个有效的答案。在
跟邮递员打电话
命令行输出是
我综合了以下答案: 引用one、two和{a4} 这也是非常重要的: https://docs.python.org/3/library/http.server.html
我相信对于一个小的实现和一些测试或者概念验证来说是可以的,但是最终您需要更好地管理这个问题,也许我可以建议您花一些时间使用Flask,它实际上是一个用于Python API构建和原型设计的非常好而且非常轻的框架。在
-在
上一个答案(上面已弃用并更新)
-
根据对this一个非常简单的引用:
^{pr2}$更新(不带和API):
假设您在或计算机上运行的自定义端口的URL处有一个自定义尾随部分,那么“纯”python将如下所示:
我假设这样你可以自由地重用变量。同时检查参考文献here,布伦达的答案。在
相关问题 更多 >
编程相关推荐