【问题标题】:Python Bottle window.location.href UnresponsivePython Bottle window.location.href 无响应
【发布时间】:2021-03-05 01:06:18
【问题描述】:

我正在尝试编写代码,通过小型 RaspberryPi 网络服务器上的按钮旋转伺服电机。

我正在为 HTML 使用 python 和模块 Bottle。我已经为此工作了一段时间,我能得到的最好的结果是按钮重定向到“/false”。

我认为错误可能与“window.location.href/”有关,但我不确定。

问题是我不知道错误在哪里,老实说,任何帮助将不胜感激,我在过去几个小时内几乎没有取得任何进展。

def locking_status(status):
    if status == 'open':
        return 'Unlocked'
    else:
        return 'Locked'

def html_for_button(status,title):
    result = "<input type='button' onClick='changed("+status+")' value='"+title+"'/>"
    print(result)
    return result

@route('/')
@route('/<status>')
def index(status = 'open'):
    if status == 'open':
        servo.angle = 90
    else:
        servo.angle = -90

    response = "<script>"
    response += "function changed(status)"
    response += "{"
    response += "  window.location.href='/' + status"
    response += "}"
    response += "</script>"

    response += '<h1>GPIO Control</h1>'
    response += html_for_button('open', 'UNLOCK')
    response += html_for_button('closed', 'LOCK')

    response += '<h2>Door=' + locking_status(status) + '</h2>'

    return response

run(host='MY_IP', port = 80, debug = True)

【问题讨论】:

    标签: python html python-3.x server bottle


    【解决方案1】:

    你可能把事情复杂化了。此外,我真的会考虑使用瓶子的内置模板引擎。很强大。

    from bottle import get, run, template
    
    @get('/')
    @get('/<status>')
    def index(status = 'open'):
        if status == 'open':
            servo.angle = 90
            stat = 'Unlocked'
        else:
            servo.angle = -90
            stat = 'Locked'
    
        response = '''<script>
        function changed(status)
        {
          window.location.href='http://localhost/' + status
        }
        </script>
    
        <h1>GPIO Control</h1>
        <input type='button' onClick='changed("open")' value='Open'/>
        <input type='button' onClick='changed("closed")' value='Closed'/>
        <h2>Door= {{stat}}</h2>
        '''
        return template(response, stat=stat)
    
    run(host='0.0.0.0', port = 80, debug = True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2018-04-24
      • 2012-03-10
      • 2014-04-23
      • 1970-01-01
      相关资源
      最近更新 更多