본문 바로가기

PROGRAMMING/PYTHON

[Python3] requests로 웹서버에 데이터 전달하기



  Python 웹서버로 데이터 전송하기

  • UART 통신으로 수신한 데이터를 수신한 시간의 timestamp와 함께 응답값을 요청하지않고 localhost 웹서버에 전송하고자 함.

  Python requests 설치

  • 외부라이브러리이므로 설치가 필요
$ pip3 install requests



  전체 코드


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
import time
import serial
import requests
 
 
def loar_receiver():
    """월태그에 전달한 lora 패킷 분석"""
 
    # UART 세팅
    ser = serial.Serial(port='/dev/ttySAC4', baudrate=115200, timeout=None)
    url = '127.0.0.1'
    while True:
        try:
            data = ser.readline().decode('utf8').replace(' ''').replace('\n''')
            data = data.upper()
 
            # 데이터가 없거나 원하는 데이터 형식에 맞지 않는 데이터가 들어오면
            if not data or data[0!= 'A' or data[2:4!= 'FD'
                continue
 
            # 현재시간 정보 
            now = time.localtime()
            now_time = "%04d-%02d-%02d %02d:%02d:%02d" % 
                (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
 
            # web server용 데이터 준비
            web_data = "%s %s"%(now_time,data)
   
            # requests 라이브러리 이용해서 localhost 
            # flask web server router : /curlc 
            # server content-type = application/json
            r = requests.post('http://%s:8008/curlc'%url, json=web_data) 
 
        except Exception as e:
            pass
 
if __name__ == '__main__':
    loar_receiver()
 
 
cs