Python mock Django Framework Instance

Source: Internet
Author: User
first, Python implements the Web server

Web development must first have a Web server. such as Apache, but in the development phase it is best to have a simple and convenient development server,
Easy to restart for debugging, and so on after the development of debugging, then deploy the code to mature and stable and efficient Web server.

#-*-Coding:utf-8-*-from wsgiref Import simple_server# define a simple Web application that outputs Hello World and environment Variables Def hello_app (environ, start_r esponse): # Output HTTP header, text/plain means plain text start_response (' OK ', [(' Content-type ', ' Text/plain ')]) # Prepare the contents of the output content = [] C Ontent.append (' Hello World ') for key, value in Environ.items ():  content.append ('%s:%s '% (key, value)) # output, according to Wsgi Protocol, the return request is an iterator that returns a list to return [' \ n '. Join (content)]# constructs the development server object, sets the address and port of the binding, and passes the Hello World application to his server = Simple_ Server.make_server (' localhost ', 8080, Hello_app) # Start the Development Server Server.serve_forever ()

After executing this program, open your browser and visit a URL that starts with http://localhost:8080 to see what environ contains.

(Intercept a small part)

Second, the basic knowledge

The HTTP protocol is used between the browser and the Web app, which specifies the format of the request and response.
1, request package (Http request)
The request primarily includes the requested method, the requested URL, the request header, and the request body.
The requested method HTTP specifies get, POST, PUT, DELETE, but Web requests initiated by the browser generally involve only get and post requests.
Get is commonly used to get server content, post-like modifications, put add, delete delete.
A POST request is typically initiated by submitting a form form for HTML. Redirection is required after success.
The biggest difference between the Get,http requests from the protocol is that the GET request has no request body, and the POST request has. This means that a POST request can be
Sending large amounts of data to the server, such as uploading files, of course, get requests can also pass parameters to the server via the URL itself and its parameters, such as
Url?arg1=value&arg2=value
The request header is the description that contains the request package. such as coding, packet length and so on.
2. Response Package (Http Response)
The format of the HTTP response packet is simpler, including the status code, the response header, and the response body, and the status code represents the result of the request, such as
200 indicates success
404 indicates that the resource was not found
500 indicates a server error
301 indicates that the resource has been replaced by an address and the client needs to jump.
The response header and the request header are similar, including some descriptive information, the response body is generally the output content, most of the page HTML code.
3, the life cycle of the request
1. The Web server receives the original HTTP request and then wraps it to the Web application with some degree of packaging
2. After the Web application is processed, return the data to the Web server in a certain format
3. The Web server then wraps the data into an HTTP response packet back to the browser.
4. About CGI
CGI (Common Gateway Interface) is an ancient protocol between a Web server and a Web application, and in the CGI protocol,
The Web server places the various information of the HTTP request into the environment variables of the CGI application, and the CGI application outputs its response header through the standard output.
and the corresponding content to the Web server.
The protocol used between the development server and the application above is called Wsgi, which, like CGI, wraps the request into a key-value pair,
Only CGI is passed to the CGI application via environment variables, and WSGI is passed directly using the Python Dictionary object.
Hello_app's first parameter, environ, is the Dictionary object that contains the request information, the second parameter is a function, and the Web application outputs the response content
It needs to be called first to output the status code and the response header.
Handling Web requests and responses here using the Webob module to handle requests and responses, need to install, here first to install the Setuptools module, a package management tool, you can automatically download the required packages through this tool, similar to Ubuntu App-get. The following is the address: Http://pypi.python.org/pypi/setuptools installation ends, you can enter directly on the command line: Easy_install webob This will automatically download the installation.

Simple to use :

>>> # import Request Object

>>> from Webob import Request

>>> environ = {}

>>> # Use Request to wrap environ dictionaries

>>> req = Request (environ)

Use a request class to wrap the Environ, and then access the Environ through the properties and methods of the Request object. Since only one web environment can get a real environ dictionary, Webob provides a way to emulate a simple Web request in order to make it easier for you to test in the shell:

You can also find other useful information through req.

It is also possible to wrap the response information through the response object in the Webob module.

Use the Webob module below to rewrite the previous Hello_app

