tornado learning notes day03 response output



Write data from chunk to output buffer

Using write method to write json data

  • The way we serialize json manually is that the property value of content type is text HTML
  • We use write automatic serialization, and our content type attribute is application/json



  • Called before entering the HTTP response method
  • You can rewrite this method to set the default headers

Be careful:

  • The field set with set header in this HTTP processing method will override the value of set default header()
  • This set header and set default headers () have the order of execution. Of course, the default one is executed first


Function: set status code for response



  • Value of status code, type int
  • If reason's value is none, the status code must be normal


  • String type
  • A phrase describing a status code, such as not found in 404 not found

Redirect self.redirect(url):


  • For example, if you write index sometimes, if you don't, you can enter the homepage, which is the function of redirection
  • Redirect to url URL


class RedirectHandler(RequestHandler):
    def get(self):
        # Direct redirection

self.send_error(status_code = 500,**kwargs):

  • Effect:
    • Throw HTTP error status code, default is 500
    • tornado will call the write error() method for processing
    • Corresponding to the custom 404 in Django


  • Effect:
    • It is used to handle the error information thrown by send error and return it to the browser error interface
  • Example:
class ErrorHandler(RequestHandler):
    def write_error(self, status_code: int, **kwargs: Any) -> None:
        if status_code == 500:
            self.write("Server internal error 500")
        elif status_code == 404:
            self.write("Resource does not exist")
            self.write("I don't know what's wrong")

    def get(self):
        # Direct redirection
        flag = self.get_query_argument("flag")
        if flag == '0':
            # Throw an error here, and the following will not be executed

        print("Nothing wrong with it.")

        self.write("you are right!")

Reverse resolution of route

This tornado is simpler than Django's reverse parsing

Give the route a name, so that the jump link fails after the url changes

Application end

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", index.IndexHandler),
            (r"/sunck", index.SunckHandler,{'name':"victor",'age':19}),

            # Status code
            (r"/status", index.StatusHandler),
            # redirect
            (r"/index", index.RedirectHandler),
            # error handling
            # iserror?flag=2
            # If it is equal to 0, it means there is an error. If it is not equal to 0, it means there is no error
            (r"/iserror", index.ErrorHandler),


View function

class IndexHandler(RequestHandler):
    def get(self):
        self.write("main page info tornado!")
        url = self.reverse_url("kaige")
        self.write("<a href='%s'>Go to another page</a>" % (url))
        # Self.write ("< a href =" + URL + "> go to another page < / a >")


Using HTTP protocol to pass parameters to the server

Extract specific parts of a uri

Instance code, app part

''' (r"/good/(\w+)/(\w+)/(\w+)", index.GoodHandler),'''
(r"/good/(?P<p1>\w+)/(?P<p3>\w+)/(?P<p2>\w+)", index.GoodHandler),

View function section

class GoodHandler(RequestHandler):
    def get(self,p1,p3,p2):
        self.write("GoodHandler kaige !")

Query string (GET pass parameter)

Http: / / / zhangmanyu? A = 1 & B = 2 & C = 4 type

Here's a way
def get_query_argument(
        name: str,
        default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
        strip: bool = True,
    ) -> Optional[str]:
  • Returns the value of the specified parameter from the get request parameter
  • If a parameter with the same name appears, theoretically this method will return the last value
  • If we set it to not pass the name parameter, it returns the default value
  • Indicates whether to filter out the blank characters on both sides
  • True by default, filtered

Http: / / / zhangmanyu? A = 1 & A = 2 & C = 4 type

  • In general, this is rarely the case
  • def get_query_arguments(self, name: str, strip: bool = True) -> List[str]:
  • Parameters: same as above

Data carried by the request body (pass parameters in POST mode)

  • This is more powerful than Django. You don't need to define a routing function. Just add a method to the class
  • The prototype is here
def get_body_argument(
        name: str,
        default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
        strip: bool = True,
    ) -> Optional[str]:

You can GET both GET and POST requests

  • It's OK to go directly to the prototype. You should not only learn to draw inferences from others, but also expand yourself
  • The prototype is here
def get_argument(  # noqa: F811
    name: str,
    default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
    strip: bool = True,
) -> Optional[str]:
  • In fact, sometimes, some structures can be understood more deeply only by looking at the source code
  • There's more than one. That's the same thing
def get_arguments(self, name: str, strip: bool = True) -> List[str]:

In the HTTP header, add custom fields

request object


  • Stored information about the request

For example:

  • HTTPServerRequest(protocol='http', host='', method='GET', uri='/zhuyin', version='HTTP/1.1', remote_ip='')


  • Method: the way of HTTP request
  • Host: requested host name (host name of the server)
  • uri: the complete resource address of the request, including the path and the parameter part of the get query
  • Path: the path part of the request
  • query: request parameters section
  • Version: HTTP version used
  • headers: requested protocol header, dictionary type
  • Body: request body data (POST)
  • Remote? ip: the ip address of the client
  • Files: files uploaded by users, dictionary type

tornado.httputil.HTTPFile object

  • Function: we can see it in the uploaded file
  • Effect: Is the received file object


  • filename: the actual name of the file
  • body: data entity of the file
  • Content type: type of uploaded file

File upload

First, filter a data structure, that is, the data structure of the request.file object

An example of the structure of the request.file object
    'file': [
        {'filename': 'a.txt',
         'body': b'suck is a wonderful man',
          'content_type': 'text/plain'

        {'filename': '',
          'body': b'x9xa0',
           'content_type': 'application/octet-stream'
    'img': [
        {'filename': 'a.img',
         'body': b'as\dfhg\ahhf\a\\h\ahfh\af',
          'content_type': 'text/plain'

Then, loop through it!

class UpFileHandler(RequestHandler):

    def get(self):
    def post(self):
        self.write("Upload success!")
        contents = self.request.files
        for content in contents:
            fileArr = contents[content]
            for fileObj in fileArr:
                file_path = os.path.join(BASE_DIR,"upfile/"+fileObj.filename)
                with open(file_path,"wb") as f:
                print("File written successfully")

I know, if you can't understand it, add some comments!

''' Import system operation module,Used to store accepted files'''
import os
# Import base? Dir and locate the absolute path in the server
from config import BASE_DIR
from tornado.web import RequestHandler

class IndexHandler(RequestHandler):
    def get(self):
        self.write("main page info tornado!")

class UpFileHandler(RequestHandler):
    //The view class used to upload the file, which contains the get method to display the form
    //And POST methods for handling uploads
    # get method, load form template
    def get(self):

    # File upload is specified as POST request
    def post(self):
        # Used to receive uploaded information
        self.write("Upload success!")
        # Get the contents of all file objects through the request.files object
        contents = self.request.files
        # Traverse the largest dictionary to get the key of no dictionary of type name
        # Where content is the key in the dictionary, such as file,img
        for content in contents:
            # Get the value through the key to get the file list of the same name
            # This filearr is a list
            fileArr = contents[content]
            # Traverse file list
            # fileObj is another dict dictionary type
            for fileObj in fileArr:
                # Define storage path
                # Get the absolute location of the server through base? Dir
                # Through the filename key of the dictionary of fileObj,
                # To get the file name and define the file name of the storage path
                file_path = os.path.join(BASE_DIR,"upfile/"+fileObj.filename)
                # write file
                with open(file_path,"wb") as f:
                    # The content of the file is body
                    # What TODO needs to deal with here is that the user uploads the file with the same name
                    #  Problems that cause files to be overwritten in the server again
                print("File written successfully")

Tags: Front-end JSON Django Attribute

Posted on Mon, 16 Mar 2020 22:59:44 -0400 by nigelbashford