[Raspberry] Triển khai Web application trên Raspberry Pi Part 6

Trong bài này, mình sẽ hướng dẫn các bạn cấu hình data SQLite3 hiển thị trên webserver.

1. Download sqlite3 trên raspberry:
 sudo apt-get install sqlite3  

2. Chỉnh sửa file env_log.py như nội dung bên dưới:
 import sqlite3  
 import sys  
 import Adafruit_DHT  
 def log_values(sensor_id, temp, hum):  
      conn=sqlite3.connect('/var/www/lab_app/lab_app.db') #It is important to provide an  
                                       #absolute path to the database  
                                       #file, otherwise Cron won't be  
                                       #able to find it!  
      curs=conn.cursor()  
      curs.execute("""INSERT INTO temperatures values(datetime(CURRENT_TIMESTAMP, 'localtime'),  
      (?), (?))""", (sensor_id,temp))  
      curs.execute("""INSERT INTO humidities values(datetime(CURRENT_TIMESTAMP, 'localtime'),  
      (?), (?))""", (sensor_id,hum))  
      conn.commit()  
      conn.close()  
 humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)  
 # If you don't have a sensor but still wish to run this program, comment out all the   
 # sensor related lines, and uncomment the following lines (these will produce random  
 # numbers for the temperature and humidity variables):  
 # import random  
 # humidity = random.randint(1,100)  
 # temperature = random.randint(10,30)  
 if humidity is not None and temperature is not None:  
      log_values("1", temperature, humidity)       
 else:  
      log_values("1", -999, -999)  

3. Chạy file env_log.py
 root@raspberrypi:/var/www/lab_app# python env_log.py   

4. Xem file lab_app.db:
 root@raspberrypi:/var/www/lab_app# sqlite3 lab_app.db   

5. Xem dữ liệu hiện tại trong database:
 sqlite> select * from temperatures;  

 sqlite> select * from humidities;  

6. Chỉnh sửa file lab_app.py(Copy nội dung dưới đây vào file):
 from flask import Flask, request, render_template  
 app = Flask(__name__)  
 app.debug = True # Make this False if you are no longer debugging  
 @app.route("/")  
 def hello():  
   return "Hello World!"  
 @app.route("/lab_temp")  
 def lab_temp():  
      import sys  
      import Adafruit_DHT  
      humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)  
      if humidity is not None and temperature is not None:  
           return render_template("lab_temp.html",temp=temperature,hum=humidity)  
      else:  
           return render_template("no_sensor.html")  
 @app.route("/lab_env_db")  
 def lab_env_db():  
      import sqlite3  
      conn=sqlite3.connect('/var/www/lab_app/lab_app.db')  
      curs=conn.cursor()  
      curs.execute("SELECT * FROM temperatures")  
      temperatures = curs.fetchall()  
      curs.execute("SELECT * FROM humidities")  
      humidities = curs.fetchall()  
      conn.close()  
      return render_template("lab_env_db.html",temp=temperatures,hum=humidities)  
 if __name__ == "__main__":  
   app.run(host='0.0.0.0', port=8080)  

7. Chỉnh sửa file lab_env_db.html(Copy nội dung dưới đây vào file):
Trong đây, có sử dụng jinja để trích xuất dữ liệu từ database.
 <!DOCTYPE html>  
 <html lang="en">  
  <head>  
   <!-- Basic Page Needs  
   –––––––––––––––––––––––––––––––––––––––––––––––––– -->  
   <meta charset="utf-8">  
   <title>Lab Conditions by RPi</title>  
   <meta name="description" content="Lab conditions - RPi">  
   <meta name="author" content="Peter Dalmaris">  
   <!-- Mobile Specific Metas  
   –––––––––––––––––––––––––––––––––––––––––––––––––– -->  
   <meta name="viewport" content="width=device-width, initial-scale=1">  
   <!-- FONT  
   –––––––––––––––––––––––––––––––––––––––––––––––––– -->  
   <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">  
   <!-- CSS  
   –––––––––––––––––––––––––––––––––––––––––––––––––– -->  
   <link rel="stylesheet" href="/static/css/normalize.css">  
   <link rel="stylesheet" href="/static/css/skeleton.css">  
   <!-- Favicon  
   –––––––––––––––––––––––––––––––––––––––––––––––––– -->  
   <link rel="icon" type="image/png" href="/static/images/favicon.png">  
  </head>  
  <body>  
   <div class="container">  
    <div class="row">  
     <div class="one-third column" style="margin-top: 5%">  
      <strong>Showing all records</strong>          
      <h2>Temperatures</h2>            
       <table class="u-full-width">  
        <thead>  
         <tr>  
          <th>Date</th>  
          <th>&deg;C</th>              
         </tr>  
        </thead>  
        <tbody>  
         {% for row in temp %}  
         <tr>  
          <td>{{row[0]}}</td>  
          <td>{{'%0.2f'|format(row[2])}}</td>  
         </tr>  
         {% endfor %}  
        </tbody>  
       </table>   
       <h2>Humidities</h2>  
       <table class="u-full-width">  
        <thead>  
         <tr>  
          <th>Date</th>  
          <th>%</th>              
         </tr>  
        </thead>  
        <tbody>  
         {% for row in hum %}  
         <tr>  
          <td>{{row[0]}}</td>  
          <td>{{'%0.2f'|format(row[2])}}</td>  
         </tr>       
         {% endfor %}  
        </tbody>  
       </table>                         
     </div>  
   </div>        
  </body>  
 </html>  

8. Sau đó, chạy server trên ras lên bằng cách nhập vào terminal:
 root@raspberrypi:/var/www/lab_app# python lab_app.py

9. Sau đó, chạy server lên bằng cách chạy browser và nhập vào http://ipraspberry:8080/lab_env_db.
OK nhé. Hôm nay, mình sẽ hướng dẫn tới đây thôi!!! Hôm sau, mình sẽ hướng dẫn các bạn cấu hình server hiện lên time của các dữ liệu đo của ras.

Nếu có bất kỳ câu hỏi nào thì cứ thoải mái mail cho tôi nhé. 😋😋😋

Bài đăng phổ biến từ blog này

Hash Map Trong Python

Stack And Queue Trong Python