使用请求在不启动服务器的情况下测试Flask应用

问题描述 投票:1回答:1

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

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

是否有一种方法可以使这项工作工作而不必运行实际的服务?

python flask python-requests wsgi werkzeug
1个回答
0
投票

requests-wsgi-adapter提供了一个适配器,用于安装可在URL处调用的WSGI。您使用session.mount()来安装适配器,因此对于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))

使用请求的缺点是,您必须在要向其发出请求的每个URL之前添加r = s.get("http://test/") assert r.html.find("p")[0].text == "Hello, World!" 。 Flask测试客户端不需要此。


您也可以告诉Flask测试客户端返回一个为您执行BeautifulSoup解析的Response,而不是使用request和request-html。快速浏览了requests-html之后,我仍然更喜欢直接的Flask测试客户端和BeautifulSoup API。

"http://test/"
$ 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()
© www.soinside.com 2019 - 2024. All rights reserved.