我需要一个实时测试服务器,它通过HTTP GET接受我对基本信息的请求,并允许我POST(即使它真的什么都不做)。这完全是为了测试目的。

这里有一个很好的例子。它很容易接受GET请求,但我需要一个接受POST请求以及。

有人知道我也可以发送虚拟测试消息的服务器吗?


当前回答

你可以在本地运行Ken Reitz的httpbin服务器(在docker下或裸机上):

https://github.com/postmanlabs/httpbin

运行dockerized

docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin

直接在您的机器上运行

## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml

## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent

现在,您在http://0.0.0.0:8000上运行了个人httpbin实例(对您的所有局域网可见)

Minimal Flask REST服务器

我想要一个返回预定义响应的服务器,所以我发现在这种情况下,使用一个最小的Flask应用程序更简单:

#!/usr/bin/env python3

# Install dependencies:
#   pip3 install flask

import json

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def root():
    # spit back whatever was posted + the full env 
    return jsonify(
        {
            'request.json': request.json,
            'request.values': request.values,
            'env': json.loads(json.dumps(request.__dict__, sort_keys=True, default=str))
        }
    )

@app.route('/post', methods=['GET', 'POST'])
def post():
    if not request.json:
        return 'No JSON payload! Expecting POST!'
    # return the literal POST-ed payload
    return jsonify(
        {
            'payload': request.json,
        }
    )

@app.route('/users/<gid>', methods=['GET', 'POST'])
def users(gid):
    # return a JSON list of users in a group
    return jsonify([{'user_id': i,'group_id': gid } for i in range(42)])

@app.route('/healthcheck', methods=['GET'])
def healthcheck():
    # return some JSON
    return jsonify({'key': 'healthcheck', 'status': 200})

if __name__ == "__main__":
    with app.test_request_context():
        app.debug = True
    app.run(debug=True, host='0.0.0.0', port=8000)

其他回答

我不确定是否有人愿意花这么大的力气来测试GET和POST调用。我使用Python Flask模块并编写了一个函数,该函数的功能类似于@Robert共享的功能。

from flask import Flask, request
app = Flask(__name__)

@app.route('/method', methods=['GET', 'POST'])
@app.route('/method/<wish>', methods=['GET', 'POST'])
def method_used(wish=None):
    if request.method == 'GET':
        if wish:
            if wish in dir(request):
                ans = None
                s = "ans = str(request.%s)" % wish
                exec s
                return ans
            else:
                return 'This wish is not available. The following are the available wishes: %s' % [method for method in dir(request) if '_' not in method]
        else:
            return 'This is just a GET method'
    else:
        return "You are using POST"

当我运行这个时,如下所示:

C:\Python27\python.exe E:/Arindam/Projects/Flask_Practice/first.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 581-155-269
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

现在让我们打几通电话。我正在使用浏览器。

http://127.0.0.1:5000/method This is just a GET method http://127.0.0.1:5000/method/NotCorrect This wish is not available. The following are the available wishes: ['application', 'args', 'authorization', 'blueprint', 'charset', 'close', 'cookies', 'data', 'date', 'endpoint', 'environ', 'files', 'form', 'headers', 'host', 'json', 'method', 'mimetype', 'module', 'path', 'pragma', 'range', 'referrer', 'scheme', 'shallow', 'stream', 'url', 'values'] http://127.0.0.1:5000/method/environ {'wsgi.multiprocess': False, 'HTTP_COOKIE': 'csrftoken=YFKYYZl3DtqEJJBwUlap28bLG1T4Cyuq', 'SERVER_SOFTWARE': 'Werkzeug/0.12.2', 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/method/environ', 'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': '', 'werkzeug.server.shutdown': , 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36', 'HTTP_CONNECTION': 'keep-alive', 'SERVER_NAME': '127.0.0.1', 'REMOTE_PORT': 49569, 'wsgi.url_scheme': 'http', 'SERVER_PORT': '5000', 'werkzeug.request': , 'wsgi.input': , 'HTTP_HOST': '127.0.0.1:5000', 'wsgi.multithread': False, 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_ACCEPT': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.errors': ", mode 'w' at 0x0000000002042150>", 'REMOTE_ADDR': '127.0.0.1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, sdch, br'}

创建选择一个免费的网络主机,并把以下代码

<h1>Request Headers</h1>
<?php
$headers = apache_request_headers();
     
foreach ($headers as $header => $value) {
    echo "<b>$header:</b> $value <br />\n";
}
?>

你可以在本地运行Ken Reitz的httpbin服务器(在docker下或裸机上):

https://github.com/postmanlabs/httpbin

运行dockerized

docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin

直接在您的机器上运行

## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml

## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent

现在,您在http://0.0.0.0:8000上运行了个人httpbin实例(对您的所有局域网可见)

Minimal Flask REST服务器

我想要一个返回预定义响应的服务器,所以我发现在这种情况下,使用一个最小的Flask应用程序更简单:

#!/usr/bin/env python3

# Install dependencies:
#   pip3 install flask

import json

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def root():
    # spit back whatever was posted + the full env 
    return jsonify(
        {
            'request.json': request.json,
            'request.values': request.values,
            'env': json.loads(json.dumps(request.__dict__, sort_keys=True, default=str))
        }
    )

@app.route('/post', methods=['GET', 'POST'])
def post():
    if not request.json:
        return 'No JSON payload! Expecting POST!'
    # return the literal POST-ed payload
    return jsonify(
        {
            'payload': request.json,
        }
    )

@app.route('/users/<gid>', methods=['GET', 'POST'])
def users(gid):
    # return a JSON list of users in a group
    return jsonify([{'user_id': i,'group_id': gid } for i in range(42)])

@app.route('/healthcheck', methods=['GET'])
def healthcheck():
    # return some JSON
    return jsonify({'key': 'healthcheck', 'status': 200})

if __name__ == "__main__":
    with app.test_request_context():
        app.debug = True
    app.run(debug=True, host='0.0.0.0', port=8000)

Nc一行本地测试服务器

在Linux下用一行设置本地测试服务器:

nc -kdl localhost 8000

另一个shell上的请求生成器示例:

wget http://localhost:8000

然后在第一个shell中,你看到请求显示出来:

GET / HTTP/1.1
User-Agent: Wget/1.19.4 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: localhost:8000
Connection: Keep-Alive

netcat-openbsd包中的nc是广泛可用的,并且已预先安装在Ubuntu上。

在Ubuntu 18.04上测试。

另一个提供一些定制且易于使用(无需安装、注册)的网站是https://beeceptor.com。

您创建一个端点,向它发出初始请求,并可以调整响应。