Home  >  Article  >  Backend Development  >  A Simple Test HTTP server from Flask

A Simple Test HTTP server from Flask

WBOY
WBOYOriginal
2024-08-16 18:01:32403browse

A Simple Test HTTP server from Flask

Last night I found myself needing to update some app code to switch from a synchronous http call to an async one. This is not a particularly hard problem but it can be tricky to get correct.

What I needed therefore was a way to test these http calls, and the machine I was using didn't already have any http servers running to use as the target.

No problem: it has Python - and that's all you need.

Don't Install - Just create

This pattern has been forming for me. For simple tasks, it's often easier to just write a little utility script instead of installing some full blown software to do a job.

If you need a real server, by all means go for it (but even then I'd suggest Docker if possible). But if you just need a quick endpoint to test with or to solve a single use case then Python is probably your friend.

I'm saying Python specifically because it's rather ubiquitous with a rich standard library and ecosystem.

Server code

The idea with this simple server was to help me test the async client calls so I wanted it to wait 5 seconds and then respond. I just wanted it to respond to any standard call with a 200 after 5 seconds.

from flask import Flask, request
import time

app = Flask(__name__)

@app.route('/', defaults={'path': ''}, methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
def catch_all(path):
    print(f"Path: {path}")
    print(f"Headers: {dict(request.headers)}")
    print(f"Params: {request.args}")
    print(f"Data: {request.data}")

    # Wait for 5 seconds
    time.sleep(5)

    return "yessir"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

The above is the detailed content of A Simple Test HTTP server from Flask. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:SageMath InstallationNext article:SageMath Installation