Python class library 26 [basic concepts of web2py]

Source: Internet
Author: User
Tags html header web2py

Execution environment of a web2py Application
In the execution environment where models, controllers, and views are located, the following objects have been imported by default:

Global Objects:
Request, response, session, Cache

Navigation:
Redirect, HTTP

Internationalization:
T

Helpers:
XML, URL, beautifya, B, beautify, body, BR, center, code, Div, em, embed, fieldset, form, H1, H2, H3, H4, H5, H6, head, HR, HTML, I, IFRAME, IMG, input, label, legend, Li, Link, ol, UL, markmin, menu, Meta, object, on, option, P, PRE, script, optgroup, select, span, style, table, Tag, TD, textarea, Th, thead, tbody, tfoot, title, TR, TT, URL, XHTML, xmlescape, embed64

Validators:
Cleanup, crypt, encrypt, encrypt, is_date, encrypt, is_datetime, encrypt, is_email, encrypt, is_expr, encrypt, is_image, encrypt, is_in_set, delimiter, is_ipv4, is_length, is_list_of, is_lower, is_match, is_0000_to, is_not_empty, is_not_in_db, is_null_or, is_slug, is_strong, is_time, is_upload_filename, is_upper, is_url

Database:
Dal, Field

 

Other infrequently used objects need to be imported by the user, such as auth, crud, and service, as follows: From gluon. Tools import auth, crud, service.

 

2. core objects of web2py

1) Request
The request object is a common type of gluon. Storage. Storage instance in web2py, and gluon. Storage. storage is a subclass of Python dict. The main difference between gluon. Storage. Storage and dict is that they can access the elements of dict just like access attributes. The following request. vars is equivalent to request ['vars']. Another difference with dict is that when the accessed key does not exist, no exception is thrown, but none is returned. Request has the following attributes, some of which are also of the gluon. Storage. Storage Type:

 

* Request. Cookies: Cookie. simplecookie () object, which contains cookies in HTTP request. It is like a cookie dictionary.
* Request. env: A storage object that contains the environment variables passed to the Controller, including the HTTP header from the HTTP request and standard wsgi parameters. Environment variables are converted to lowercase letters, and dots are converted to underscores.
* Request. application: the name of the requested application (resolved from request. Env. path_info ).
* Request. Controller: name of the requested controller (resolved from request. Env. path_info ).
* Request. function: the name of the requested function (parsed from request. Env. path_info ).
* Request. Extension: the default extension is HTML. If the controller function returns a dictionary with no view specified, extension is used to determine which view to use to render the dictionary. (Parsed from request. Env. path_info ).
* Request. Folder: Application Program Directory.
* Request. Now: stores the timestamp of the current request, type: datetime. datetime.
* Request. ARGs: List of URL path components after the controller function, which is equivalent to request. Env. path_info ('/') [3:].
* Request. vars: The storage object contains the query variables of http get and http post.
* Request. get_vars: The storage object stores the http get query variable.
* Request. post_vars: The storage object stores the http post query variable.
* Request. Client: the IP address of the client.
* Request. body: the read-only file stream contains the HTTP Request body.
* Request. Ajax: true if the function is called through Ajax request.
* Request. CID: ID of the component generated by Ajax request.
* Request. wsgi: A hook allows you to call a third-party wsgi application in actions.

 

For requests http: // 127.0.0.1: 8000/examples/default/status/x/y/z? P = 1 & Q = 2. The request object is as follows:

Variable value
Request. Application Examples
Request. Controller default
Request. Function Index
Request. Extension html
Request. View status
Request. Folder applications/examples/
Request. ARGs ['x', 'y', 'z']
Request. vars <storage {'P': 1, 'q': 2}>
Request. get_vars <storage {'P': 1, 'q': 2}>
Request. post_vars <storage {}>
Request. CID none
Request. wsgi hook
Request. Env. content_length 0
Request. Env. content_type
Request. Env. http_accept text/XML, text/html;
Request. Env. http_accept_encoding gzip, deflate
Request. Env. http_accept_language en
Request. Env. http_cookie session_id_examples = 127.0.0.1.119725
Request. Env. http_host 127.0.0.1: 8000
Request. Env. http_max_forwards 10
Request. Env. http_referer http://web2py.com/
Request. Env. http_user_agent Mozilla/5.0.
Request. Env. http_via 1.1 web2py.com
Request. Env. http_x_forwarded_for 76.224.34.5
Request. Env. http_x_forwarded_host web2py.com
Request. Env. http_x_forwarded_server 127.0.0.1
Request. Env. path_info/examples/simple_examples/status
Request. Env. QUERY_STRING remote_addr: 127.0.0.1
Request. Env. request_method get
Request. Env. script_name
Request. Env. SERVER_NAME 127.0.0.1
Request. Env. server_port 8000
Request. Env. server_protocol HTTP/1.1
Request. Env. web2py_path/users/mdipierro/web2py
Request. Env. we2bpy_version version 1.83.1
Request. Env. web2py_runtime_gae (optional, defined only if Gae detected)
Request. Env. wsgi_errors <open file, mode 'W' at>
Request. Env. wsgi_input
Request. Env. wsgi_multiprocess false
Request. Env. wsgi_multithread true
Request. Env. wsgi_run_once false
Request. Env. wsgi_url_scheme HTTP
Request. Env. wsgi_version 10

