Django 實現mqtt web 客戶端

2021-10-09 04:52:05 字數 2405 閱讀 6595

前端html

2.後端**

import paho.mqtt.client as mqtt #mqtt庫檔案

import time

msg=''

task_topic = '' # 客戶端發布訊息主題

address='' # ip位址

username='' # 使用者名稱

password='' # 密碼

client_id = time.strftime('%y%m%d%h%m%s', time.localtime(time.time()))

client = mqtt.client(client_id, transport='tcp')

client.username_pw_set(username, password=password)

def clicent_main(message: str):

"""客戶端發布訊息

:param message: 訊息主體

:return:

"""# time_now = time.strftime('%y-%m-%d %h-%m-%s', time.localtime(time.time()))

#payload =

# publish(主題:topic; 訊息內容)

client.publish(task_topic, json.dumps(message, ensure_ascii=false))

print("successful send message!")

return true

#檢查ip位址

def check_ip(ipaddr):

compile_ip=re.compile('^(1\d|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)$')

if compile_ip.match(ipaddr):

return true

else:

return false

def test(request):

return render(request, 'test.html')

# 表單

def index(request):

return render(request, 'index.html')

res = '無'

# 接收請求資料

def mqtt_client(request):

request.encoding = 'utf-8'

if 'issuetopic' in request.get and request.get['issuetopic']:

global task_topic,msg,address,username,password,res

#message = '你搜尋的內容為: ' + request.get['issuetopic']

message=request.get['address']

task_topic=request.get['issuetopic']

address=request.get['address']

username=request.get['username']

password=request.get['password']

flag=''

if (check_ip(address)):

# 判斷ip是否ping的通

# try:

client.connect_async(address, 1883, 60) # 此處埠預設為1883,通訊埠期keepalive預設60

client.loop_start()

res='連線成功'

flag=1

else:

res='連線失敗'

flag=0

if(flag):

msg = request.get['msg']

clicent_main(msg)

return render(request,'index.html',)

else:

message = '你提交了空表單'

Django實現簡單helloworld

1.主題 web開發 2.環境 1 ubuntu 2 python3.5以上 3 開發工具 4 djiango 1.113.具體操作 1.新建專案hello 用3.6版本python pyenv virtualenv 3.6.4 hello 2.進入專案 pyenv activate hello 3...

django 實現分頁功能

分頁效果 檢視 1 coding utf 8 2 from django.shortcuts import render,get object or 404 3 from django.core.paginator import paginator,pagenotaninteger,emptypag...

Django傳送郵件實現

傳送郵件功能在不少場景下需要使用到,在django中實現這個功能相對其他語言或框架而言是非常簡單的,接下來就來看一下具體的實現步驟。伺服器名稱 伺服器位址 ssl埠 非ssl埠 imap imap.qq.com 993143 smtp smtp.qq.com 465或587 25pop pop.qq...