我是网络服务器的新手,所以我需要一些指导如何实现以下目标:
非常感谢任何帮助。
我将在learnpythonthehardway.com的50和51课程中学习这些教程。这是我设法开始的。
仓/ app.py
import web
import time
urls = ('/cycle', 'Index')
app = web.application(urls, globals())
render = web.template.render('templates/', base="layout")
class Index(object):
def GET(self):
return render.hello_form2()
def POST(self):
form = web.input(cycles=0)
cycleparams = "%s" % (form.cycles)
cycleGPIO(form.cycles)
return render.index2(cycleparams = cycleparams)
if __name__ == "__main__":
app.run()
def cycleGPIO(cycles):
for i in range(int(cycles)):
print "cycle " + str(i+1)
time.sleep(1)
模板/的layout.html
$def with (content)
<html>
<head>
<title>Test Page</title>
</head>
<body>
$:content
</body>
</html>
模板/ index2.html
$def with (cycleparams)
$if cycleparams:
Test completed with the following parameters:
<br>
$cycleparams
$else:
No parameters specified
<br><br>
<a href="/cycle">Return to form</a>
模板/ hello_form2.html
<fieldset>
<legend>Output Cycling</legend>
<form action="/cycle" method="POST">
<br>Number of cycles:
<br><input type="number" name="cycles">
<input type="submit">
</form>
</fieldset>
答案 0 :(得分:1)
解决此问题的最佳方法是分离Web和GPIO循环过程。在此之后,您可以使用python中可用的许多进程间通信机制之一。阅读此内容的好页面是Interprocess Communication and Networking。
现在,我只选择一种最简单的方法来在两个python进程之间进行通信,这是一个纯文本文件。我们有两个文件。您的Web服务进程将用于将表单输入发送到GPIO进程,GPIO进程将用于向Web服务发送反馈的另一个进程。
请记住,这只是一个例子,有许多更好的方法来解决进程间通信问题。这只是为了给您一个粗略的想法,而不是您应该在任何生产系统中使用的东西。
这就是代码的样子。
web.py服务更改
...
urls = ('/cycle-status', 'StatusIndex')
...
class StatusIndex(object):
def GET(self):
# Read feedback params from a file
cycleparams = read_gpio_feedback_file()
return render.index2(cycleparams = cycleparams)
class Index(object):
...
def POST(self):
form = web.input(cycles = 0)
cycleparams = "%s" % (form.cycles)
# Write cycle params to a file
write_cycle_params(form.cycles)
# This call probably won't produce any results
# because your GPIO process couldn't react so fast.
return render.index2(cycleparams = {})
def write_cycle_params(cycles):
f = open('/path/to/cycles/file.txt', 'w')
for i in range(int(cycles)):
f.write("cycle " + str(i + 1))
f.close()
def read_gpio_feedback():
cycleparams = {}
f = open('/path/to/feedback/file.txt', 'r')
for line in f:
cycleparams['param1'] = line
f.close()
return cycleparams
GPIO流程
#!/usr/bin/env python
import sys
if __name__ == '__main__':
cycleparams = ""
f = open('/path/to/cycles/file.txt', 'r')
for line in f:
cycleparams = cycleparams + line
f.close()
# Do something with cycleparams related to GPIO
# Get your cycle params from GPIO pins
...
cycleparams = ""
f = open('/path/to/feedback/file.txt','w')
f.write(cycleparams + '\n')
f.close()
sys.exit(0)
您的GPIO流程必须定期运行以从Web服务生成的文件中读取信息,并且还要写入Web服务将解析并显示输出的反馈。您可以通过将GPIO进程添加到crontab(或任何其他进程调度机制将正常工作)来实现此目的。