#-*-Coding:utf-8-*-from wsgiref import simple_serverfrom webob import Request, response# We've added a feature that is based on what the user passed after the URL Parameter # Displays the appropriate content Def hello_app (request): content = [] # Gets the parameter of the GET request Content.append (' Hello%s '%request. get[' name ']) # outputs all Environ variables for key, value in Request.environ.items ():  content.append ('%s:%s '% (key, value)) Res Ponse = Response (body= ' \ n '. Join (content)) response.headers[' content-type '] = ' text/plain ' return response# Packaging requests and Responses Def wsgi_wrapper (environ, start_response): request = Request (environ) response = Hello_app (Request) # response The object itself also implements the Protocol to communicate with the WSGI server, # So it can help us handle the interaction with the Web server. # This is a strange sentence, what does the object use parentheses mean .... Return response (environ, start_response) server = Simple_server.make_server (' localhost ', 8080, wsgi_wrapper) Server.serve_forever ()

In order to make the wsgi_wrapper a little more generic, it can be designed as a decorator form:

#-*-Coding:utf-8-*-from wsgiref import simple_serverfrom webob import Request, response# written as decorator Wsgi_wrapperdef Wsgi_w Rapper (func): Def new_func (environ, start_response):  request = Request (environ)  response = func (Request)  Return response (environ, start_response) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ return new_ func# Application @wsgi_wrapperdef Hello_app (Request): content = [] content.append (' Hello%s '%request. get[' name ')) for key, value in Request.environ.items ():  content.append ('%s:%s '% (key, value)) Response = Response (b Ody= ' \ n '. Join (content)) response.headers[' content-type '] = ' text/plain ' return responseserver = Simple_server.make_ Server (' localhost ', 8080, Hello_app) server.serve_forever ()

Third, the template
Sure enough, you still need to use the template, not always directly in the response to write long strings of HTML code.
The template engine in Python is mainly Mako, Genshi, Jinjia and so on.
Mako main feature is that the template can be more convenient embedded Python code, and execution efficiency first-class;
Genshi is characterized by XML-based, very easy-to-understand template syntax, a good choice for those who love XHTML,
Python code can also be embedded to implement some complex presentation logic;
Jinja and Genshi have very simple template syntax, just do not depend on the format of XML, it is also suitable for designers to directly make the template,
It is also possible to embed Python code to implement some complex presentation logic.

Install it using Mako, address http://pypi.python.org/pypi/Mako, download python setup.py install
Examples of simple modules:

# #-*-Coding:utf-8-*-  Simple Mako Template   

Hello ${name}!

    % for key, value in Data.items ():
  • ${key}-${value}

Save As simple.html file, then need to pass data and name two parameters to the template object, then render, you can enter HTML content

#-*-coding:utf-8-*-# Import Template object from mako.template import template# use template file name to construct template Object Tmpl = Templates (filename= './simple.html ', output_encoding= ' Utf-8 ') # Constructs a simple dictionary fill template and print out print tmpl.render (name= ' python ', data = {' A ': 1, ' B ': 2})

Save As test_template.py file, run to enter content:
$ python test_template.py

  Simple Mako Template   

Hello python!

  • A-1
  • B-2

The Hello_app program is refactored as follows:
1. Place the wsgi_wrapper separately in the Universal module utils.py:

#-*-Coding:utf-8-*-from webob import requestdef Wsgi_wrapper (func): Def new_func (environ, start_response):  reques t = Request (environ)  response = func (Request)  return response (environ, start_response) new_func.__name__ = Func . __name__ new_func.__doc__ = func.__doc__ return New_func

2. Completely separate the Hello_app to form a separate module controller.py:

#-*-Coding:utf-8-*-from utils import wsgi_wrapperfrom webob import responsefrom Mako import template# integrated template functionality Hello_a Pp@wsgi_wrapperdef Hello_app (Request): Tmpl = Template (filename= './simple.html ', output_encoding= ' utf-8 ') content = Tmpl.render (name=request. get[' name '], Data=request.environ) return Response (body=content)

3. This is how the main.py becomes:

#-*-Coding:utf-8-*-from wsgiref Import simple_serverfrom Controller Import Hello_appserver = Simple_server.make_server (' localhost ', 8080, Hello_app) server.serve_forever ()

Four, ORM (object Relation Mapping, objects relational mapping)
Finally, this is the step, as a Web application, or need to work with the database.
Using SQLAlchemy, this is an ORM (object-relational mapping) library that provides a mapping between a Python object and a relational database. And Django's models.
You can use Python code to create database tables and manipulate them as well.
SQLAlchemy can also automatically map the inheritance of Python objects, enabling eager loading, lazy loading, to map the Model directly to the custom
SQL statements, support for n-more databases, and so on. It can be said that SQLAlchemy has not lost the power of Hibernate, without losing the Python
Simplicity and elegance.
How to use:

