I am trying to take info from my python program and update this real time on the web page.
I am trying to use node-red and communicate via web sockets.
My python program is below:
#!/usr/bin/python
import time
import websocket
ws = websocket.WebSocket();
ws.connect("ws://localhost:1880/ws/example")
count = 0;
while(count < 50):
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
time.sleep(5)
count = count + 1
ws.close()
Using Node-red I have set up my flow as follows:
Node-Red Flow
However when I run them both, my python program says it is sending the message, however the node red console is returning null for the msg value.
Please check your settings.js file -- do you have a url prefix defined for either httpRoot or httpNodeRoot?
For instance, in my project, when I add a new websocket config node, this info box is shown:
By default, payload will contain the data to be sent over, or received from a
websocket. The listener can be configured to send or receive the entire message
object as a JSON formatted string. This path will be relative to /red.
If so, I believe you will have to modify the url in your python code, like so:
ws.connect("ws://localhost:1880/red/ws/example")
substituting your prefix, of course...
Related
Suppose I have two scripts - one is for cloudfront(cf),and another elb.I have some assigned value in json inside a queue(Rabbitmq), called request queue.when I run my elb scripts it should get only the msg with file_type=elb
{'file_type':'elb','elb_name':'name1','customer_id':'1','s3_bucket':'elb-logs-bucket'}
when I run my cf scripts it should get only the msg with file_type=cf
{'file_type':'cf','cf_name':'name1','customer_id':'1','s3_bucket':'cf-logs-bucket'}
My below code works only for the first msg I published to the queue, not type.Anyone can provide the idea what can I do to get file_type=cf msg from cf scripts and vice-versa..I am using default exchange
import json
import pika
import logging
def get_rmq_request_queue(channel,connection,req_queue_name):
payload_dict={}
try:
queue_message=channel.basic_get(queue=req_queue_name,no_ack=False)
payload=queue_message[2]
print payload
print payload
payload_dict=json.loads(payload)
return payload_dict
except Exception as e:
payload_dict={}
payload_dict['error']=str(e)
return payload_dict
main():
res_req_que=get_rmq_request_queue(channel,connection,req_queue_name)
if 'error' not in res_req_que:
s3_bucket=res_req_que['s3_bucket']
customer_id=res_req_que['customer_id']
file_type=res_req_que['file_type']
cf_name=res_req_que['cf_name']
I might have many messages in a queue, the challenge is I need to get the recent message with file type...
One of the points of RabbitMQ is that you can define queues to bind to exchanges with particular routing keys. You should use the type parameter as part of your routing key, then bind your queue so that it listens to the type you want.
See for example part 4 of the RabbitMQ tutorial.
I'm completely new to Python (v2.7) and I need to write a simple program that runs continuously, listens to a gmail account and calls a function when said account receives an email. So far it seems like using either Python's built-in IMAP or SMTP libraries seems like the best option but I'm not very familiar with them, let alone Python itself.
What I've come up with so far is able to connect to the email and find the most recent email via IMAP4 but it's lacking a way to continuously check whether a new email has been received:
(Source)
import imaplib
import email
#logs in to the desired account and navigates to the inbox
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email#gmail.com','password')
mail.list()
mail.select('inbox')
result, data = mail.search(None,'ALL')
#retrieves the latest (newest) email by sequential ID
ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]
Any help on how I can adjust this to continuously run and check for new incoming messages would be great. Thanks!
Use the threading module and subclass threading.Thread. Documentation can be found here: https://docs.python.org/2/library/threading.html
import threading
import time
class MailThread(threading.Thread):
then your code goes into run() where you have to add some delay. Let's say 1000 seconds.
def run():
#your code here
time.sleep(1000)
The last section of your script looks like this
if __name__ == '__main__':
mail_thread = MailThread()
mail_thread.start()
# do other stuff
OR
Just use a while(True) loop with time.sleep() and a break once you got mail.
I'm following this tutorial to send GCM message from a server via a python script.
I've downloaded the GcmDemo that can successfully send messages to itself using my project num, server API key and reg id.
But no way to do it from python.
I've registered the client:
06-13 09:47:45.682 2272-32480/com.google.android.gcm.demo I/GcmDemo﹕ registration succeeded.
senderId: 11xxxxxxx07
token: fxq...xxxx..r5
My server API key:
The python script on the server:
from gcm import *
gcm = GCM("AIza...xxx...XQ")
data = {'ciao ciao': 'test message', 'param2': 'value2'}
reg_id = 'fxq...xxxx..r5'
gcm.plaintext_request(registration_id=reg_id, data=data)
No error messages but no messages received.
Is there a way to log and see where the problem is ?
The client doesn't react (log on Android Studio set to verbose, no log at all).
Any idea ?
The google project console just shows logs till 30 May.
I'm not using Python anymore as I switched to PHP but I had the same problem there and solved adding the icon field to the "data". So adding something like:
data = {'icon' : '#drawable/myAwesomeIcon', ...}
should solve the problem.
For me it was not working when i put dry_Run =True, but worked on removing drun_Run.dry_Run=True was giving me fake_message_id.
I am researching what it would take to make a web app that would interact with e-mails directly. Like you would send to something#myapp.com and the app would tear it apart and determine who it's from, if they are in the DB, what is the subject line, etc.
I am working with/most familiar with python and flask.
Could anyone get me started in the right direction of how to get an e-mail to interface with my flask app code?
There are several approach you can take:
write some code which uses IMAP or POP to retrieve emails and process them. Either run this from a crontab (or something similar) or add it to your flask app and trigger it in there, either through a crontab that requests a magic URL or setting up a custom timer thread.
configure your MTA to deliver email for something#myapp.com by feeding it to a program you write (for example in Exim you could use a pipe transport) . In that program you can either process it directly, or do something like POSTing it to your flask app.
I've done something along these lines recently, with a simple bookmarking web-app. I have the usual bookmarklet way of bookmarking something to it, but I also wanted to be able to e-mail links to it from apps like Reeder on my iPhone and whatever. You can see what I ended up with on GitHub: subMarks.
I use Google Apps for your Domain for my email, so I created a special address for my app to look at - I really didn't want to try building/configuring my own e-mail server.
the mail_daemon.py file from above is run as a cron job every 5 minutes. It connects to the email server using the poplib Python package, processes the emails that are there and then disconnects (one part I feel compelled to point out is that I check that the emails are from me before they are processed :) )
My Flask app then provides the front end to the bookmarks, displaying them from the database.
I decided not to put the email handling code into the actual flask app, because it can be rather slow and would only run when the page was visited, but you could do this if you wanted.
Here's some barebones code to get things going:
import poplib
from email import parser
from email.header import decode_header
import os
import sys
pop_conn = poplib.POP3_SSL('pop.example.com')
pop_conn.user('my-app#example.com')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message into an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
# check message is from a safe recipient
if 'me#example.com' in message['from']:
# Get the message body text
if message['Content-Type'][:4] == 'text':
text = message.get_payload() #plain text messages only have one payload
else:
text = message.get_payload()[0].get_payload() #HTML messages have more payloads
# decode the subject (odd symbols cause it to be encoded sometimes)
subject = decode_header(message['subject'])[0]
if subject[1]:
bookmark_title = subject[0].decode(subject[1]).encode('ascii', 'ignore') # icky
else:
bookmark_title = subject[0]
# in my system, you can use google's address+tag#gmail.com feature to specifiy
# where something goes, a useful feature.
project = message['to'].split('#')[0].split('+')
### Do something here with the message ###
pop_conn.quit()
I created a shutdown.py script that shuts down my computer.
I have a working rule in Microsoft Outlook that executes my Python script when I receive an email that has %BLAHBLAHBLAH% in the subject.
Is it possible to pass the email's subject line into the Python script before executing it?
Basically, I want a keyword in the subject line to execute a certain script but also be able to "pass" parameters into the email's subject line to the Python script.
For example if I send %shutdown30% my python script would parse the string %shutdown30% and use the 30 as a parameter to shutdown the computer in 30 minutes.
Why creating a rule in outlook that runs a script if an email is received, when you can simply do it all from python.
Using Python to monitor outlook for all incoming emails and then execute some code if an email, with %BLAHBLAH% in the subject, is received is possible. Here is an example:
import win32com.client
import pythoncom
import re
class Handler_Class(object):
def OnNewMailEx(self, receivedItemsIDs):
# RecrivedItemIDs is a collection of mail IDs separated by a ",".
# You know, sometimes more than 1 mail is received at the same moment.
for ID in receivedItemsIDs.split(","):
mail = outlook.Session.GetItemFromID(ID)
subject = mail.Subject
try:
# Taking all the "BLAHBLAH" which is enclosed by two "%".
command = re.search(r"%(.*?)%", subject).group(1)
print command # Or whatever code you wish to execute.
except:
pass
outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)
#and then an infinit loop that waits from events.
pythoncom.PumpMessages()