app.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """
  2. 演示 HTTP 服务
  3. - GET /get 普通 GET 请求演示
  4. - POST /post 普通 POST 请求演示
  5. - GET /stream/<n> 流式响应演示(逐行返回 n 条 JSON)
  6. 运行方式:
  7. pip install flask
  8. python app.py
  9. 默认监听 0.0.0.0:8080,局域网内 Android 设备通过 http://<本机IP>:8080 访问
  10. """
  11. import json
  12. import time
  13. from flask import Flask, request, Response, jsonify
  14. app = Flask(__name__)
  15. PORT = 8080
  16. def cors(response):
  17. response.headers["Access-Control-Allow-Origin"] = "*"
  18. response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
  19. response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
  20. return response
  21. @app.after_request
  22. def after_request(response):
  23. return cors(response)
  24. # ── GET /get ──────────────────────────────────────────────────────────────────
  25. @app.route("/get", methods=["GET", "OPTIONS"])
  26. def demo_get():
  27. data = {
  28. "code": 0,
  29. "message": "GET 请求成功",
  30. "data": {
  31. "method": "GET",
  32. "url": request.url,
  33. "args": dict(request.args),
  34. "headers": dict(request.headers),
  35. "timestamp": int(time.time()),
  36. },
  37. }
  38. return jsonify(data)
  39. # ── POST /post ────────────────────────────────────────────────────────────────
  40. @app.route("/post", methods=["POST", "OPTIONS"])
  41. def demo_post():
  42. body = {}
  43. raw = ""
  44. try:
  45. body = request.get_json(force=True) or {}
  46. raw = json.dumps(body, ensure_ascii=False)
  47. except Exception:
  48. raw = request.data.decode("utf-8", errors="replace")
  49. data = {
  50. "code": 0,
  51. "message": "POST 请求成功",
  52. "data": {
  53. "method": "POST",
  54. "url": request.url,
  55. "body": body,
  56. "raw": raw,
  57. "headers": dict(request.headers),
  58. "timestamp": int(time.time()),
  59. },
  60. }
  61. return jsonify(data)
  62. # ── GET /stream/<n> ───────────────────────────────────────────────────────────
  63. @app.route("/stream/<int:n>", methods=["GET"])
  64. def demo_stream(n):
  65. """
  66. 逐行输出 n 条 JSON,每条之间延迟 500ms,模拟流式响应。
  67. 客户端用 @Streaming + ResponseBody 逐行读取即可。
  68. """
  69. n = min(max(n, 1), 20) # 限制 1~20 条
  70. def generate():
  71. for i in range(n):
  72. line = json.dumps(
  73. {
  74. "index": i + 1,
  75. "total": n,
  76. "message": f"流式数据第 {i + 1} 条",
  77. "timestamp": int(time.time()),
  78. },
  79. ensure_ascii=False,
  80. )
  81. yield line + "\n"
  82. time.sleep(0.5)
  83. return Response(
  84. generate(),
  85. status=200,
  86. mimetype="application/octet-stream",
  87. headers={"X-Accel-Buffering": "no"},
  88. )
  89. # ── 入口 ──────────────────────────────────────────────────────────────────────
  90. if __name__ == "__main__":
  91. print(f"Demo server running on http://0.0.0.0:{PORT}")
  92. print(" GET http://<本机IP>:8080/get")
  93. print(" POST http://<本机IP>:8080/post")
  94. print(" GET http://<本机IP>:8080/stream/5")
  95. app.run(host="0.0.0.0", port=PORT, debug=False, threaded=True)