【问题标题】:Use requests-html to test Flask app without starting server在不启动服务器的情况下使用 requests-html 测试 Flask 应用程序
【发布时间】:2020-07-18 00:20:02
【问题描述】:

我一直在使用 Flask test_client 对象来测试我的 Web 应用程序。我使用BeautifulSoup 来解析其中一些调用的HTML 输出。

现在我想尝试requests-html,但我不知道如何使它与 Flask 测试客户端一起工作。这些示例都使用request package 来获取响应,但是 Werkzeug 测试客户端并没有进行实际的 HTTP 调用。据我所知,它会设置环境并调用处理程序方法。

有没有一种方法可以在不运行实际服务的情况下完成这项工作?

【问题讨论】:

    标签: python flask python-requests wsgi werkzeug


    【解决方案1】:

    requests-wsgi-adapter 提供了一个适配器来在 URL 上挂载一个 WSGI 可调用对象。您使用session.mount() 来安装适配器,因此对于requests-html,您将改用HTMLSession 并安装到该适配器。

    $ pip install flask requests-wsgi-adapter requests-html
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route("/")
    def index():
        return "<p>Hello, World!</p>"
    
    from requests_html import HTMLSession
    from wsgiadapter import WSGIAdapter
    
    s = HTMLSession()
    s.mount("http://test", WSGIAdapter(app))
    
    r = s.get("http://test/")
    assert r.html.find("p")[0].text == "Hello, World!"
    

    使用请求的缺点是您必须在要向其发出请求的每个 URL 之前添加"http://test/"。 Flask 测试客户端不需要这个。


    除了使用 requests 和 requests-html,您还可以告诉 Flask 测试客户端返回一个为您进行 BeautifulSoup 解析的响应。快速浏览 requests-html 后,我还是更喜欢直接的 Flask 测试客户端和 BeautifulSoup API。

    $ pip install flask beautifulsoup4 lxml
    
    from flask.wrappers import Response
    from werkzeug.utils import cached_property
    
    class HTMLResponse(Response):
        @cached_property
        def html(self):
            return BeautifulSoup(self.get_data(), "lxml")
    
    app.response_class = HTMLResponse
    c = app.test_client()
    
    r = c.get("/")
    assert r.html.p.text == "Hello, World!"
    

    您还应该考虑使用HTTPX 而不是请求。它是一个现代的、维护良好的 HTTP 客户端库,与请求有许多 API 相似之处。它还具有强大的功能,例如异步、HTTP/2 和 call WSGI applications directly 的内置功能。

    $ pip install flask httpx
    
    c = httpx.Client(app=app, base_url="http://test")
    
    with c:
        r = c.get("/")
        html = BeautifulSoup(r.text)
        assert html.p.text == "Hello, World!"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2021-10-06
      • 2013-11-14
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多