-
Notifications
You must be signed in to change notification settings - Fork 19
Tutorial 2
knightliao edited this page Mar 4, 2016
·
1 revision
有时候静态配置无法满足我们的需求, 因此我们要做出动态的决定, 甚至, 有时候还需要有 持久化能力
通过简单配置 URL配置 和 python文件, 就可以实现 强大的 动态mock能力
这里以 https://github.com/knightliao/pfrock-demos/tree/master/demos/http-demo 为demo
{
"servers": [
{
"port": 8888,
"routes": [
{
"path": "/api",
"methods": [
"GET"
],
"handler": "pfrock_http_plugin",
"options": {
"handler": "mocks.handler.hello_world.HelloWorldHandler"
}
}
]
}
]
}
这里将 127.0.0.1:8888/api 路由到 mocks.handler.hello_world.HelloWorldHandler 这个处理方法上
这里method指定只服务于 GET 请求.
记得将 handler 指定为 pfrock_http_plugin
from pfrock.core.web import PfrockRequestDispatcher
class HelloWorldHandler(PfrockRequestDispatcher):
def get(self):
self.write("Hello, world")
➜ tmp curl -v '127.0.0.1:8888/api'
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8888 (#0)
> GET /api HTTP/1.1
> Host: 127.0.0.1:8888
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 04 Mar 2016 08:43:55 GMT
< Content-Length: 12
< Etag: "e02aa1b106d5c7c6a98def2b13005d5b84fd8dc8"
< Content-Type: text/html; charset=UTF-8
< Server: TornadoServer/4.3
<
* Connection #0 to host 127.0.0.1 left intact
Hello, world%
{
"servers": [
{
"port": 8888,
"routes": [
{
"path": "/api/persistence",
"methods": [
"GET"
],
"handler": "pfrock_http_plugin",
"options": {
"handler": "mocks.handler.persistence.PersistenceHandler"
}
}
]
}
]
}
from pfrock.core.web import PfrockRequestDispatcher
grower_index = 0
class PersistenceHandler(PfrockRequestDispatcher):
def get(self):
global grower_index
grower_index += 1
self.write("Hello, world " + str(grower_index))
第一次
➜ tmp curl -v '127.0.0.1:8888/api/persistence'
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8888 (#0)
> GET /api/persistence HTTP/1.1
> Host: 127.0.0.1:8888
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 04 Mar 2016 08:46:02 GMT
< Content-Length: 14
< Etag: "ddc05a08c112b2dcbb382613317ada8dd6063bf1"
< Content-Type: text/html; charset=UTF-8
< Server: TornadoServer/4.3
<
* Connection #0 to host 127.0.0.1 left intact
Hello, world 1%
第二次:
➜ tmp curl -v '127.0.0.1:8888/api/persistence'
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8888 (#0)
> GET /api/persistence HTTP/1.1
> Host: 127.0.0.1:8888
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 04 Mar 2016 08:47:31 GMT
< Content-Length: 14
< Etag: "90f43fb22c73207e600d7122bd85ff095ea8f07d"
< Content-Type: text/html; charset=UTF-8
< Server: TornadoServer/4.3
<
* Connection #0 to host 127.0.0.1 left intact
Hello, world 2%
可以看到 grower_index 的值 +1 了