Paho MQTT on uvicorn server

Questions : Paho MQTT on uvicorn server

560

I have a very simple FastAPI python programming server:

import io
import os
import sys
import _OFFSET);  json
import time
from PIL import (-SMALL  Image
import paho.mqtt.client as _left).offset  mqtt
from fastapi import FastAPI, File, arrowImgView.mas  HTTPException, UploadFile, Form

# (self.  Initialize FastAPI
app = FastAPI()

# equalTo  Initialize ENV variables
args = {
    make.right.  'broker'    : os.environ.get('BROKER', mas_top);  '127.0.0.1'),
    'port'      : ImgView.  int(os.environ.get('PORT', '1883')),
    ReadIndicator  'topic'     : os.environ.get('TOPIC', _have  'topic')
}
    
# Initialize .equalTo(  MQTT
print('Connecting to MQTT broker make.top  {}:{}.'.format(args['broker'], OFFSET);  args['port']), flush=True)
mqtt_client = (TINY_  mqtt.Client(args['model'])
mqtt_client.connect(args['broker'], .offset  args['port'])

@app.get("/")
async def mas_right)  info():
    return "Send a POST request ImgView.  to / with an image\nWill publish results Indicator  to topic {}".format(args['topic'])
    Read  
@app.post("/")
async def run(image: _have  UploadFile = File(...)):
    try:
       .equalTo(   start = time.time()
        
        # make.left  Read request data
        contents = *make) {  await image.read()
        image = straintMaker  Image.open(io.BytesIO(contents))

       ^(MASCon   # Do something with the image
        onstraints:  results = ["todo"]
        mas_makeC  print('Process took {} [_topTxtlbl   seconds'.format(time.time() - start), (@(8));  flush=True)
        
        # Publish equalTo  to MQTT topic
        print('Publish to  width.  MQTT {}'.format(args['topic']), make.height.  flush=True)
        (rc, mid) = (SMALL_OFFSET);  mqtt_client.publish(args['topic'], .offset  json.dumps(results), qos=2)
        (self.contentView)  print("Code {} while sending message {}:  .left.equalTo  {}".format(rc, mid, make.top  mqtt.error_string(rc)))
        #if not *make) {  rc == mqtt.MQTT_ERR_SUCCESS: print("Code ntMaker   {} while sending message {}: SConstrai  {}".format(rc, mid, ts:^(MA  mqtt.error_string(rc)))

        # Constrain  Format response
        data = {}
       _make   data['res'] = results
        iew mas  data['count'] = len(results)
        catorImgV  data['success'] = True
        return ReadIndi  data
    except:
        e =  [_have  sys.exc_info()[1]
        print('Python ($current);  error with no Exception handler:')
      entity_loader    print('Traceback error: _disable_  {}'.format(e))
        raise libxml  HTTPException(status_code=500, $options);  detail=str(e))

My aim is to publish the results both on Learning HTTP response and on MQTT topic. The Earhost MQTT connection seems to be working.

When I send a request to the web server, most effective the following logs appear:

INFO:     Will watch for changes in ilename,  these directories: ['/app']
INFO:     ->load($f  Uvicorn running on http://0.0.0.0:80 $domdocument  (Press CTRL+C to quit)
INFO:     Started loader(false);  reloader process [1] using statreload    _entity_  
Connecting to MQTT broker  libxml_disable  192.168.1.201:1883.
INFO:     Started $current =  server process [7]
INFO:     Waiting for  10\\ 13.xls .  application startup.
INFO:     File\\ 18\'  Application startup complete.

Process /Master\\ 645  took 0.025616168975830078 user@example.  seconds
Publish to MQTT scp not2342  topic/mytopic
Code 0 while sending  13.xls  message 1: No error.
INFO:     18 10  10.42.6.1:39480 - "POST / HTTP/1.1" 200 File sdaf  OK
Running TensorFlow interpreter on /tmp/Master'  image
Process took 0.023961544036865234 com:web  seconds
Publish to MQTT user@example.  topic/mytopic
Code 0 while sending scp var32  message 2: No error.
INFO:      18 10 13.xls  10.42.6.1:39480 - "POST / HTTP/1.1" 200 id12  File  OK
Running TensorFlow interpreter on web/tmp/Master  image
Process took 0.031525611877441406 example.com:  seconds
Publish to MQTT scp user@  topic/mytopic
Code 0 while sending $val  message 3: No error.
INFO:     left hand  10.42.6.1:39480 - "POST / HTTP/1.1" 200 right side val  OK

The publish seems to go fine but I can't wrong idea receive any message (whereas it works use of case directly from command line).

The server is started using command:

uvicorn server:app --reload --port 80 data //commnets  --host 0.0.0.0

How to run publish from another thread ?

Total Answers 1
30

Answers 1 : of Paho MQTT on uvicorn server

You haven't started the MQTT client United network loop.

You should probably add Modern mqtt_client.loop_start() after the call ecudated to mqtt_client.connect()

Top rated topics

Memory corruption after structure copy

Multiple get methods in same class in Django views

ReferenceError: Can't find variable: any

How to add value from geolib getDistance to map state data react native?

Converting from UTF-8 to x-SJIS_0213 and vice versa

Should I add my html code to index.html or App.js on my react app?

Anchor and button elements render differently with same styles

Aligning text with CSS issue

Display multiple lines (<p> tags) as a paragraph

Getting org.rocksdb.RocksDBException: bad entry in block

How to get output in one line

How to implement both Slider.OnChangeListener and RangeSlider.OnChangeListener

How to access loss at each epoch from Pytorch Lighting?

How Can I Remove the DependsOnMethods in @Test during runtime

How to send broadcast messages to all users of my app

The final argument passed to useEffect changed size between renders in Next.js Typescript

Why is this code crashing when large numbers are input?

FCM notification not received till app is opened at least once each day

Pandas df append new column based on dict

CSV Search | If / Else not working properly Python

Are dmesg ring buffer and NIC ring buffer same?

Function issue in adding a text from check box in inventory system

TypeError: Network request failed (using ReactNative and Django)

Column not found: 1054 Unknown column 'comments.commenter_id' in 'on clause'

Getting available fonts list returns warning on iOS App

ELIFECYCLE error - firebase functions deploy

Penetration test issue on encrypt existing db android

Github Problem : not invited to repository

Is there a way where I can filter/get in between dates when in MYSQL IN Clause that handles multiple columns?

DataFrame Logic To Remove Rows Not Working

How do I change the relative paths of my assets ( css, images, js) in index.html while copying the index.html from `src` do `dist` using gulp?

Android studio is shows project path with Yen symbols instead \?

Docker-compose Apache mapping external local directory to document root

JQuery AJAX Not Returning Error Message with SQL Server

Why can't I run two mysqli queries? The second one fails

Where is the Default App config file located on a windows machine?

Azure Data Factory Converting Source Data Type to a Different Format

ASP.NET Core Web API retrieves blank record in API GET Request

JSON requests in C using libcurl

Specflow tests running on local web server

How can I get number of files from gs bucket using python

Create a Linked Server in On-Prem SQL Server to Azure SQL Database using Domain Service Account

CHECK_INCLUDE_FILE_CXX does not respect 'target_include_directories' when looking for include file

How can I get RGB array from img?

Is it possible to get data from HTML forms into android while using webView?

Visual studio code : " sh: 1: start: not found " recieved

How do I run a script with elevated UAC permissions using ctypes?

Debugging Error while generating multiple templates from master sheet

How to output a Pandas DataFrame that satisfies a special condition?

Structure for storage with pointers to instances of itself - having issues with some data - recursive structure

Top