天天看點

tornado學習筆記(1)HTTP請求及API測試

  Tornado是現在的主流 Web 伺服器架構,它與大多數 Python 的架構有着明顯的差別:它是非阻塞式伺服器,而且速度相當快。得利于其非阻塞的方式和對 epoll 的運用,Tornado 每秒可以處理數以千計的連接配接,這意味着對于實時 Web 服務來說,Tornado 是一個理想的 Web 架構。

  在本文中,我們将介紹tornado的HTTP請求,包括GET、POST請求,并将介紹如何來測試該app.

  我們的項目結構如下:

  tornado.py的完整代碼如下:

# tornado的GET、POST請求示例
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options

#定義端口為8080
define("port", default=8080, help="run on the given port", type=int)

# GET請求
class IndexHandler(tornado.web.RequestHandler):
    # get函數
    def get(self):
        self.render('index.html')

# POST請求
# POST請求參數: name, age, city
class InfoPageHandler(tornado.web.RequestHandler):
    # post函數
    def post(self):
        name = self.get_argument('name')
        age = self.get_argument('age')
        city = self.get_argument('city')
        self.render('infor.html', name=name, age=age, city=city)

# 主函數
def main():
    tornado.options.parse_command_line()
    # 定義app
    app = tornado.web.Application(
            handlers=[(r'/', IndexHandler), (r'/infor', InfoPageHandler)], #網頁路徑控制
            template_path=os.path.join(os.path.dirname(__file__), "templates") # 模闆路徑
          )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

main()           

  templates檔案夾為存放HTML檔案的模闆目錄,其中index.html的代碼如下:

<!DOCTYPE html>
<html>
<head><title>Person Info</title></head>
<body>
<h2>Enter your information:</h2>
<form method="post" action="/infor">
<p>name<br><input type="text" name="name"></p>
<p>age<br><input type="text" name="age"></p>
<p>city<br><input type="text" name="city"></p>
<input type="submit">
</form>
</body>
</html>           

infor.html的代碼如下:

<!DOCTYPE html>
<html>
<head><title>Welcome</title></head>
<body>
<h2>Welcome</h2>
<p>Hello, {{name}}! You are {{age}} years old now , and you live in {{city}}.</p>
</body>
</html>           

  這樣我們就完成了tornado的一個簡單的HTTP請求的示例項目。在浏覽器中輸入localhost:8080/,界面如下,并在輸入框中輸入如下:

  點選“送出”按鈕後,頁面如下:

  以上我們已經完成了這個web app的測試,但是在網頁中測試往往并不友善。以下我們将介紹兩者測試web app的方法:

  • postman
  • curl

  首先是postman. postman 提供功能強大的 Web API 和 HTTP 請求的調試,它能夠發送任何類型的HTTP 請求 (GET, POST, PUT, DELETE…),并且能附帶任何數量的參數和 Headers.

  首先是GET請求的測試:

在Body中有三種視圖模式:Pretty,Raw,Preview, Pretty為HTML代碼, Raw為原始視圖,Preview為網頁視圖。

  接着是POST請求:

  在Linux中,我們還可以用curl指令來測試以上web app.在Linux中,curl是一個利用URL規則在指令行下工作的檔案傳輸工具,可以說是一款很強大的http指令行工具。它支援檔案的上傳和下載下傳,是綜合傳輸工具。

  首先是curl的GET請求:

  接着是curl的POST請求:

  在本次分享中,我們介紹了tornado的HTTP請求,包括GET、POST請求,并将介紹如何使用postman和curl來測試該app.

  本次分享到此結束,歡迎大家交流~~