当前位置:   article > 正文

Flask流输出stream和前端jquery逐行输出代码示例html通用的路由vue源码_flask 流式输出

flask 流式输出

前端jquery代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Streaming Response Example</title>
  7. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8. </head>
  9. <body>
  10. <textarea id="output" rows="10" cols="50"></textarea>
  11. <input type="number" id="quantity" min="1" placeholder="Enter quantity">
  12. <button id="submit">Submit</button>
  13. <script>
  14. $(document).ready(function() {
  15. var output = $('#output');
  16. var quantityInput = $('#quantity');
  17. var submitButton = $('#submit');
  18. submitButton.on('click', function() {
  19. var quantity = parseInt(quantityInput.val());
  20. if (isNaN(quantity) || quantity <= 0) {
  21. alert("Please enter a valid quantity.");
  22. return;
  23. }
  24. fetch('/stream_data?quantity=' + quantity)
  25. .then(response => {
  26. const reader = response.body.getReader();
  27. return new ReadableStream({
  28. start(controller) {
  29. function push() {
  30. reader.read().then(({ done, value }) => {
  31. if (done) {
  32. controller.close();
  33. return;
  34. }
  35. controller.enqueue(value);
  36. push();
  37. });
  38. }
  39. push();
  40. }
  41. });
  42. })
  43. .then(stream => {
  44. const decoder = new TextDecoder();
  45. const reader = stream.getReader();
  46. function processText({ done, value }) {
  47. if (done) return;
  48. const text = decoder.decode(value, { stream: true });
  49. console.log("received data -", text);
  50. output.val(output.val() + text);
  51. reader.read().then(processText);
  52. }
  53. reader.read().then(processText);
  54. })
  55. .catch(error => {
  56. console.error('Error:', error);
  57. });
  58. });
  59. });
  60. </script>
  61. </body>
  62. </html>

jquery2示例:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Streaming Response Example</title>
  7. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <textarea id="output" rows="10" cols="50"></textarea>
  12. <input type="number" id="quantity" min="1" placeholder="Enter quantity">
  13. <button id="submit">Submit</button>
  14. </div>
  15. <script>
  16. $(document).ready(function(){
  17. $('#submit').click(function(){
  18. var output = $('#output');
  19. var quantity = $('#quantity').val();
  20. fetch(`/stream_data?quantity=${quantity}`, {
  21. method: "GET",
  22. headers: {
  23. "Content-Type": "application/json",
  24. }
  25. })
  26. .then(response => {
  27. const reader = response.body.getReader();
  28. const decoder = new TextDecoder();
  29. reader.read().then(function processText({ done, value }) {
  30. if (done) {
  31. //output.val('');
  32. return;
  33. }
  34. const text = decoder.decode(value, { stream: true }).replace('undefined', '');
  35. console.log("received data -", text);
  36. output.val(output.val() + text);
  37. reader.read().then(processText);
  38. });
  39. })
  40. .catch(error => {
  41. console.error('Error:', error);
  42. });
  43. });
  44. });
  45. </script>
  46. </body>
  47. </html>

vue代码示例:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Streaming Response Example</title>
  7. <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <textarea id="output" rows="10" cols="50">{{ outputText }}</textarea>
  12. <input type="number" id="quantity" min="1" v-model.number="quantity" placeholder="Enter quantity">
  13. <button @click="submit">Submit</button>
  14. </div>
  15. <script>
  16. new Vue({
  17. el: '#app',
  18. data: {
  19. outputText: '',
  20. quantity: 1
  21. },
  22. methods: {
  23. async submit() {
  24. try {
  25. const response = await fetch(`/stream_data?quantity=${this.quantity}`, {
  26. method: "GET",
  27. headers: {
  28. "Content-Type": "application/json",
  29. }
  30. });
  31. if (!response.body) return;
  32. const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
  33. while (true) {
  34. const { value, done } = await reader.read();
  35. if (done) break;
  36. const text = value?.replace('undefined', '');
  37. console.log("received data -", text);
  38. this.outputText += text;
  39. }
  40. } catch (error) {
  41. console.error('Error:', error);
  42. }
  43. }
  44. }
  45. });
  46. </script>
  47. </body>
  48. </html>

后端python接口:

  1. from flask import Flask, Response, send_from_directory, request
  2. import time
  3. app = Flask(__name__, static_folder='static')
  4. # @app.route('/')
  5. # def index():
  6. # return app.send_static_file('index.html')
  7. @app.route('/<html_file>')
  8. def serve_html(html_file):
  9. return send_from_directory(app.static_folder, html_file)
  10. @app.route('/stream_data')
  11. def stream_data():
  12. quantity = int(request.args.get('quantity', 10)) # 获取数量值,默认为10
  13. if quantity <= 0:
  14. return "Invalid quantity value", 400 # 返回400错误
  15. def generate():
  16. for i in range(quantity):
  17. yield f"Data point {i}\n"
  18. time.sleep(1) # 模拟生成数据的延迟
  19. return Response(generate(), mimetype="text/event-stream")
  20. if __name__ == '__main__':
  21. app.run(host='0.0.0.0', port=8666)

其他。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
  • 相关标签
      

    闽ICP备14008679号