The request. Env. Http _ * variable is parsed from the request HTTP header.

 

2) Response

Response is another storage instance that contains the following attributes:

Response. Body: contains the stringio object of the returned page body.
Response. Cookies: similar to request. Cookies (including cookies sent from the client to the server), but contain cookies returned from the server to the client.
Response. Download: A method is used to implement the controller function to allow file download.
Response. Files: List of CSS and JS files required by the page. These files will be automatically connected to the standard layout.html header. To include new CSS and JS files, you only need to add them to this list. Note the file sequence.
Response. Flash: optional parameter, which can be included in views. It is usually used to inform users of some changes.
Response. headers: the HTTP Response Header must be dict.
Response. Menu: optional parameter, which can be included in views. It is generally used to pass the navigation menu to views. It can be generated using menu helper.
Response. Meta: The storage object contains optional meta storage information, such as response. Meta. Author, response. Meta. description, and response. Meta. keywords. The content of the metavariable is automatically placed in the corresponding tag by web2py_ajax.html (included by views/layout.html.
Response. postprocessing: This is a function list, which is empty by default. These functions are used to filter the response object of the output of an action before the output is rendered.
Response. Render (view, vars): A method is used to call view in the Controller explicitly. View is the name of the View File. Vars is a dict passed to the view.
Response. seesion_file: The file stream contains the session.
Response. session_file_name: contains the name of the file saved by the session.
Response. session_id: the ID of the current session.
Response. session_id_name: name of the session cookie of the application.
Response. Status: HTTP status Code . 200 by default.
Response. Stream: When a controller returns it, the content of the web2py streaming file is sent to the client.
Response. Subtitle: optional parameter included in views. It should contain the subtitle of the page.
Response. Title: optional parameter included in views.
Response_vars: a variable that can only be accessed by the view. Action cannot be accessed. It contains the value that action returns to view.
Response. view: the name of the view template used to render the page. The default value is "% S/% S. % s" % (request. Controller, request. function, request. Extension ). If the preceding view template does not exist, use "Generic. % s" % (request. Extension ). Change the value to modify the View File of a specific action.
Response. XMLRPC: When a controller returns it, this function exposes this method through XML-RPC.
Response. JS: Contains JavaScript code.

 

3) session

Session is another storage instance. As long as the code is executed by the same user in the same session (the user has not deleted session cookies and the session has not expired), the session can be used. myvar = 'hello' stores the variable and uses a = session. myvar to use variables.

The session has two important methods:
Session. Forget (response). This method tells web2py not to save the session.
Session. Connect (request, response, DB, masterapp = none), DB is an open database connection. This method tells web2py to store the session to the database instead of the file system. Web2py creates a table:
DB. define_table ('web2py _ session ',
Field ('locked', 'boolean', default = false), field ('client _ ip '),
Field ('created _ datetime', 'datetime', default = now), field ('Modified _ datetime', 'datetime'), field ('unique _ key '), field ('session _ data', 'text '))
Cpickled sessions is stored in the session_data field.

4) Cookies
Web2py uses the python Cookies module to process cookies. Cookies sent from the browser are stored in request. Cookies. Contained in response. Cookies sent from the server to the client. You can use the following methods to set cookies:
Response. Cookies ['mycooker'] = 'somevalue'
Response. Cookies ['mycookies'] ['expires'] = 24*3600
Response. Cookies ['mycooker'] ['path'] = '/'

Use cookies as follows:
If request. Cookies. has_key ('mycookier'): value = request. Cookies ['mycookies']. Value

 

 

5) Cache

Cache is a global variable in the web2py execution environment. The cache has two attributes:
Cache. Ram: The application is buffered in the memory;
Cache. Disk: The application is buffered on the hard disk;

Example of buffering the controller function output to the memory:
@ Cache (request. Env. path_info, time_expire = 5, cache_model = cache. Ram)
Def cache_controller_in_ram ():
Import time
T = time. ctime ()
Return dict (time = T, link = a ('click me', _ href = request. url ))

Example of buffering the controller function output to the hard disk:
@ Cache (request. Env. path_info, time_expire = 5, cache_model = cache. Disk)
Def cache_controller_on_disk ():
Import time
T = time. ctime ()
Return dict (time = T, link = a ('click to reload', _ href = request. url ))
 
6) URL
The URL is used to generate the URL path. For example, URL ('A', 'C', 'F', argS = ['x', 'y'], vars = dict (Z = 'T ')) ing to/A/C/F/X/y? Z = T.

 

7) HTTP and redirect
HTTP is actually an exception class, such as 400 exception raise HTTP (400, "My message ")
Redirect ('HTTP: // www.web2py.com ') is used to switch to http://www.web2py.com /.

 

 

End 1

Related Article

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.