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/,界面如下,并在输入框中输入如下:


GET请求

  点击“提交”按钮后,页面如下:

POST请求

  以上我们已经完成了这个web app的测试,但是在网页中测试往往并不方便。以下我们将介绍两者测试web app的方法:

  • postman
  • curl

  首先是postman. postman 提供功能强大的 Web API 和 HTTP 请求的调试,它能够发送任何类型的HTTP 请求 (GET, POST, PUT, DELETE…),并且能附带任何数量的参数和 Headers.
  首先是GET请求的测试:


postman的GET请求

在Body中有三种视图模式:Pretty,Raw,Preview, Pretty为HTML代码, Raw为原始视图,Preview为网页视图。
  接着是POST请求:

postman的POST请求

  在Linux中,我们还可以用curl命令来测试以上web app.在Linux中,curl是一个利用URL规则在命令行下工作的文件传输工具,可以说是一款很强大的http命令行工具。它支持文件的上传和下载,是综合传输工具。
  首先是curl的GET请求:

curl的GET请求

  接着是curl的POST请求:

curl的POST请求

  在本次分享中,我们介绍了tornado的HTTP请求,包括GET、POST请求,并将介绍如何使用postman和curl来测试该app.
  本次分享到此结束,欢迎大家交流~~

猜你喜欢

转载自blog.csdn.net/jclian91/article/details/80369941
今日推荐