#-*-Coding:utf-8-*-from sqlalchemy import *from sqlalchemy.orm import Sessionmaker, Scoped_sessionfrom sqlalchemy.ext. Declarative import declarative_base# Create the database engine, where we directly use the Python2.5 's own database engine: sqlite,# directly in the current directory to build a database called data.db engine = Create_engine (' sqlite:///data.db ') # SQLAlchemy all database operations are managed by a session # for more information on the session please refer to:/http Www.sqlalchemy.org/docs/05/session.htmlSession = Scoped_session (Sessionmaker (Autocommit=false, Autoflush=false, Bind=engine)) Base = Declarative_base () class Dictionary (base): # Python object corresponds to the table name of the relational database __tablename__ = ' t_dictionary ' # defines automatic , parameter meanings are: Database field name, field type, other option key = Column (' key ', string (255), primary_key=true) value = Column (' Value ', string (255)) # Create Database Base.metadata.create_all (engine) session = Session () for item in [' Python ', ' Ruby ', ' Java ']: # constructs an Object dictionary = Dictionary (Key=item, Value=item.upper ()) # tells SQLAlchemy to add the object to the database Session.add (Dictionary) # submit session, where the operation of the database is actually performed , add three records to Database Session.commit () # Query database for dictionary objects corresponding to dictionary in Session.quEry (Dictionary): Print Dictionary.key, Dictionary.value 

The above code you execute two times will be an error, why ... Because the primary key for inserting the database is duplicated ....
This can be integrated into the previous controller.py file.

#-*-Coding:utf-8-*-from utils import wsgi_wrapperfrom webob import responsefrom mako.template import template# import public m  Odel module from model import session, Dictionary@wsgi_wrapperdef Hello_app (Request): Session = Session () # Query to all Dictionary objects Dictionaries = Session.query (Dictionary) # then convert the list to a dictionary based on the key, Value property of the Dictionary object data = Dict ([(Dictionary.key, Dicti Onary.value) for dictionary in dictionaries]) Tmpl = Template (filename= './simple.html ', output_encoding= ' utf-8 ') Content = Tmpl.render (name=request. get[' name '], Data=data) return Response (body=content)

V. URL Distribution Control
To design different URLs for different resources, the client requests the Url,web application to navigate to the specific function and execute it according to the URL requested by the user.
There are many benefits to providing a clean URL:
1. Readability, through the URL, you can probably understand what it provides
2. User easy to remember and easy to enter directly
3. Well-designed URLs are generally shorter and more friendly to search engines
Using the selector module to process URL mappings
Download address http://pypi.python.org/pypi/selector, download the source file for Python setup.py install
First, put the configuration of the URLs in the urls.py alone.

#-*-Coding:utf-8-*-from Controller Import hello_appmappings = [('/hello/{name} ', {' GET ': Hello_app})]

Modify main.py

#-*-Coding:utf-8-*-from wsgiref import simple_serverfrom URLs import mappingsfrom selector import selector# build a URL dispenser App = Selector (mappings) server = Simple_server.make_server (' localhost ', 8080, app) Server.serve_forever ()

The name parameter can then be obtained by environ[' Wsgiorg.routing_args ' in Hello_app.
But in Wsgi_wrapper can actually further simplify the work of Hello_app: directly to the analysis of the parameters
Pass it as a function parameter! Modify utils.py:

From Webob import requestdef Wsgi_wrapper (func): Def new_func (environ, start_response):  request = Request (environ) C1/>position_args, Keyword_args = Environ.get (' Wsgiorg.routing_args ', ((), {}))  response = func (Request, *position _args, **keyword_args)  return response (environ, start_response) new_func.__name__ = func.__name__ new_func.__doc_ _ = func.__doc__ return New_func

That Hello_app can be changed into this:

... @wsgi_wrapperdef hello_app (Request, Name= "): ... content = Tmpl.render (Name=name, Data=data) return Response (body= Content) perform main.py, Access Http://localhost:8080/hello/Python

Summarize
The above part of the implementation, is similar to the Django framework of several major functional modules, I hope that everyone's learning is helpful.

  • 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.