Teach you to develop a python module in minutes (1)-a method that can be printed directly in a browser, python Module
Once, those who used the python print command were amazed at the streamlining of the python syntax. Later, they used web development frameworks such as tornado and django and had to admire those who developed these frameworks. So we started to use their framework =, a configuration that has been repeated countless times. So the question is, if I have done a similar problem in a certain field many times, do I need to repeat the configuration every time? By chance, I was wondering if they could be further streamlined in their frameworks to achieve more efficient development for a specific purpose. Use of the web framework, including the server and browser. This modification adopts the tornado framework.
First, we start with the print ("Helloworld!") on the first day of getting started with python !") Start.
Dry Goods start:
First, let's look at a simplified tornado code:
import tornado.ioloopimport tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/index", MainHandler),]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
The above code outputs hello, world! in the browser! From top to bottom, the functions are module import, business processing class, route ing, and server-side enabling.
This blog introduces the module modification in detail. For more information about tornado, see the following link:
- Detailed description of the source code required for efficient tornado Development
Tornado web advanced development project drawer page login verification, form verification, thumb ups, comments, article paging processing, send email verification code, login verification code, registration, publish articles, upload pictures
Tornado of Web Framework
Although the above Code implements the output content in the browser, there are many shortcomings:
- Every time you print something, you need to write so much code.
- Only string printing is supported. Common data structures such as dictionaries, lists, and tuples are not supported.
We know that the print usage of python is very simple. We just need to put the print content inside the print to print the desired result in one sentence.So the question is,Is there a simple way to makeCan we print out any data structure we want in a browser in one sentence?
The answer is yes, of course. Yes, you are not mistaken. Next, the blogger will show you how to implement this magical function step by step.
Module import:
import tornado.ioloopimport tornado.webimport json
What is different from the previous one is that we have added the json module. You should have guessed it. The blogger wants to support different data structures through json. Yes, that's right! Some people say that this is nothing. I will, too. Well, don't go. Continue to look down! For more information, see the following section!
Solution:
In fact, solving this problem is actually very simple. The core issue is how to pass the data that you need to print to self. write by passing parameters.
To solve this problem, we need to specify where the tornado framework can transmit parameters. Let's take a look at the tornado code:
import tornado.ioloopimport tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/index", MainHandler),]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
We use an internal and external analysis method:
- The first is self. write ("Hello, world"). The result we want to implement is self. write (arg). arg represents the parameters passed by the user. Where can I transfer this arg from? The get method is wrapped in the get method. We know that the http get method can pass in data through question marks and key-value pairs on the url of the browser, but does the user input data in the browser url every time they print the data? This is obviously unreasonable. Therefore, parameter passing through the get method does not work.
- The next step is the business processing MainHandler. Can it transmit parameters? We know that a class can pass parameters through the init method. You can pass parameters every time you instantiate a class, do we need to define an init method and inherit the init method of the parent class? But the question is, where is the MainHandler instantiated, and where do we need to transmit the parameter? Here we go to the tornado source code, but the source code can be changed at will, so it is unreasonable to PASS Parameters in the init method.
- In order to follow the principle of closed source code and open extension, tornado source code has already reserved a location for us. This is the legendary initialize method, which is also called a "Hook ".
How to Use the initialize method?
First, you need to define a class for re-writing the initialize method in the source code, because the initialize method in the source code has nothing to do.
class BaseHandler(tornado.web.RequestHandler): def initialize(self,arg): self.arg=arg
Here, we pass in the parameter arg for the initialize method and add the attribute self to the class. arg = arg. The purpose of this operation is to inherit its subclass and use this parameter. This is the object-oriented encapsulation. The parameter is passed once, all methods of this class subclass can be used. Yes, you can find it again. If our MainHandler class inherits the BaseHandler class, you can use the self. arg parameter in the get method of the MainHandler class. The following is the modification of the MainHandler class.
class MainHandler(BaseHandler): def get(self): self.write(self.arg)
Here, you may have discovered: Well, I will pass the parameter through the initialize method. But how can I pass the parameter input by the user into the initialize method?
We found that the only thing related to the MainHandler class is routing ing. It is a tuples. The 0th elements of the tuples are regular matching. The first element is the class name of the business processing class, so the blogger thought, can we receive the third parameter? Can I transmit parameters? Take a look at the route ing:
application = tornado.web.Application([ (r"/index", MainHandler, ), ])
After analyzing the Application source code, the blogger can pass the third parameter:
Source code:
In the source code, spec is each tuples. For more source code issues, you are welcome to comment at the bottom to discuss with the bloggers. After consultation and discussion by multiple parties, The author finally concluded that the third parameter supports dictionary format transfer (the source code is ** kwargs ).
Route ing modification code:
application = tornado.web.Application([ (r"/index", MainHandler, dict(arg=json.dumps(request))), ])
In addition, to support common data structures, bloggers use json to serialize data.
The above is the entire modification process. The following describes the overall code module and how to use this module.
import tornado.ioloopimport tornado.webimport jsonclass BaseHandler(tornado.web.RequestHandler): def initialize(self,arg): self.arg=argclass MainHandler(BaseHandler): def get(self): self.write(self.arg)def print_to_browser(request,port=8888): application = tornado.web.Application([ (r"/", MainHandler, dict(arg=json.dumps(request))), ]) application.listen(port) tornado.ioloop.IOLoop.instance().start()
The above module is original to the blogger. It encapsulates tornado route ing and is enabled on the server. parameter passing is supported. The first parameter is the content to be printed, and the second parameter is optional. The default port is 8888, if the user has passed the parameter, the parameter entered by the user shall prevail.
In view of the author's article being stolen by multiple websites, forgive the author for inserting a statement here: this blog is the original author of the blogger. For the transfer, please specify the original article link: http://www.cnblogs.com/wanghzh/p/5869336.html!
Module usage:
#! /Usr/bin/env python #-*-coding: UTF-8-*-from my. mytornado import print_to_browser # import the above module print_to_browser ([1, 2, 3, 4,])
Result example:
The preceding method is as simple as print provided by python. It supports data structures such as strings, dictionaries, lists, and tuples. Default Domain Name: 127.0.0.1, default port: 8888. You only need to open the browser client (127.0.0.1: 8888 ).
If you think this article is of reference value to you, thank you very much for your suggestions at the bottom of this article!