날뛰는 코드

LAMP 를 이용해 python -> php -> DB json으로 통신 하기. 본문

AWS/LAMP (Linux Apache Mysql Php)

LAMP 를 이용해 python -> php -> DB json으로 통신 하기.

미 냉 2018. 1. 21. 22:50

*post json to PHP using python requests,and insert the data to db 

 

1. http://webnautes.tistory.com/1028

LAMP설치 이블로그에서 많은 도움을 얻고있다

짱짱

 

2. python 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import urllib.request
import requests
import json
 
if __name__ == "__main__":
    print("Hello World")
    
    print("\n")
    URL = 'http://xx.xxx.xx.xx/phpsqltest.php' 
#    response = requests.get(URL) 
    
    # json data 
    payload = {'NAME':'ebi','ACCURACY'98.2,'TIME'"2017-11-11 12:20:20"}
    headers = {'content-type''application/json'}
 
    # post to url 
    response = requests.post(URL, data=json.dumps(payload), headers=headers)
    
    
    # result value
    print(response.status_code )
    data = response.text
    print(data)
#    jsondata = response.json()
#    print(jsondata)
    
    #write result
    f = open("./response.txt""w+")
    f.write(str(data))    
    f.close()
cs

 

 

3. php 코드

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php 
 
error_reporting(E_ALL);
 
ini_set("display_errors"1);
 
 
header('Content-Type: text/html; charset=utf-8');
 
 
 
$db_host = "localhost";
 
$db_user = "root";
 
$db_passwd = "password";
 
$db_name = "mysql";
 
 
 
// 데이터베이스 테스트
 
$mysqli = new mysqli($db_host$db_user$db_passwd$db_name);
 
 
 
 //db와 연결 설정 및 연결
 $link = mysqli_connect("localhost" , "root" , "password""phpmyadmin");
 
 //db 연결 실패 시 오류값 반환
 if(!$link)
 {
    array_push($dataarray('status'=>"doesn't connect DB"));
    exit();
 }
else{
 
echo "<center>DB 접속 성공!!!</center><br>\n";
 
}
 
// json 데이터 받아서 파싱
$post = json_decode(file_get_contents('php://input'),true);
print_r($post);
 
// 안의 데이터 확인
echo "name: "$post['NAME']."\n"
 
$name = $post['NAME'];
$acuuracy = (float)$post['ACCURACY'];
$time = $post['TIME'];
 
// DB에 쿼리문 보내서 insert
$sql_j =  "INSERT INTO OBJECT_INFO VALUES('".$name."',".$acuuracy.",'".$time."')";
echo "sql_j: "$sql_j."\n";
$result = mysqli_query($link,$sql_j);
 
// 쿼리 실패시
if (!$result) {
    echo 'Could not query:' ."<br>\n";
}
 
 
// 잘 들어갔나 확인
$select = "SELECT * FROM OBJECT_INFO";
$result = mysqli_query($link,$select);
 
if (!$result) {
    die('Could not query:' . mysqli_error());
}
else 
{
    // row 개수만큼 db데이터 출력
    for($i=0;$i<$result->num_rows;$i++)
    {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        printf ("%s (%s) %s<br>\n"$row["NAME"], $row["ACCURACY"],$row["D_DATE"]);
 
    }
}
// db에 데이터 있으면 yes 아니면 no
if($result->num_rows>0)
 echo "yes result"
else
 echo "no result";
//phpinfo();
 
?>
cs
Comments