The content printed by Django view function is not displayed

  introduction

  Today I found a very strange problem. In the django project view function, using print, the result cannot be printed. Since the project was written for a long time, and it was checked for a long time, the root cause was finally found. Sometimes the bug is hidden in that inconspicuous corner!

  problem

 

 

 

From the above picture, the view function request is successful, and there is nothing wrong, but it is puzzled, why is this happening?

Then add a log and look at:

 

 

 The log can be displayed normally, but printing cannot always be displayed.

 

  Stepped pit

  And I changed the project, my other projects, try to print, it is normal. This project alone will not work, but the project operation is normal, and the data returned by the front-end operation back-end is also normal. In all these seemingly normal situations, this printing is never displayed, not just this view function, but all the view functions in me added a printing function to not display. Later, under the guidance of a great god, I tried to build a new project and got it again, but it still didn't work. Finally, there is only a step by step comment to find the reason. The result eventually found the cause.

  solve

  The root cause is that I encapsulated a module, which was caused by two lines of code.

import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

  After trying this comment, the result is printed.

 

 

 

Why is this? These two codes actually change the output method. When we need to print some characters, we don't print them immediately, but put the characters that need to be printed into the buffer first, and print them when the buffer is refreshed. When the buffer is not full, Or when the program is not finished, you can use sys.stdout.flush () to force the buffer to be flushed and print it immediately.

  to sum up

  I have been lying in this pit for almost 6 hours. Sometimes I have to be cautious when writing the code myself, and there must be remarks. Otherwise, after a long time, you will come to maintain the code. It will consume you a lot of time. Although this seems to be a small problem, it took me too long, so record it, hoping to help my friends who encounter the same problem.

   If you are interested in python test development related technology partners, welcome to join the test development learning exchange QQ group: 696400122, no pace, no miles

 

Guess you like

Origin www.cnblogs.com/liudinglong/p/12705855.html