веб-приложение с qpython и SL4A в Android

Я новичок в python на Android, и я пытаюсь создать небольшой пример веб-приложения, найденного здесь ( http://pythoncentral.io/python-for-android-using-webviews-sl4a/), где скрипт Python открывает веб-страницу и взаимодействует с ней (вы вводите текст в страница, а скрипт Python обрабатывает ее и отправляет обратно на веб-страницу для отображения). В моей попытке сделать это скрипт python может открыть страницу, но между веб-страницей и скриптом нет диалога. Кажется, что строка «var android = new Android()» на веб-странице не работает, как в примере.

Вот код веб-страницы:

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            var droid = new Android();

            function postInput(input) {
                if (event.keyCode == 13)
                    droid.eventPost('line', input)

                droid.registerCallback('stdout', function(e) {
                    document.getElementById('output').innerHTML = e.data;
                });
            }
        </script>   
    </head> 
    <body>
        <div id="banner">
            <h1>SL4A Webviews</h1>
            <h2>Example: Python Evaluator</h2>
        </div>

        <input id="userin" type="text" spellcheck="false"
               autofocus="autofocus" onkeyup="postInput(this.value)"
        />

        <div id="output"></div>

        <button id="killer" type="button"
                onclick="droid.eventPost('kill', '')"
        >QUIT</button>
    </body>
</html>

и код Python, запускающий веб-страницу выше:

import sys, androidhelper
droid = androidhelper.Android()

def line_handler(line):
    ''' Evaluate user input and print the result into a webview.
    This function takes a line of user input and calls eval on
    it, posting the result to the webview as a stdout event.
    '''
    output = str(eval(line))
    droid.eventPost('stdout', output)

droid.webViewShow('file:///storage/emulated/0/com.hipipal.qpyplus/scripts/webview1.html')

while True:
    event = droid.eventWait().result

    if event['name'] == 'kill':
        sys.exit()
    elif event['name'] == 'line':
        line_handler(event['data'])

Я действительно не понимаю, как должен работать экземпляр Android() на веб-странице. Спасибо за любую помощь ! (Я использую qpython с библиотекой SL4A на леденце Android)


person val    schedule 09.06.2016    source источник


Ответы (1)


Наконец, вчера я обнаружил, что qpython поставляется с хорошим фреймворком под названием Bottle. И это очень легко использовать для новичка, как я.

from bottle import route, run, request, template

@route('/hello')
def hello():
    line = ""
    output = ""
    return template('/storage/emulated/0/com.hipipal.qpyplus/webviewbottle2.tpl', line=line, output=output)

@route('/submit', method='POST')
def submit():
    line = request.forms.get('line')
    output = str(eval(line))
    return template('/storage/emulated/0/com.hipipal.qpyplus/webviewbottle2.tpl', line=line, output=output)

run(host='localhost', port=8080, debug=True)    

# open a web browser with http://127.0.0.1:8080/hello to start
# enter 40 + 2 in the input and "submit" to get the answer in the output window.

и файл шаблона:

<h1>bottle Webview</h1>
<h2>Example: Python Evaluator</h2>
<form action="/submit" method = "post">
    <input name="line" type = "text" value = {{line}}><br>
    <input name="output" type = "text" value = {{output}}>
    <button name="submit" type = "submit">submit</button>
</form>
person val    schedule 10.06.2016