簡體   English   中英

如何在谷歌應用引擎上運行用 python 編寫的 MQTT 訂閱者腳本

[英]How to run MQTT subscriber scripts written in python on google app engine

我為 MQTT 訂閱者編寫了一個 python 腳本,它在本地運行良好。

Python訂閱者腳本

import paho.mqtt.client as mqtt
import os,json

filePath = "logs.csv"

def initiateFile():
    if (os.path.exists(filePath) == False):
        fileObj = open(filePath, "w")
        fileObj.write("Label,x,y,z\n")

def readFile():
    data = open(filePath,'r').read()
    return data

def decodeJson(jsonString):
    jsonObject = json.loads(jsonString)
    label = jsonObject.keys()[0]
    x = jsonObject[label]['x']
    y = jsonObject[label]['y']
    z = jsonObject[label]['z']
    return label.encode("utf-8")+","+x+","+y+","+z;

def writeInFile(newData):
    oldData = readFile()
    fileObj = open(filePath, "w")
    fileObj.write(oldData+newData+"\n")

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc)+" "+str(client))
    client.subscribe("sensors/test")
    initiateFile()

def on_message(client, userdata, msg):
    print msg.payload
    writeInFile(decodeJson(msg.payload))

def on_disconnect(client, userdata, rc):
    print("Disconnect, reason: " + str(rc))
    print("Disconnect, reason: " + str(client))

client = mqtt.Client()
client.username_pw_set(username, password)
client.connect(broker,port)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
client.on_disconnect = on_disconnect

但是當我嘗試在谷歌雲上部署它時,出現“ImportError: No module named paho.mqtt.client”錯誤。

然后我嘗試了以下解決方案但出現錯誤

1.) 在 app.yaml 中聲明 paho-mqtt 庫

runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: main.app

libraries:
- name: paho-mqtt
  version: "1.3.0"

***ERROR: (gcloud.app.deploy) An error occurred while parsing file: [C:\Users\uni5p_000\Desktop\RMIT_Studies\Sem_1\Cloud_Computing\Practical\GOOGLE\python-docs-samples\appengine\standard\hello_world\app.yaml]
the library "paho-mqtt" is not supported
  in "C:\Users\uni5p_000\Desktop\RMIT_Studies\Sem_1\Cloud_Computing\Practical\GOOGLE\python-docs-samples\appengine\standard\hello_world\app.yaml", line 11, column 19***

2.) 在 Cloud shell 上 pip install paho-mqtt

***OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.3.0.dist-info'***

現在如何進行?

Google 的文檔解釋了如何在本地lib目錄下安裝庫。

  1. 創建一個目錄來存儲您的第三方庫,例如 lib/。

mkdir lib

  1. 使用帶有 -t 標志的 pip(版本 6 或更高版本)將庫復制到您在上一步中創建的文件夾中。 例如:

pip install -t lib/ <library_name>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM