簡體   English   中英

鏈接HTML Tornado服務器和Python文件的方法

[英]Methods on linking a HTML Tornado server and Python file

這是我的示例HTML文件

    <html>
    <head>
    <title>
    </title>
    </head>
    <body>
    <form action="">
    Value a:<br>
    <input type="text" name="Va">
    <br>
    Value b:<br>
    <input type="text" name="Vb">
    <br><br>
    <input type="submit">
    </form>
    <textarea rows="4" cols="10">

    </textarea>
    <p>
    </p>
    </body>
    </html>

和給定的模板Tornado服務器代碼:(我還需要幫助解釋以下代碼的每個部分)

    import tornado.ioloop
    import tornado.web
    import tornado.httpserver
    import tornado.gen
    import tornado.options
    tornado.options.parse_command_line()  
    class APIHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        def get(self):
            self.render('template.html')
        @tornado.gen.engine
        def post(self):
            try:
                num = int(self.get_argument('num'))
            except:
                num = 5
            self.render('template.html')
    app = tornado.web.Application([(r"/next_rec",APIHandler),])        
    if __name__ == "__main__":
        server = tornado.httpserver.HTTPServer(app)
        server.bind(48763)
        server.start(5)
        tornado.ioloop.IOLoop.current().start()

最后我的python代碼:

    if __name__ == '__main__':
        a = int(raw_input())
        b = int(raw_input())
    print a+b

我正在使用一個簡單的'a + b'函數來測試這個功能。 但我的問題是我無法找到將它們連接在一起的方法。 所以我的最終目標是點擊HTML上的“提交”按鈕,將兩個值傳遞給Tornado服務器,在我的python腳本中將其用作輸入,最后在HTML的文本區域或另一頁面上顯示輸出。 我知道網上有大量的信息,但我對Tornado來說是全新的(接近0知識),其中大多數我都無法理解。 非常感謝您對搜索方法或關鍵字的幫助,非常感謝。 (請盡可能保持答案基礎,這將有很大幫助,謝謝!)

首先,您應該查看官方文檔 這很簡單,它針對的是新人。

同樣在這個簡短的指南中 ,與您的類似代碼的部分正在簡單地解釋。

現在為您的代碼:

在您的模板上,您需要指定表單應通過添加<form method="post" id="sum_form">發送提交請求

此外,您需要確保在事件中提交表單中添加的數據: $("#sum_form").submit();

在post方法中,您需要從客戶端表單中讀取傳遞的數字,添加它們,然后將它們作為參數發送回模板。

例如:

def post(self):
  numA = int(self.get_argument('Va'))
  numB = int(self.get_argument('VB'))
  sumAB = numA + numB
  self.render('template.html',sumAB=sumAB)

在template.html中,您需要添加一個字段,您將把傳遞的總和顯示為jinja變量: {{sumAB}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM