• R/O
  • HTTP
  • SSH
  • HTTPS

コミット

タグ
未設定

よく使われているワード(クリックで追加)

javac++androidlinuxc#windowsobjective-ccocoa誰得qtpythonphprubygameguibathyscaphec計画中(planning stage)翻訳omegatframeworktwitterdomtestvb.netdirectxゲームエンジンbtronarduinopreviewer

コミットメタ情報

リビジョン3ee713ff1e3238f2c6dd83de05af0b2eca272696 (tree)
日時2019-05-06 11:27:11
作者kazuhiro_kondow <simauma.circus@gmai...>
コミッターkazuhiro_kondow

ログメッセージ

使用するサーバーをherokuに変更した関係でDBをPostgresqlに変更

変更サマリ

差分

--- a/DataBaseContxtMngPostgres.py
+++ b/DataBaseContxtMngPostgres.py
@@ -4,23 +4,25 @@ import psycopg2
44 class UseDataBase:
55 """DataBaseの接続と切断を処理するコンテキストマネージャクラス"""
66 def __init__(self) -> None:
7- self.DATABASE_URL = os.environ['DATABASE_URL']
8-
7+ self.database_url = os.environ['DATABASE_URL']
8+ if os.getenv('APP_ENV',False) is False:
9+ print('APP_ENV False')
10+ self.conn = psycopg2.connect(self.database_url,sslmode='require')
11+ else:
12+ print('APP_ENV True')
13+ self.conn = psycopg2.connect(self.database_url)
914
1015 def __enter__(self) -> 'cursor':
16+ print('call UseDataBase enter')
1117 try:
12- if os.getenv('APP_ENV',False) is False:
13- self.conn = psycopg2.connect(self.DATABASE_URL,sslmode='require')
14- else:
15- self.conn = psycopg2.connect(self.DATABASE_URL)
16- self.cursor = self.conn.cursor(dictionary=True)
18+ self.cursor = self.conn.cursor()
1719 return self.cursor
1820 except psycopg2.Error as err:
21+ print('err.pgerror')
1922 print(err.pgerror)
2023 except Exception as err:
2124 print('Other errors')
2225
23-
2426 def __exit__(self, exc_type, exc_value, exc_trace) -> None:
2527 self.conn.commit()
2628 self.cursor.close()
--- a/appmain.py
+++ b/appmain.py
@@ -1,39 +1,34 @@
1-import logging
2-from logging.config import dictConfig
31 from flask import Flask, request, render_template
4-from DataBaseContxtMng import UseDataBase
5-import json
6-import ctypes2python
7-
8-logdict = json.load(open('LoggingConfigDict.json','r'))
9-dbconfig = json.load(open('dbconfig.json','r'))
10-dictConfig(logdict)
2+from DataBaseContxtMngPostgres import UseDataBase
3+import struct
114
125 app = Flask(__name__)
136
147 def do_dataentry(req: 'flask_request') -> str:
158 """Iot端末からのデータをDBに追加する"""
169 try:
17- app.logger.info("call do_dataentry")
18- rcv_data = ctypes2python.rcvdatacnv(req.form['data'])
19- app.logger.info(rcv_data)
20- with UseDataBase(dbconfig) as cursor:
21- insert_SQL = ("insert into ReceiveTest "
22- "(nodeid,temperature,humidity,photosensitive,soilmoisture,humaninduct,soiltemperature)"
23- "values (%(nodeid)s,%(temperature)s,%(humidity)s,%(photosensitive)s,%(soilmoisture)s,%(humaninduct)s,%(soiltemperature)s);")
24- cursor.execute(insert_SQL, rcv_data )
25- app.logger.info("finish do_dataentry")
26- return 'Success'
10+ print("call do_dataentry")
11+ print(req.form['data'])
12+ rcv_data = cnv_rcvdata2dict(req.form['data'])
13+ print(rcv_data)
14+ insert_SQL = ("insert into ReceiveTest "
15+ "(nodeid,temperature,humidity,photosensitive,soilmoisture,humaninduct,soiltemperature)"
16+ "values (%(nodeid)s,%(temperature)s,%(humidity)s,%(photosensitive)s,%(soilmoisture)s,%(humaninduct)s,%(soiltemperature)s);")
17+ print("insert_SQL:[%s]" % insert_SQL)
18+ with UseDataBase() as cursor:
19+ cursor.execute(insert_SQL, rcv_data)
20+ print("finish do_dataentry")
21+ return 'Success'
2722 except Exception as err:
28- app.logger.error(type(err)) # the exception instance
29- app.logger.error(err.args) # arguments stored in .args
30- app.logger.error(err) # __str__ allows args to be printed directly,
23+ print(type(err)) # the exception instance
24+ print(err.args) # arguments stored in .args
25+ print(err) # __str__ allows args to be printed directly,
3126 return 'Failed'
3227
3328 def do_selectdata() -> dict:
3429 """DataBaseからChartに表示するデータを抽出する"""
3530 try:
36- app.logger.info("call do_selectdata")
31+ print("call do_selectdata")
3732 select_SQL = ("select DATE_FORMAT(ReceiveTime, '%m月-%d日 %H時') AS time, "\
3833 " round(AVG(temperature),2) AS temperature,"\
3934 " round(AVG(humidity),2) as humidity,"\
@@ -43,17 +38,43 @@ def do_selectdata() -> dict:
4338 " round(AVG(humaninduct),2) as humaninduct"\
4439 " FROM ReceiveTest "\
4540 " GROUP BY DATE_FORMAT(ReceiveTime, '%m月-%d日 %H時');")
46- with UseDataBase(dbconfig) as cursor:
41+ with UseDataBase() as cursor:
4742 cursor.execute(select_SQL)
4843 result = cursor.fetchall()
49- app.logger.info("finish do_selectdata")
44+ print("select_SQL:[%s]" % select_SQL)
45+ print("finish do_selectdata")
5046 return result
5147 except Exception as err:
52- app.logger.error(type(err)) # the exception instance
53- app.logger.error(err.args) # arguments stored in .args
54- app.logger.error(err) # __str__ allows args to be printed directly,
48+ print(type(err)) # the exception instance
49+ print(err.args) # arguments stored in .args
50+ print(err) # __str__ allows args to be printed directly,
5551 return 'Failed'
5652
53+def cnv_rcvdata2dict(rcv: 'POST_Data') -> dict:
54+ """Arduinoからのバイナリデータを復号して辞書として返す"""
55+ try:
56+ print("call cnv_rcvdata2dict")
57+ if(rcv.isalnum()):
58+ receive = struct.unpack('<BBBffHHfHH',bytes.fromhex(rcv))
59+ rcv_data = {'nodeid':str(receive[0])+str(receive[1])+str(receive[2]),
60+ 'temperature':receive[3],
61+ 'humidity':receive[4],
62+ 'photosensitive':receive[5],
63+ 'soilmoisture':receive[6],
64+ 'soiltemperature':receive[7],
65+ 'humaninduct':receive[8],
66+ 'CRC':receive[9]
67+ }
68+ return rcv_data
69+ else:
70+ print("rcv.isalnum() False!")
71+ return {}
72+ except Exception as err:
73+ print(type(err)) # the exception instance
74+ print(err.args) # arguments stored in .args
75+ print(err) # __str__ allows args to be printed directly,
76+ return {}
77+
5778 @app.route('/')
5879 def index() -> str:
5980 """誤ったHTTPaccessに対する案内"""
@@ -62,22 +83,23 @@ def index() -> str:
6283 @app.route('/dataentry', methods=['POST'])
6384 def node_request() -> str:
6485 """IOT機器からのデータ受信窓口"""
86+ print(request)
6587 respons = do_dataentry(request)
66- app.logger.info(respons)
88+ print(respons)
6789 return respons
6890
6991 @app.route('/showdata')
7092 def show_data() -> str:
7193 """Show entry datas"""
7294 respons = do_selectdata()
73- app.logger.info('show_data')
95+ print('show_data')
7496 return respons
7597
7698 @app.route('/chart')
7799 def show_chart() -> str:
78100 """DBデータを元にチャートを表示する"""
79101 try:
80- app.logger.info("call show_chart")
102+ print("call show_chart")
81103 respons = do_selectdata()
82104 if(respons == 'Failed'):
83105 return respons
@@ -100,10 +122,15 @@ def show_chart() -> str:
100122 photosensitive = lst_photosensitive,soilmoisture = lst_soilmoisture, \
101123 soiltemperature = lst_soiltemperature)
102124 except Exception as err:
103- app.logger.error(type(err)) # the exception instance
104- app.logger.error(err.args) # arguments stored in .args
105- app.logger.error(err) # __str__ allows args to be printed directly,
125+ print(type(err)) # the exception instance
126+ print(err.args) # arguments stored in .args
127+ print(err) # __str__ allows args to be printed directly,
106128 return 'Failed'
107129
130+@app.route('/testchart')
131+def show_testchart() -> str:
132+ """Display Demo Chart"""
133+ return '<!DOCTYPE html><html><head><title>This is test Chart Dir</title></head><body><p><font size="6">This is test Chart Dir</font></p></body></html>'
134+
108135 if __name__ == '__main__':
109- app.run(debug=True)
\ No newline at end of file
136+ app.run(debug=True)