[requests.post] python으로 보낸 데이터 php로 받기

카테고리 없음|2017. 2. 11. 00:41
반응형

python으로 보낸 데이터 php로 받기



인터넷에서 python에서 데이타를 보내는 예제를 많이 찾아 볼 수 있다. 하지만 문제는 파이썬3.x버전에서는 사용해야 하는 모듈이 인터넷에 나온 기존 예제와 다르다는 것이다. 또한 데이타베이스에 저장을 하는 것이 아닌 쿠키를 생성함으로써 데이타가 잘 전송되는지 알아보려고 하는 실수 때문에 시간이 오래 걸렸다.


작동되는 코드는 다음과 같이 간단하다.



import requests

userdata = {"firstname": 'frompython', "lastname": "Doe", "password": "jdoe123"}

resp = requests.post('http://localhost/test/testing.php', data=userdata)

print(resp.text)

 





1. 딕셔너리 형식으로 데이타를 변수에 저장한 뒤 

2. requests.post를 사용하여 데이타를 처리하는 페이지에 전달을 한다.

다음은 이것을 처리하는 php서버 코드이다.


<?php 

if(isset($_POST['firstname'])){

   $name = $_POST['firstname'];

   $conn=mysql_connect("localhost","root","");

   if(!$conn){

   die('could not connect:'.mysql_error());

   }

   mysql_select_db("test",$conn);

   $query ="INSERT INTO testing (data) VALUES ('$name');";  

   // '$name에서' '' 이거 빠뜨리지 않게 조심해야함. 쿠키는 클라이언트에서 생성함으로 여기서 만들어지지 않음


   $result = mysql_query($query, $conn);  

   setcookie("name", "$name", time()+5000);

   echo "$name";

}else{

   echo("nothing");

}


 ?>



처음에 데이타가 제대로 전송이 되는지 확인하기 위해 쿠키를 생성하려고 하였지만 쿠키는 클라이언트에서 생성하기 때문에 생성이 되지 않았다. 하지만 데이타베이스에 저장하는 코드를 적으니 데이타베이스에 값이 저장 되는 것을 볼 수 었다. 



----- 추가 -----

import urllib

import urllib2


url = 'http://xxx.xxx.x.xxx/reciever.php'

payload = {"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}

headers = {'content-type': 'application/json'}    

data = urllib.urlencode(payload)

req = urllib2.Request(url, data, headers)

response = urllib2.urlopen(req)

the_page = response.read()




구글링할때 가장 많이 보는 코드인데 

3.0버전에서는urllib2가 분리되어서 작동하지 않는다. 아래 처럼 코드를 작성하면 request가 아닌 urllib로 urllib2를 대신 할 수 있다.


import urllib.request 

userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"} 

userdata = urllib.parse.urlencode(userdata) 

binary_data = userdata.encode('utf-8') 

resp = urllib.request.urlopen('http://localhost/test/testing.php', binary_data) 


반응형

댓글()