动态可配置服务器
loose-server的Python项目详细描述
安装
$ python -m pip install loose-server
将安装其他程序包:Flask,flask-restful(服务器需要)和requests(http客户端需要)。
文档
包的文档可以在Wiki上找到。
快速启动
松散服务器有两种变体:
- 带有api的独立服务器,通过http管理规则。
- Flask应用程序,可以用作可配置的单元内模拟测试。
独立服务器
可以通过命令启动服务器
$ python -m looseserver.default.server.run * Serving Flask app "looseserver" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:50000/ (Press CTRL+C to quit)
api端点嵌套到基本配置url。默认情况下是/_configuration/。
fromlooseserver.default.client.ruleimportPathRulefromlooseserver.default.client.responseimportFixedResponsefromlooseserver.default.client.httpimportHTTPClientclient=HTTPClient(configuration_url="http://127.0.0.1:50000/_configuration/")path_rule=client.create_rule(rule=PathRule(path="example"))json_response=FixedResponse(status=200,headers={"Content-Type":"application/json"},body='{"key": "value"}',)client.set_response(rule_id=path_rule.rule_id,response=json_response)
所有配置的终结点都有一个公共前缀。默认情况下是/routes/。 可通过以下请求获得响应
$ curl http://127.0.0.1:50000/routes/example -i HTTP/1.0 200 OK Content-Type: application/json Content-Length: 16 Server: Werkzeug/0.15.2 Python/3.5.2 Date: Fri, 05 Apr 2019 14:08:50 GMT {"key": "value"}
可配置模拟
loose server可用作模拟服务器,方法如下
fromlooseserver.default.server.applicationimportconfigure_applicationfromlooseserver.default.client.flaskimportFlaskClientfromlooseserver.default.client.ruleimportPathRulefromlooseserver.default.client.responseimportFixedResponseapplication=configure_application(base_endpoint="/base/",configuration_endpoint="/config/")app_client=application.test_client()client=FlaskClient(configuration_url="/config/",application_client=app_client)path_rule=client.create_rule(rule=PathRule(path="example"))json_response=FixedResponse(status=200,headers={"Content-Type":"application/json"},body='{"key": "value"}',)client.set_response(rule_id=path_rule.rule_id,response=json_response)response=app_client.get("/base/example")assertresponse.headers["Content-Type"]=="application/json"assertresponse.json=={'key':'value'}