I'm newbie for raspberry pi and python coding. I'm working on a school project. I've already looked for some tutorials and examples but maybe I'm missing something. I want to build a web server based gpio controller. I'm using flask for this. For going into this, I've started with this example. Just turning on and off the led by refreshing the page.
So the problem is, I can't see the response value on the web server side. It's turning on and off the led. But I want to see the situation online. But I just couldn't. I'm getting and internal server error. I'm giving the python and html codes. Can you help me with solving the problem.
from flask import Flask
from flask import render_template
import RPi.GPIO as GPIO
app=Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.output(4,1)
status=GPIO.HIGH
#app.route('/')
def readPin():
global status
global response
try:
if status==GPIO.LOW:
status=GPIO.HIGH
print('ON')
response="Pin is high"
else:
status=GPIO.LOW
print('OFF')
response="Pin is low"
except:
response="Error reading pin"
GPIO.output(4, status)
templateData= {
'title' : 'Status of Pin' + status,
'response' : response
}
return render_template('pin.html', **templateData)
if __name__=="__main__":
app.run('192.168.2.5')
And basically just this line is on my html page.
<h1>{{response}}</h1>
I think "response" doesn't get a value. What's wrong on this?
Firstly it helps to run it in debug mode:
app.run(debug=True)
This will help you track down any errors which are being suppressed.
Next have a look at the line where you are building the title string:
'title' : 'Status of Pin' + status
If you enable the debug mode, then you should see something saying that an int/bool can't be converted to str implicitly. (Python doesn't know how to add a string and an int/bool).
In order to fix this, you should explicitly cast status to a string:
'title' : 'Status of Pin' + str(status)
Or better yet:
'title' : 'Status of Pin: {}'.format(status)
Your server was probably throwing an exception when trying to create your dictionary, therefore the templateData value was being sent as an empty value.
Notice in this example, the TypeError which is thrown when trying to concatenate 2 variables of different type.
Hence, wrapping your variable in the str(status) will cast the status variable to it's string repersentation before attempting to combine the variables.
[root#cloud-ms-1 alan]# cat add.py
a = 'one'
b = 2
print a + b
[root#cloud-ms-1 alan]# python add.py
Traceback (most recent call last):
File "add.py", line 6, in <module>
print a + b
TypeError: cannot concatenate 'str' and 'int' objects
[root#cloud-ms-1 alan]# cat add.py
a = 'one'
b = str(2)
print a + b
[root#cloud-ms-1 alan]# python add.py
one2
Related
I'm trying to run a sample function that allows a user to execute arbitrary code
Note: I"m assuming this is ok because Azure Functions will by default provide a sandbox. (And the end user will need to write code with dataframes, objects etc. I've looked into pypy.org but don't think I need it as I am not worried about attacks that use it as a spambot or something):
import os
import json
import ast
print('==============in python function========================')
postreqdata = json.loads(open(os.environ['req']).read())
response = open(os.environ['res'], 'w')
response.write("hello world from "+postreqdata['name'])
response.close()
logic = (postreqdata['logic'])
eval(logic)
but I keep getting the following output/error:
2018-01-17T09:09:08.949 ==============in python function========================
2018-01-17T09:09:09.207 Exception while executing function: Functions.ccfinopsRunModel. Microsoft.Azure.WebJobs.Script: Traceback (most recent call last):
File "D:\home\site\wwwroot\ccfinopsRunModel\run.py", line 12, in <module>
eval(logic)
File "<string>", line 1
print('code sent from client')
^
SyntaxError: invalid syntax
.
My POST request body contains the following:
{
"name": "Python Function App",
"logic": "print('code sent from client')"
}
So the "logic" variable is being read in, and eval() is trying to interpret the string as python code, but it is causing a Syntax Error where there appears to be none.
What am I doing wrong? If there was a restriction on 'eval' I'm assuming it would say that instead of "Syntax Error"
Thanks for any help you can provide!
Use exec to run your code. eval is used evaluating expressions.
logic = (postreqdata['logic'])
exec(logic)
Also can try sending your code as multi-line string as below,
>>> s = '''
for i in range(3):
print("i")
'''
>>> exec(s)
0
1
2
I am trying to build a Phasor Measurement Unit using Beaglebone Black rev 3. The following is the code. While running it gives an error as:
prussdrv_open open failed
Traceback (most recent call last):
File "/var/lib/cloud9/pmu.py", line 36, in <module>
pru.open(0) # open connection to PRU 0
SystemError: error return without exception set
The code goes here:
import pypruss as pru
import mmap
import numpy as np
import struct
import time
## MEMORY LOCATIONS ##
PRU_ICSS=0x4A300000
PRU_ICSS_LEN=512*1024
RAM_START=0x00000000
RAM1_START=0x00002000
RAM2_START=0x00012000
TOTAL_BUFFER_LEN=0x00000FA0
BUFFER_LEN=TOTAL_BUFFER_LEN/2
BUFFER1_START=RAM2_START+4
BUFFER2_START=BUFFER1_START+BUFFER_LEN
## FUNCTION DEFINITIONS ##
def processRawADC(value):
value=0x00000FFF&value
value=int(value)
value=(value*1.8)/(2^12)
return value
def channelID(value):
value=0x000F0000&value
value=value>>16
return value
## PRU SETUP ##
pru.modprobe( ) # enable uio_pruss module
pru.init( ) #initialize PRU
pru.open(0) # open connection to PRU 0
pru.pruintc_init( ) # configure interrupt handlers
pru.exec_program(0,"./oneshot.bin") # load assembly file
counter = 0
f=open("/dev/mem","r+b")
output=open("./results.txt","w")
while counter<10 :
start=time.time()
pru.wait_for_event(0)
ddr_mem=mmap.mmap(f.fileno( ),PRU_ICSS_LEN,offset=PRU_ICSS)
shared=struct.unpack('L ',ddr_mem[RAM2_START:RAM2_START+4])
print(shared[0])
if shared[0]==1 :
print ("buffer 1")
for i in range(0,500) :
fifo = struct.unpack ( 'L ' ,ddr_mem[BUFFER2_START+( i*4)
:BUFFER2_START+4+(i*4)])[0]
value=processRawADC(fifo)
channelNum=channelID(fifo)
output.write(str(channelNum)+","+str(value)+"nn")
counter += 1
pru.clear_event(0)
elif shared[0] == 2:
shared=struct.unpack('L ',ddr_mem[RAM2_START:RAM2_START+4])
print("buffer 2")
for i in range(0,500):
fifo=struct.unpack('L',ddr_mem[BUFFER2_START+(i*4) :BUFFER2_START+4+
(i*4)])[0]
value = processRawADC(fifo)
channelNum = channelID(fifo)
output.write(str(channelNum)+","+str(value)+"nn")
counter +=1
pru.clear_event(0)
end=time.time( )
#print end-start
f.close( )
output.close( )
pru.clear_event(0)
pru.pru_disable(0)
pru.exit ( )
I am unable to find, where is the mistake lies. Please Help.
Looks like there is a bug in PyPRUSS code.
Its pypruss_open function does not properly set exception information but returns an error indication (NULL). Python doesn't like when a function does so.
Looking at the pypruss_open source, it will fail in such way if prussdrv_open fails and returns -1 as an error indication. It in turn might fail either itself (if that device is already opened) or if __prussdrv_memmap_init fails.
Unfortunately, looks like there is no way to get information about the exact reason of the error.
What can you do to debug this issue? If you won't be able to find anything obvious (like missing /dev/uid0 after calling pru.modprobe()) then you can run your script with strace to see which system calls precede an error. Then you look at the source code under links I gave you above and see when exactly does the failure happen.
I'm beginning to use CGI with Python.
After running the following piece of code:
#!c:\python34\python.exe
import cgi
print("Content-type: text/html\n\n") #important
def getData():
formData = cgi.FieldStorage()
InputUN = formData.getvalue('username')
InputPC = formData.getvalue('passcode')
TF = open("TempFile.txt", "w")
TF.write(InputUN)
TF.write(InputPC)
TF.close()
if __name__ =="__main__":
LoginInput = getData()
print("cgi worked")
The following error occurs:
Traceback (most recent call last):
File "C:\xampp\htdocs\actual\loginvalues.cgi", line 21, in <module>
LoginInput = getData()
File "C:\xampp\htdocs\actual\loginvalues.cgi", line 16, in getData
TF.write(InputUN)
TypeError: must be str, not None
>>>
I'm trying to write the values, inputted in html, to a text file.
Any help would be appreciated :)
Your calls to getValue() are returning None, meaning the form either didn't contain them, had them set to an empty string, or had them set by name only. Python's CGI module ignores inputs that aren't set to a non-null string.
Works for Python CGI:
mysite.com/loginvalues.cgi?username=myname&pass=mypass
Doesn't work for Python CGI:
mysite.com/loginvalues.cgi?username=&pass= (null value(s))
mysite.com/loginvalues.cgi?username&pass (Python requires the = part.)
To account for this, introduce a default value for when a form element is missing, or handle the None case manually:
TF.write('anonymous' if InputUN is None else InputUN)
TF.write('password' if InputPC is None else InputUN)
As a note, passwords and other private login credentials should never be used in a URL. URLs are not encrypted. Even in HTTPS, the URL is sent in plain text that anyone on the network(s) between you and your users can read.
The only time a URL is ever encrypted is over a tunneled SSH port or an encrypted VPN, but you can't control that, so never bank on it.
I have the next code somewhere in Pyramid application
import xmlrpclib
....
#view_config(route_name='api-paypoint', renderer='string')
def api_paypoint(request):
call_data = ["mid", "password", "name"]
api_server = xmlrpclib.ServerProxy('https://www.secpay.com/secxmlrpc/make_call')
response = api_server.SECVPN.validateCardFull(call_data)
print response
return {}
What I'm trying is to call Secpay API (here's JAVA's example http://www.paypoint.net/support/gateway/soap-xmlrpc/xmlrpc-java/ )
I'm getting the next error:
Exception Value: <Fault 0: 'java.lang.NoSuchMethodException: com.secpay.secvpn.SECVPN.validateCardFull(java.util.Vector)'>
Any idea what is wrong here?
I found a problem. I was trying to pass to api_server.SECVPN.validateCardFull() which is wrong. This should be changed to
api_server.SECVPN.validateCardFull('mid', 'password', 'name')
You're calling with the wrong number of arguments, and the java serverside can't find a method matching that signature. If you call with 14 strings the exception changes (something about the serverside failing to encode a null).
proxy.SECVPN.validateCardFull("","","","","","","","","","","","","","")
I'm trying to create a simple module for phenny, a simple IRC bot framework in Python. The module is supposed to go to http://www.isup.me/websitetheuserrequested to check is a website was up or down. I assumed I could use regex for the module seeing as other built-in modules use it too, so I tried creating this simple script although I don't think I did it right.
import re, urllib
import web
isupuri = 'http://www.isup.me/%s'
check = re.compile(r'(?ims)<span class="body">.*?</span>')
def isup(phenny, input):
global isupuri
global cleanup
bytes = web.get(isupuri)
quote = check.findall(bytes)
result = re.sub(r'<[^>]*?>', '', str(quote[0]))
phenny.say(result)
isup.commands = ['isup']
isup.priority = 'low'
isup.example = '.isup google.com'
It imports the required web packages (I think), and defines the string and the text to look for within the page. I really don't know what I did in those four lines, I kinda just ripped the code off another phenny module.
Here is an example of a quotes module that grabs a random quote from some webpage, I kinda tried to use that as a base: http://pastebin.com/vs5ypHZy
Does anyone know what I am doing wrong? If something needs clarified I can tell you, I don't think I explained this enough.
Here is the error I get:
Traceback (most recent call last):
File "C:\phenny\bot.py", line 189, in call
try: func(phenny, input)
File "C:\phenny\modules\isup.py", line 18, in isup
result = re.sub(r'<[^>]*?>', '', str(quote[0]))
IndexError: list index out of range
try this (from http://docs.python.org/release/2.6.7/library/httplib.html#examples):
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
if res.status >= 200 and res.status < 300:
print "up"
else:
print "down"
You will also need to add code to follow redirects before checking the response status.
edit
Alternative that does not need to handle redirects but uses exceptions for logic:
import urllib2
request = urllib2.Request('http://google.com')
request.get_method = lambda : 'HEAD'
try:
response = urllib2.urlopen(request)
print "up"
print response.code
except urllib2.URLError, e:
# failure
print "down"
print e
You should do your own tests and choose the best one.
The error means your regexp wasn't found anywhere on the page (the list quote has no element 0).