1開啟端口
https://blog.csdn.net/a497785609/article/details/77944327
安裝方法
sudo apt-get install ufw
使用方法
1.啟用
sudo ufw enable
sudo ufw default deny
作用:開啟了防火牆並隨系統啟動同時關閉所有外部對本機的訪問(本機訪問外部正常)。
2.關閉
sudo ufw disable
3.查看防火牆狀態
sudo ufw status
4.開啟/禁用相應端口
sudo ufw allow 80 允許外部訪問80端口
sudo ufw delete allow 80 禁止外部訪問80 端口
sudo ufw allow from 192.168.1.1 允許此IP訪問所有的本機端口
sudo ufw deny smtp 禁止外部訪問smtp服務
sudo ufw delete allow smtp 刪除上面建立的某條規則
ufw deny proto tcp from 10.0.0.0/8 to 192.168.0.1 port要拒絕所有的流量從TCP的10.0.0.0/8 到端口22的地址192.168.0.1
可以允許所有RFC1918網絡(局域網/無線局域網的)訪問這個主機(/8,/16,/12是一種網絡分級):
sudo ufw allow from 10.0.0.0/8
sudo ufw allow from 172.16.0.0/12
sudo ufw allow from 192.168.0.0/16
推薦設置
sudo apt-get install ufw
sudo ufw enable
sudo ufw default deny
這樣設置已經很安全,如果有特殊需要,可以使用sudo ufw allow開啟相應服務
但是必須關閉防護牆,不讓遠程界面就用不了了
如果是SSH或者VNC登錄,就別試這個功能了。不然就不能遠程登錄了。
還要連上屏幕,關閉防火牆才能,繼續玩耍。
sudo
ufw disable
2搭建flask服務器
https://segmentfault.com/a/1190000017330435
安裝Flask
使用pip安裝Flask:
pip install flask
1運行簡單例程
現在,讓我們完整地看一下app.py的整個代碼:
from flask import * app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ =="__main__": app.run((host=’0.0.0.0’,port=8080)
然后運行起來:
* Serving Flask app "app" (lazy loading) * Environment: production * Debug mode: on * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 770-937-705
現在就可以打開瀏覽器訪問http://127.0.0.1:8080/
了:
2 運行網頁版本
同目錄創建templates文件夾,所有網頁放進去
我們將模板文件按如下路徑放置:
Apps folder /app.py templates |-/index.html
使用模板時,視圖函數應當返回render_template()
的調用結果。例如下面的代碼片段渲染模板index.html
,並將渲染結果作為視圖函數的返回值:
from flask import Flask, render_template app = Flask(__name__) @app.route('/hello') def hello(): return render_template('index.html', name="Alex") if __name__ == '__main__': app.run(debug = True)
在上面的代碼中,模板文件index.html
依賴於變量name
,其內容如下:
<html> <body> {% if name %} <h2>Hello {{ name }}.</h2> {% else %} <h2>Hello.</h2> {% endif %} </body> </html>
模板文件的語法擴充了HTML,因此可以使用變量和邏輯。
在瀏覽器中訪問http://127.0.0.1:8080/hello/alex
:
3 使用表單
每個web應用都需要使用表單來采集用戶數據。現在讓我們使用Flask框架創建一個簡單的表單來收集用戶的基本信息,例如名稱、年齡、郵件、興趣愛好等,我們將這個模板文件命名為bio_form.html
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>Bio Data Form</h1> <form action="showbio"> <label>Username</label> <input type="name" name="username"><br> <label>Email</label> <input type="email" name="email"><br> <label>Hobbies</label> <input type="name" name="hobbies"><br> <input type="submit" name=""> </form> </body> </html>
視圖函數bio_data_form
同時支持POST和GET請求。GET請求將渲染bio_form.html
模板,而POST請求將重定向到showbio
:
@app.route('/form', methods=['POST', 'GET']) def bio_data_form(): if request.method == "POST": username = request.form['username'] age = request.form['age'] email = request.form['email'] hobbies = request.form['hobbies'] return redirect(url_for('showbio', username=username, age=age, email=email, hobbies=hobbies)) return render_template("bio_form.html")
下面是showbio的實現:
@app.route('/showbio', methods=['GET']) def showbio(): username = request.args.get('username') age = request.args.get('age') email = request.args.get('email') hobbies = request.args.get('hobbies') return render_template("show_bio.html", username=username, age=age, email=email, hobbies=hobbies)
以及show_bio.html的內容:
<!DOCTYPE html> <html> <head> <title>Bio-Data Details</title> </head> <body> <h1>Bio-Data Details</h1> <hr> <h1>Username: {{ username }}</h1> <h1>Email: {{ email }}</h1> <h1>Hobbies: {{ hobbies }}</h1> </body> </html>
from flask import * app = Flask(__name__) #測試1 根目錄簡單 @app.route('/') def hello_world(): return 'Hello, World!' #測試2 指定目錄 攜帶參數 @app.route('/hello') def hello(): return render_template('index.html', name="Alex") #測試3 指定目錄 獲取請求參數+動態生成網頁 @app.route('/showbio', methods=['GET']) def showbio(): username = request.args.get('username') age = request.args.get('age') email = request.args.get('email') hobbies = request.args.get('hobbies') return render_template("show_bio.html", username=username, age=age, email=email, ) #測試4 指定目錄 獲取請求post表單參數+重定向到測試3 @app.route('/form', methods=['POST', 'GET']) def bio_data_form(): #第一次獲取網頁后,網頁里面有post請求處理 if request.method == "POST": username = request.form['username'] age = request.form['age'] email = request.form['email'] #網頁重新定向 return redirect(url_for('showbio', username=username, age=age, email=email, )) #第一次訪問 直接返回網頁 return render_template("bio_form.html") # if __name__ =="__main__": app.run(host="0.0.0.0",port=8080)
網頁開啟管教口
import RPi.GPIO as GPIO from flask import Flask, render_template, request app = Flask(__name__) GPIO.setmode(GPIO.BCM) pins = { 24 : {'name' : 'TV', 'state' : GPIO.LOW}, 25 : {'name' : 'Light', 'state' : GPIO.LOW} } for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) @app.route("/") def main(): for pin in pins: pins[pin]['state'] = GPIO.input(pin) templateData = { 'pins' : pins } return render_template('main.html', **templateData) @app.route("/<changePin>/<action>") def action(changePin, action): changePin = int(changePin) deviceName = pins[changePin]['name'] if action == "on": GPIO.output(changePin, GPIO.HIGH) message = "Turned " + deviceName + " on." if action == "off": GPIO.output(changePin, GPIO.LOW) message = "Turned " + deviceName + " off." if action == "toggle": GPIO.output(changePin, not GPIO.input(changePin)) message = "Toggled " + deviceName + "." for pin in pins: pins[pin]['state'] = GPIO.input(pin) templateData = { 'message' : message, 'pins' : pins } return render_template('main.html', **templateData) if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True)
如何開啟局域網
flask默認開啟的網站是本地的127.0.0.1:5000
現在把已經有的本機訪問改成局域網訪問
app.run(host=’0.0.0.0’,port=8080)
port可以不配置,默認還是5000,如果修改則是修改后的內容
局域網訪問采用 主機IP地址+端口號
在windows下搭建后需要開啟防火牆的入站規則,指定端口號
3具體開發示例
動態折線
https://blog.csdn.net/weixin_39561473/article/details/86608661
python文件
from flask import Flask,render_template from flask import jsonify #數據轉為json,並以字典的形式傳回前端 import datetime,random #導入時間和隨機數模塊 app = Flask(__name__) #綁定app #函數一:關聯頁面 @app.route('/') #路由 def image(): return render_template('image.html') #函數二:生成數據 @app.route('/setData/') #路由 def setData(): now = datetime.datetime.now().strftime('%H:%M:%S') data = {'time':now,'data':random.randint(1,10)} #print(data) return jsonify(data) #將數據以字典的形式傳回 if __name__ =="__main__": app.run(host="0.0.0.0",port=8080)
網頁代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="panel" height="330px" width="700px"> </canvas> <!--折線圖位置--> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <!--導入jQuery--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> <!--導入jQuery--> <script> $(function () { var can = $('#panel').get(0).getContext('2d'); /*繪制類型*/ //定義圖標的數據 var canData = { labels:["a","b","c","d","e","f"], /*初始x軸數據*/ datasets : [ { //折線的填充顏色 fillColor:"rgba(255,255,255,0.1)", //線條顏色: strokeColor:"rgba(255,255,0,1)", //y軸初始數據: data:[1,3,2,1,5,4] } ] }; //繪制圖片 var line = new Chart(can).Line(canData); var int = setInterval(function () { //設置定時器 $.ajax( { url:"/setData/", //從setData函數中獲取數據 type:"get", data:"", success:function (data) { line.addData( [data["data"]], //y軸,因為同一個x軸可以有多個折線 data["time"] //x軸 ); //保持x軸只有8個數據,要不隨着時間推移x軸會越來越長 var len = line.datasets[0].points.length; if(len>8){ line.removeData() } } } ) },1000) }) </script> </body> </html>
https://blog.csdn.net/qq_34803821/article/details/86240096
如果你想在網頁上點擊按鈕,並且讓樹莓派接收到響應,並做響應的處理,實現網頁上與樹莓派進行數據交互以及一些數據渲染,那么希望這篇文章對你有所幫助:
源碼放在git:https://github.com/StarFishing/ardunio/tree/master
樹莓派與Arduino進行通信可以參考另一篇文章:https://blog.csdn.net/qq_34803821/article/details/86238387
首先先看效果圖,總體效果我會放在文章末尾
這是已經寫好的HTML頁面,我截取了其中一部分,當我們點擊藍色按鈕,樹莓派打開Arduino板上的風扇,點擊紅色按鈕關閉風扇
百度網盤工程:
鏈接:https://pan.baidu.com/s/1JIh-XsiJI5PbGt9G7pOjWQ
提取碼:zu5x
復制這段內容后打開百度網盤手機App,操作更方便哦
環境配置
准備材料:
樹莓派上安裝flask:sudo pip install flask
python 串口讀取:sudo pip insall pyserial
我們針對樹莓派進行講解,我們如何實現點擊的相應,讓樹莓派接收到事件呢?
樹莓派服務器
# codinf:utf-8 from flask import Flask, render_template, Response, request import serial port = "/dev/ttyACM0" app = Flask(__name__) single = serial.Serial(port, 9600) single.flushInput() @app.route('/') def index(): single.flushOutput() single.flushInput() single.write('8') response = str(single.readline().decode()) if response.startswith('hum:'): # cut int num hum = response[5:7] tem = response[-6:-3] templateData = { 'tem': tem, 'hum': hum } print(response.strip('\n')) return render_template('index.html', **templateData) @app.route('/fopen', methods=['POST', 'GET']) def fopen(): if request.method == 'GET': return render_template('index.html') else: single.flushOutput() single.write('1') return "Open OK" @app.route('/fclose', methods=['POST']) def fclose(): single.flushOutput() single.write('2') return "Close OK" @app.route('/lclose', methods=['POST']) def lclose(): # single.flushOutput() # single.write('3') return "LED Close OK" @app.route('/lopen', methods=['POST']) def lopen(): # single.flushOutput() # single.write('4') return "LED Open OK" if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True, threaded=True) © 2019 GitHub, Inc.
在HTML里面,我們做這樣一件事情:
將我們的點擊事件異步提交到相應的路由下
<div class="open"> <span class="warning">高溫警告:</span> <span class="text">已自動為您打開風扇</span> <span class="close">關/開風扇:</span> <i id="close"></i ><i id="open"></i> </div>
$('.open i').click(function() { if (this.id == 'close') { $.post('/fclose', this.id, function(data, status) {}) } if (this.id == 'open') { $.post('/fopen', this.id, function(data, status) {}) } })