Web Framework Authoring learning experience in Python

Source: Internet
Author: User

Learn Liaoche teacher's Python real-combat tutorial, in the Web framework this part of a more than a week, the front of the knowledge of the lack of solid, because of relatively complex, so here is summed up, is also considered to be consolidated.

First look at the calling code of the framework:

‘handlers‘)add_static(app)
    1. Use the web. The application class creates Aiohttp Server--app, where loop is eventloop used to process HTTP requests, middlewares as middleware, Here is the code used to log and process the data returned by handler as Web.response object, which is seen here response_factory
AsyncDefResponse_factory(app, handler):AsyncDefResponse(Request): Logging.info (' Response handler ... ')#获取handler的返回值, processing R = based on the different types of return valuesawait handler (Request) Print (type (r))If Isinstance (r, Web. Streamresponse):Return rIf Isinstance (r, bytes): Resp = Web. Response (body=r) Resp.content_type =' Application/octet-stream 'Return RESPIf Isinstance (R, str):If R.startswith (' Redirect: '):Return web. Httpfound (r[9:]) resp = web. Response (Body=r.encode (' Utf-8 ')) Resp.content_type =' Text/html;charset=utf-8 'Return RESPIf Isinstance (R, dict): template = R.get (' __template__ ')If templateIsNONE:RESP = web. Response (Body=json.dumps (R, ensure_ascii=False, default=Lambda o:o.__dict__). Encode (' Utf-8 ')) Resp.content_type =' Application/json;charset=utf-8 'Return RESPELSE:RESP = web. Response (body=app[' __templating__ '].get_template (template). Render (**r). Encode (' Utf-8 ')) Resp.content_type =' Text/html;charset=utf-8 'Return RESPIf Isinstance (r, int)and R >= 100 and R < 600: return web. Response (R) if isinstance (r, tuple) and len (r) = = 2:t, M = R if isinstance (t, int) and t >= 100 and T <  600: return web. Response (t, str (m)) # default:resp = web. Response (Body=str (R). Encode ( ' utf-8 ')) Resp.content_type =  Text/plain;charset=utf-8 ' return resp return response   
    1. Use the JINJIA2 template to build the front-end page, which we don't use for the time being
    2. Registering the Add_route function in the handler,aiohttp that handles the URL, we use the add_routes bulk registration of the handler of the ' Handlers ' module here
DefAdd_route(App, fn): Method = GetAttr (FN,' __method__ ',None) path = GetAttr (FN,' __route__ ', none) If Path is none or method is none: raise ValueError (' @get or @p OST not defined in%s. '% str (FN)] if not asyncio.iscoroutinefunction (FN) and not  Inspect.isgeneratorf Unction (fn): fn = Asyncio.coroutine (FN) logging.info (' Add route '%s '%s ' =%s ' (%s) '% (method, path, fn.__name__, 
                         
                           ', '. Join (Inspect.signature (FN). Parameters.keys ()))) App.router.add_route (method, Path, RequestHandler (app, FN)) 
                         
DefAdd_routes(app, module_name):#找到 '. ' Returns the location, otherwise 1 n = module_name.rfind (‘.‘)if n = = (-1): #mod为包含module_name模块中全部属性和方法的list mod = __import__ (Module_name, Globals (), locals ()) Span class= "Hljs-keyword" >else:name = Module_name[n+ 1:] mod = GetAttr (__import__ (module_ NAME[:N], Globals (), locals (), [name]), name) for attr in dir ( MoD):  #检查handler是否被 @get or @post decoration if Attr.startswith (continue fn = getattr (mod, attr) if Callable (FN): Method = GetAttr (FN,  ' __method__ ', none) path = GetAttr (FN,  ' __route__ ', none) if Method and path:add_route (App, fn)        

There is a RequestHandler class here, it has the call magic method, so you can call the function like the example, where the RequestHandler class is mainly to handler encapsulation, Gets the parameters passed in the request and passes in the handler.

    1. Add_static is the user processing tablets, JS, CSS and other static resources, only for the development environment for ease of use, the production environment is generally used nginx or CDN, and so on, this piece I have not yet figured out, no way to comb

Finally, the code of my handler module is posted for reference:

From CorowebImport GET, PostFrom AiohttpImport Web@get ('/blog ')AsyncDefHandler_url_blog(Request): body=' return body@get ('/greeting ')AsyncDefHandler_url_greeting(*,name,request): body=' return body@get ('/input ')AsyncDefHandler_url_input(Request): body=' <form action= '/result "method=" POST ">e-mail: <input type=" Email "name=" user_email "/><input type=" Submit "/></form>"return body@post ('/result ')AsyncDefHandler_url_result(*,user_email,request): body=' return body@get ('/index ' )Async def handler_url_index(Request): body=' return Body@get ('/create_comment ')async def handler_url_create_comment(Request): body=' return body        


Paste June
Links: https://www.jianshu.com/p/0fded26001e3
Source: Pinterest
The copyright of the book is owned by the author, and any form of reprint should be contacted by the author for authorization and attribution.

Web Framework Authoring learning experience in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.