views.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # 主業務邏輯中的視圖和路由的定義
  2. import os
  3. import datetime
  4. from flask import render_template, request, session, Response, url_for
  5. # 導入藍圖程序,用於構建路由
  6. from werkzeug.utils import redirect, secure_filename
  7. from . import main
  8. from manage import mqtt
  9. # 導入db,用於操作數據庫
  10. from manage import db, app
  11. # 導入實體類,用於操作數據庫
  12. from ..models import *
  13. import json
  14. from datetime import datetime as dt
  15. from sqlalchemy import text
  16. import socket
  17. import pickle
  18. import cv2
  19. import numpy as np
  20. import math
  21. import threading
  22. import time
  23. from flask_mqtt import Mqtt
  24. import requests
  25. import re
  26. import copy
  27. from selenium import webdriver
  28. from selenium.webdriver.support.ui import Select
  29. from bs4 import BeautifulSoup
  30. from time import sleep as sl
  31. from app import ALLOWED_EXTENSIONS
  32. # 主頁的訪問路徑
  33. @main.route('/')
  34. def main_index():
  35. # 獲取登入信息
  36. if 'id' in session and 'uname' in session and 'status' in session:
  37. username = session['uname']
  38. if session['status'] == 1:
  39. return redirect('/index')
  40. elif session['status'] == 2:
  41. return redirect('/index')
  42. else:
  43. return render_template('sign_in.html')
  44. # 登入頁面的訪問路徑
  45. @main.route('/login', methods=['GET', 'POST'])
  46. def login_views():
  47. if request.method == 'GET':
  48. if 'id' in session and 'uname' in session and 'status' in session:
  49. return redirect('/')
  50. else:
  51. return render_template('sign_in.html')
  52. else:
  53. # 接收前端傳過來的資料
  54. username = request.form['username']
  55. password = request.form['password']
  56. # 使用接收的用戶和密碼到資料庫中查詢
  57. user = User.query.filter_by(username=username, password=password).first()
  58. # 如果用戶存在,將信息保存置session並重定向回首頁,否則回登入頁
  59. if user:
  60. resp = redirect('/')
  61. # 判斷是否有記住密碼
  62. if 'rem' in request.form:
  63. sn = str(user.sn)
  64. max_age = 60 * 60 * 24 * 365
  65. resp.set_cookie("username", username, max_age=max_age)
  66. resp.set_cookie("sn", sn, max_age=max_age)
  67. session['uname'] = user.username
  68. session['id'] = user.sn
  69. session['status'] = user.status
  70. return resp
  71. else:
  72. errMsg = "Wrong login or password"
  73. return render_template('sign_in.html', errMsg=errMsg)
  74. # 註冊頁面的訪問路徑
  75. @main.route('/register', methods=['POST', "GET"])
  76. def register_views():
  77. if request.method == 'GET':
  78. return render_template('registration.html')
  79. else:
  80. # 獲取文本框的值並賦值給user實體對象
  81. user = User()
  82. user.firstname = request.form['firstname']
  83. user.lastname = request.form['lastname']
  84. user.mail = request.form['email']
  85. user.phone = request.form['phone']
  86. user.username = request.form['username']
  87. user.password = request.form['password']
  88. user.status = 1
  89. user.isActive = True
  90. # 將數據保存進資料庫 - 註冊
  91. db.session.add(user)
  92. # 手動提交,目的是為了獲取提交後的user的id
  93. db.session.commit()
  94. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  95. # 完成登入的操作
  96. user = User.query.filter_by(username=user.username).first()
  97. session['id'] = user.sn
  98. session['uname'] = user.username
  99. session['status'] = user.status
  100. return redirect('/')
  101. #登入重設密碼的頁面
  102. @main.route('/reset_password', methods=['POST', 'GET'])
  103. def reset_password_views():
  104. if request.method == 'GET':
  105. if 'mail' in session:
  106. del session['mail']
  107. return render_template('reset_pwd1.html')
  108. else:
  109. #如果有id在session裡,代表從reset_pwd2過來的
  110. if "mail" in session:
  111. new_pwd = request.form['new_pwd']
  112. confirm_pwd = request.form['confirm_pwd']
  113. #判斷密碼是否一致
  114. if new_pwd == confirm_pwd:
  115. mail = session['mail']
  116. user = User.query.filter_by(mail=mail).first()
  117. user.password = new_pwd
  118. db.session.add(user)
  119. del session['mail']
  120. #修改完後回登入頁
  121. return redirect('/login')
  122. else:
  123. errMsg = "Passwords does not match"
  124. return render_template('reset_pwd2.html', errMsg=errMsg)
  125. email = request.form['email']
  126. user = User.query.filter_by(mail=email).first()
  127. if user:
  128. session['mail'] = user.mail
  129. return render_template('reset_pwd2.html')
  130. else:
  131. errMsg = "Wrong email.Please try again"
  132. return render_template('reset_pwd1.html', errMsg=errMsg)
  133. #驗證email訪問路徑
  134. @main.route('/check_email')
  135. def check_email_views():
  136. email = request.args['email']
  137. user = User.query.filter_by(mail=email).first()
  138. if user:
  139. result = {"errMsg":" "}
  140. else:
  141. result = {"pass":" "}
  142. return json.dumps(result)
  143. #驗證username訪問路徑
  144. @main.route('/check_username')
  145. def check_username_views():
  146. username = request.args['username']
  147. user = User.query.filter_by(username=username).first()
  148. if user:
  149. result = {"errMsg":" "}
  150. else:
  151. result = {"pass":" "}
  152. return json.dumps(result)
  153. #用戶主介面的訪問路徑
  154. @main.route('/index', methods=['POST', 'GET'])
  155. def index_views():
  156. username = session['uname']
  157. farm_info = FarmInfo.query.filter_by(user_id=session['id']).first()
  158. purchase_info = PurchaseInfo.query.filter_by(user_id=session['id']).first()
  159. monitor_num = purchase_info.monitor_num
  160. nodes = NodePosition.query.filter_by(user_id=session['id']).all()
  161. node_imgs = NodeImage.query.filter_by(user_id=session['id']).all()
  162. nodeimg_paths = []
  163. for node_img in node_imgs:
  164. nodeimg_paths.append("http://localhost:5555" + node_img.path[3:])
  165. if request.method == 'GET':
  166. path = farm_info.path
  167. if path == '0':
  168. path = False
  169. else:
  170. path = 'http://localhost:5555' + path[3:]
  171. lat = farm_info.loc_lat
  172. lng = farm_info.loc_lng
  173. if lat== '0' or lng == '0':
  174. lat = False
  175. lng = False
  176. return render_template('index.html', params=locals())
  177. else:
  178. pass
  179. #過濾前端傳過來文件副檔名函數
  180. def allowed_file(filename):
  181. return '.' in filename and \
  182. filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
  183. #環境資訊的訪問路徑
  184. @main.route('/env_info/<tid>', methods=['POST', 'GET'])
  185. def env_info_views(tid):
  186. username = session['uname']
  187. purchase_info = PurchaseInfo.query.filter_by(user_id=session['id']).first()
  188. monitor_num = purchase_info.monitor_num
  189. node_info = NodeInfo.query.filter_by(user_id=session['id']).first()
  190. node_info = eval(node_info.node_info)
  191. # print(node_info)
  192. first_monitor = json.dumps(node_info['node' + str(tid)])
  193. if request.method == 'GET':
  194. sensors = SensorList.query.all()
  195. sensor_list = []
  196. for sensor in sensors:
  197. sensor_list.append(sensor.toDict())
  198. return render_template('env_info.html', params=locals())
  199. else:
  200. pass
  201. #監控功能選取的訪問路徑
  202. @main.route('/monitor/<tid>', methods=['POST', 'GET'])
  203. def monitor_views(tid):
  204. node_info = NodeInfo.query.filter_by(user_id=session['id']).first()
  205. node_info = eval(node_info.node_info)
  206. # print(node_info)
  207. if request.method == 'GET':
  208. d = request.args.to_dict()
  209. if d['monitor']:
  210. module_list = node_info['node' + str(tid)][str(d['monitor'])]
  211. return json.dumps(module_list)
  212. return render_template('env_info.html', params=locals())
  213. else:
  214. pass
  215. # 退出的訪問路徑
  216. @main.route('/logout')
  217. def logout_views():
  218. if 'id' in session and 'uname' in session:
  219. del session['id']
  220. del session['uname']
  221. del session['status']
  222. return redirect('/')