我在googleing并尝试,但我找不到答案(我不是说“我如何使用python发送POST请求?”)。
故事:
开发POS系统我已经在使用python脚本执行一些任务,例如与硬件外围设备的通信。到目前为止,这些脚本在安装了Apache的小型服务器上运行,并通过POST请求启动到ajax.php
,假设有两个参数$_POST['name']='scriptname'
和$_POST['param1']=1200
,它们通过php命令传输,如system('python ' . $_POST['name'] . '.py ' . $_POST['param1'] . ' &');
进入system('python scriptname.py 1200 &');
现在我正在考虑设置一个没有安装Apache的纯Linux / Python服务器,并希望执行相同的操作。
假设,simpleHTTPserver已启动并运行指定的文件夹。
第一个问题:
如何管理它,所以从另一个网络客户端发送POST(或者现在让我们说GET)请求到这个服务器,如http://192.168.20.11:8080/scriptname.py?arg=1200
第二个问题:
如何通过USB刻度获得“完成”或类似1560之类的响应,以继续使用发送网络客户端上的响应(ajax数据部分)?
答案 0 :(得分:0)
投降?永远不会!
数小时后......我的第一个python脚本,仍然需要一些动手,到目前为止我可以看到一些小的凹痕和划痕,但它运行并为我提供了我最初想要它做的事情。
它同时是一种包装器和服务器,包含一些合理性和安全性检查,当然可以加强,现在它接受一个参数,逗号分隔,一个字符串(所需子进程的名称)脚本)和一个数字作为参数,如ajax.html
。还没有添加JSON,但目前不需要它。
它没有任何python框架,但是使用WSGIserver,客户端使用jquery AJAX和CORS(使用不同的URL测试,尚未在不同的机器上测试,因为稍后将需要)
在此您可以找到三个文件。 server.py
,sayhello.py
和测试题<html>
<head>
<title>Ajax POST to python</title>
</head>
<body>
send message: <input type="text" id="message" value="" size="10" placeholder="string,number"> <input type=button id="send" value="send">
<br />
response: <span id="response"></span>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$("input#send").click(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080',
crossDomain: true,
data: $('input#message').val(),
dataType: 'text',
timeout: 3000,
success: function(responseData, textStatus, jqXHR)
{
$('span#response').html(responseData);
},
error: function (responseData, textStatus, errorThrown)
{
console.warn(responseData, textStatus, errorThrown);
alert('failed - ' + textStatus);
}
});
});
</script>
</html>
。
感谢您提前提供进一步的提示,警告或改进。希望你喜欢它。
ajax.html
#!/usr/bin/env python
import threading
from subprocess import Popen, PIPE
from pathlib import Path
from wsgiref.simple_server import make_server
PORT = 8080
REQUEST_METHOD = "POST"
def myapp(env, http_stuff):
if env['REQUEST_METHOD'] == REQUEST_METHOD:
try:
request_body_size = int(env['CONTENT_LENGTH'])
request_body = env['wsgi.input'].read(request_body_size)
except (TypeError, ValueError):
request_body = "0"
try:
#---------------------------security / plausibility
allowed_scripts = ["sayhello","count_apples","get_scale_weight","etc."]
el = request_body.split(",");
arg_filename = str(el[0].strip())
arg_num = int(el[1].strip())
if not (arg_filename in allowed_scripts):
arg_filename = ""
if isinstance(arg_num, int):
arg_num = str(arg_num)
else:
arg_num = ""
#---------------------------script exists ?
my_file = Path(arg_filename+".py")
if my_file.is_file():
output = "no valid output."
#---------------------------subprocess
proc = Popen(["python", arg_filename+".py",arg_num], shell=False, stdout=PIPE, stderr=PIPE )
output = proc.communicate()[0]
#---------------------------more stuff
response_body = output
else:
response_body = "["+request_body+"] is not allowed !"
except:
response_body = "some other error"
else:
response_body = "no POST data"
status = '200 OK'
#---------------------------header with CORS support
headers = [('Content-type', 'text/plain'),
("Access-Control-Allow-Origin", "*")]
http_stuff(status, headers)
return response_body
def start_server():
httpd = make_server("", PORT, myapp)
httpd.serve_forever()
if __name__ == "__main__":
start_server()
server.py
#!/usr/bin/env python
import sys
print "I am sayhello.py and I say HELLO "+sys.argv[1]
sayhello.py
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
data: {}, //filled by fetch data from API
imgData: {}, //filled by fetch image data from API
typeData: {}, //filled by fetch types data from API
types: {
typesArray: []
},
typeDataTotal: {},
specificTypeData: {}
};
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
//alert('Text field value is: ' + this.state.value);
var _this = this;
fetch('https://pokeapi.co/api/v2/pokemon/' + this.state.value + '/').then(function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' + response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
console.log(data.sprites.front_default);
_this.setState({data: data});
_this.setState({imgData: data.sprites});
_this.setState({typeData: data.types[0].type});
_this.setState({specificTypeData: data.types}); //this is the one I want to use for keys in the array
_this.setState({
typeDataTotal: Object.keys(data.types)
});
console.log(data.types[0].type.name); //shows item as string
console.log(data.types[1].type.name);
console.log(Object.keys(data.types).length);
});
}
}
render() {
var data = this.state.data;
var imgData = this.state.imgData;
var typeData = this.state.typeData;
var typeDataTotal = this.state.typeDataTotal;
var specificTypeData = this.state.specificTypeData;
var forms = [];
for (var key in typeDataTotal) {
console.log("obj." + key + " = " + specificTypeData[key].type.name);
forms.push(<formjs data={specificTypeData[key].type.name}/>);
console.log(forms);
}
return (
<div>{forms}</div>
);
}
}