我正在编写小型Python实用程序来使用我用PHP编写的RESTful API。到目前为止,一切都适用于GET
个请求,但是当我尝试执行POST
请求时,即使响应返回状态代码200
,也不会在数据库中创建新记录。
from httplib2 import Http
import json
root_dir = 'http://restphp/restphp/public/api/'
not_finished = True
http_obj = Http()
def get(url):
resp, content = http_obj.request(url)
return resp, content
def post(url, data):
resp, content = http_obj.request(
uri = url,
method = 'POST',
headers = {'Content-Type': 'application/json; charset=UTF-8'},
body = json.dumps(data)
)
return resp, content
# Code for getting data from input stream
# ...
data = {
'first_name': first_name,
'last_name': last_name,
'email': address
}
resp, content = post(root_dir + 'customer/add', data)
print(resp)
这是输出:
{'date': 'Sun, 29 Oct 2017 19:27:29 GMT', 'server': 'Apache/2.4.23 (Unix) OpenSSL/1.0.2j PHP/7.0.13 mod_perl/2.0.8-dev Perl/v5.16.3', 'x-powered-by': 'PHP/7.0.13', 'content-length': '109', 'content-type': 'text/html; charset=UTF-8', 'status': '200'}
这是创建新客户的途径(我正在使用Slim框架)。我使用RestEasy extension检查了适用于Chrome的API,所有内容都适用。
# Add new customer
$app->post('/api/customer/add', function(Request $request, Response $response) {
$first_name = $request->getParam('first_name');
$last_name = $request->getParam('last_name');
$phone = $request->getParam('phone');
$email = $request->getParam('email');
$address = $request->getParam('address');
$city = $request->getParam('city');
$state = $request->getParam('state');
$sql = "INSERT INTO customers (first_name, last_name, phone, email, address, city, state) VALUES
(:first_name, :last_name, :phone, :email, :address, :city, :state)";
try {
$db = new DB();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(":first_name", $first_name);
$stmt->bindParam(":last_name", $last_name);
$stmt->bindParam(":phone", $phone);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":address", $address);
$stmt->bindParam(":city", $city);
$stmt->bindParam(":state", $state);
$stmt->execute();
echo '{"notice": {"text": "Customer added."}}';
} catch (PDOException $e) {
echo '{"error": {"text": ' . $e->getMessage() . '}}';
}
});
我在每次执行时都会收到随机错误,例如'first_name' column can't be null
(即使发送了整个数据)或BrokenPipeError: [Errno 32] Broken pipe
。
答案 0 :(得分:0)
当您发布数据在正文中发送数据时。试试这个
$value = json_decode($request->getBody());
$first_name = $value->first_name
$last_name = $value->last_name
$phone = $value->phone
$email = $value->email
$address = $value->address
$city = $value->city
$state = $value->state