Python_ Original _web Frame

Source: Internet
Author: User

Gen: 10_4_2017

Repair:

What is a web framework?

--essentially a socket, user request, Business logic processing, return processing results

--A frame that contains a socket or does not contain a socket

What is WSGI?

--Web Framework Gateway Interface, Django, flask no socket, tronado frame comes with socket

--Python has wsgiref module with socket service, there is a problem in using the module in Python3

How do I write a simple web framework?

--Import WSGI module

--Define main logic handler function, GET request URL and define reply request logic in main function

--Determine the URL and then assign the URL that meets the requirements to the corresponding handler function

--Returns the corresponding function processing result in the main function

--Instance service object in Mian function and start Web service

#!/usr/bin/python2#-*-coding:utf-8-*-from wsgiref.simple_server import Make_serverdef Home ():    return ' home ' def Index ():    return ' index ' def runserver (environ, start_response):    start_response (' OK ', [' Content-type ', ' Text/html ')]) (    print environ[' path_info ')    url = environ[' path_info ']    if url = = '/home ':        return ()    elif url = = '/index ':        return index () if __name__ = = ' __main__ ':    httpd = Make_server (', 9999, runserver) 
   
    httpd.serve_forever () # URL every time to judge, when the URL has too many times, come out a lot of duplicate code # If you join the database operation, it seems a bit messy, logical structure confusion, how to solve? # You might want to categorize URLs and corresponding functions first
   

  What are the problems with the service above? URLs and processing functions are put together, a little messy

#!/usr/bin/python2#-*-coding:utf-8-*-from wsgiref.simple_server Import make_server # import WSGI Module Def home (): With                                     Open (' home.html ', ' R ') as F: # opens file, read in data = F.read () return data                                            # home Logic Processing Def index (): Return ' Welcome to index ' # index logic processing urls = {             # URL and function to establish a mapping relationship between the functions '/home ':/index ': Index,}def runserver (environ, start_response): # to request URL processing with match start_response (' OK ', [(' Content-type ', ' text/html ')]) url = environ[' path_info '] if u        RL in Urls.keys (): # Determine if URL is in urls func = urls[url] # call handler function return func () # returns the processing result Else:return ' 404 ' # Not returning error 404if __name__ = = ' __main__ ': httpd = Make_server (", 9999, Runserver) Httpd.serve_forever () # Although the implementation does not modify the primary logical function, only The URL dictionary needs to be modified to solve the matching problem # logical knotStructure is not chaotic, but the processing function and URL too many words, all written in a page, not easy to maintain and read, how to implement? # You can write your own functions in a. py file, and then use the respective import to implement the classification, logic clear?  # You can write the URL in a url.py file, the processing function is written in the Ccontrollers, the returned HTML is written in the view directory, do not solve the problem?

  

First set up the Yizhihua directory, save the directory under the __init__.py file, under the Yizhihua directory to create the following file

-urls.py Write

From Yizhihua Import controllersurls = {                                            # URL and function to establish a mapping relationship through    a dictionary '/home ': Controllers.home,    '/index ': Controllers.index,}

  -start.py Write-Start program entry

#!/usr/bin/python2#-*-coding:utf-8-*-from wsgiref.simple_server import make_server       # import WSGI module from Yizhihua Import URLs                           # imports URLs module def runserver (environ, start_response):             # to request URL processing and matching    start_response (' OK ', [(' Content-type ', ' text/html ')])    url = environ[' path_info ']    if URL in URLs. Urls.keys ():                     # Determines if the URL is        func = URLs in URLs. Urls[url]                       # call handler function return        func ()                               # return processing result    else: return        ' 404 '                                # does not return error 404if __name__ = = ' __main__ ':    httpd = Make_server (", 9999, Runserver)    httpd.serve_forever ()

  -controllers.py Write-Logical processing function

From JINJA2 import Templateimport osdef Home (): With    open (os.path.join (' views ', ' home.html '), ' R ',) as F:        # Open File, Read in        result = F.read ()    template = Template (result) # Instance render object    data = Template.render ({' User_ List ': [' + ', ' Beauty ', ' hehe '], ' name ': ' Yizhua '} ' # render template    return Data.encode (' Utf-8 ') # character transcoding def i Ndex (): With    open (' Os.path.join ', ' index.html '), ' R ') as F:      # Open file, read in        data = F.read ()    return Data                                                   # Index Logic processing # os.path.join () to spell two characters into a path

-View directory, where you save HTML files, template files

-Home.html Write

1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4     <MetaCharSet= "UTF-8">5     <title>Home</title>6 </Head>7 <Body>8     <H1>{{Name}}</H1>9     <ul>Ten {% for item in user_list%} One         <Li>{{Item}}</Li> A {% endfor%} -     </ul> - </Body> the </HTML>

    -Index.html Write

1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4     <MetaCharSet= "UTF-8">5     <title>Index page</title>6 </Head>7 <Body>8     <H1>Index</H1>9 </Body>Ten </HTML>

 -models.py is temporarily not written, mainly used to write data table structure, and database interaction

Then launch the Start module, Access Http://127.0.0.1:9999/home or Http://127.0.0.1:9999/index to get the returned page

What modules are in the framework?

--Models database related operations

--Views Template HTML file

--Controllers business logic

In fact, the code is logically categorized, through which each mutually import, to achieve integrity, the above is the MVC framework

--Models database related processing

--Views Business logic

--tempates Template HTML file

This is the MTV framework, essentially the same as MVC, except that the names are different.

How do I implement an incoming parameter in a dynamic template?

--Replace a value with a custom {{item}}, and then replace Data.replace ({{Item}}, ' replace value ') with a character

--Cyclic replacement

What are the modules in the template language?

JINJA2 module, template language

--pip Install JINJA2

-Import from JINJA2 import Template

-Pass the results of the read in to template template = Template (read the results)

-render the result data = Template.render ({Field 1: value 1, List 2: List value 2}) in dictionary form

Replace value: Replaces the position of {{Field 1}} in the template with a value of 1

Loop: {% for item in List 2}

{{Item}}

{% endfor%} loops in the template each time the list value 2 is placed in the position of {{Item}}

-generally written in HTML, and then in logical functions

--After the rendering is complete, the subsequent transcoding. Decode (' Utf-8 ')

Python_ Original _web Frame

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.