使用flask运行多个python函数

时间:2013-01-26 06:38:31

标签: python serial-port arduino flask

第二次更新

几乎就是!!但得到“ValueError:尝试使用未打开的端口”

File "c:\Python27\lib\site-packages\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)

File "c:\Python27\lib\site-packages\flask\app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))

File "c:\Python27\lib\site-packages\flask\app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()

File "c:\Python27\lib\site-packages\flask\app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)

File "c:\Python27\lib\site-packages\flask\app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()

File "c:\Python27\lib\site-packages\flask\app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)

File "G:\OverAir\arduino\server.py", line 19, in light_off
board.output([pin])

File "G:\OverAir\arduino\arduino.py", line 16, in output
self.__sendData(len(pinArray))

File "G:\OverAir\arduino\arduino.py", line 56, in __sendData
while(self.__getData()[0] != "w"):

File "G:\OverAir\arduino\arduino.py", line 61, in __getData
return self.serial.readline().rstrip('\n')

File "c:\Python27\lib\site-packages\serial\serialwin32.py", line 221, in read
if not self.hComPort: raise portNotOpenError

ValueError: Attempting to use a port that is not open
     

更新

     

以下@Blender回答的代码可能是正确的。现在的问题   我正在使用的是“SerialException:无法打开端口   COM5:[错误5]访问被拒绝。“

     

但是,如果我单独运行我的原始,on.py或off.py脚本,它   工作正常...我不知道新代码是如何工作的......除非   它尝试两次打开COM5 ??

     

END UPDATE

我尝试使用Flask运行多个python函数或单独的.py脚本;为了生成单独的URL。只是试图打开/关闭Arduino在本地运行它。

例如,我有on.py和off.py并且想要构建sever.py。 所以,当我打开127.0.0.1:5000/它运行on.py时,类似127.0.0.1:5000/off运行off.py,

几个小时后,我决定将两个.py函数添加到server.py中,但当然它不起作用......我想我只是不明白参数用法。

提前真的感谢你!

## Open a serial connection with Arduino.

from time import sleep
from arduino import Arduino

from flask import Flask


b = Arduino("COM5",9600)
pin = 13
num = 5

ON = Flask("Light_ON")
OFF = Flask("Light_OFF")


def LightON():
    #declare output pins as a list/tuple
    b.output([pin])
    b.setHigh(pin)
    b.close()
    return 'Light is ON'

def LightOFF():
    #declare output pins as a list/tuple
    b.output([pin])
    b.setLow(pin)
    return 'Light is OFF'

@ON.route('/ON')
@OFF.route('/OFF')

ON.run()
OFF.run()  //I know this doesn't run, just not sure how to include it.

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

from arduino import Arduino
from flask import Flask

app = Flask('light_control')
board = Arduino('COM5', 9600)
pin = 13

@app.route('/on')
def light_on():
    board.output([pin])
    board.setHigh(pin)
    board.close()

    return 'Light is ON'

@app.route('/off')
def light_off():
    board.output([pin])
    board.setLow(pin)
    # board.close() ???

    return 'Light is OFF'

if __name__ == '__main__':
    app.debug = True
    app.run()