A simple and straightforward Python web framework: web.py

Source: Internet
Author: User
Tags cdata db2 function definition html tags line web sql injection

from:https://www.oschina.net/question/5189_4306

web.py GitHub Address: https://github.com/webpy/webpy https://pypi.python.org/pypi/web.py

web.py Cookbook Simplified Chinese version: HTTP://WEBPY.ORG/COOKBOOK/INDEX.ZH-CN

web.py 0.3 Novice Guide: HTTP://WEBPY.ORG/DOCS/0.3/TUTORIAL.ZH-CN

WEBPY official website Document: http://webpy.org/

web.py 10 minutes Create a simple blog: http://blog.csdn.net/freeking101/article/details/53020728

A simple web.py forum: http://www.cnblogs.com/russellluo/p/3240564.html


web.py is a Python web framework that is simple and powerful. web.py is open, no matter what use is used is unrestricted. And rather compact, it should belong to a lightweight web framework. But this does not affect the strength of the web.py, and it is very simple and straightforward to use. In practice, web.py is more of an academic value, because you can see more of the bottom of Web apps, which you can't learn in today's "abstract" web framework: You can access web.py's official documentation if you want to learn more about web.py.

First feel the simplicity and strength of web.py:

Import Web

urls = (
    '/(. *) ', ' Hello '
)

app = Web.application (URLs, Globals ())

class Hello:
    def Get (self, name):
        i = web.input (Times=1)
        if not name: 
            name = "World" for
        C xrange (int (i.times)): 
            print ' Hello, ', name+ '!
        Return ' Hello, ' + name + '! '

if __name__ = = "__main__":
    App.run ()

The above is a complete Web application based on web.py. Save the above code as a file code.py and execute the Python code.py at the command line. Then open your browser, open the address: http://localhost:8080 or Http://localhost:8080/test No surprises (of course, first install the web.py, the following will be introduced), the browser will show "Hello, World "or" Hello, test ".



Run under Linux


This is one of the simplest Hello World Web apps. Is it simple? The next web.py will be described in more detail below.


1. Installation

Download web.py installation files, will download the file web.py decompression, into the Unpacked folder, executed under the command line: Python setup.py install, in Linux and other systems, need root permissions, can execute: sudo python setup.py install.


2. URL Handling

For a site, the organization of the URL is the most important part, because this is what the user sees, and it directly affects how the site works, such as Www.baidu.com, its URLs and even part of the Web interface. and web.py can construct a powerful URL in a simple way.

In each web.py application, you must import the Web module first:

Import Web

Now, we need to tell web.py how the URL is organized, let's start with a simple example:

URLs = (
  '/', ' Index '    )

In the example above, the first part is a regular expression that matches the URL, like/,/help/faq,/item/(\d+), and so on (\d+ will match the numbers). Parentheses indicate that the corresponding data is captured for later use. The second part is the class name that accepts the request, like index, view, Welcomes.hello (The Hello Class of the welcomes module), or Get_\1. \1 will be replaced with what the regular expression captures, and the rest of the captured content will be passed into your function. (' index ') is a class name, and a matching request will be sent to the past. This line means we have to url/(home) by a class called Index.

Now we need to create a application that enumerates these URLs.

App = Web.application (URLs, globals ())


Get and POST: Distinguishing

Now we need to write the index class. When most people browse the Web, they don't notice that browsers communicate with the World Wide Web via HTTP. The details of communications are less important, but to be clear, a user requests a Web server to complete a certain request (for example, get or post) through a URL (for example,/or/foo?f=1).

Get is the most common way to request a page. When we enter "harvard.edu" in the browser, it actually requests a get "/" to the Web server. Another common method is post, which is often used to submit a specific type of form, such as asking for something to buy. You can use post whenever you submit a request to do something (like using a credit card to process a transaction). This is critical, because the URL of get can transfer the submitted parameters in clear text. If you submit some important sensitive information, such as user name, password, it may be captured by someone else. Post, however, does not transmit the submitted information on the URL, and the post is submitted through the form.

In our web.py code. We clearly distinguish between the two approaches:

Class Index:
    def get (self):
        print "Hello, world!"

When a GET request is received, the above get method is called by web.py. Good. Now we just add the last line of code and let web.py start the Web application:

if __name__ = = "__main__":
    App.run ()

It tells web.py how to configure URLs and the global namespace in the file for the class you are looking for. And then for us to start the application above.

The contents of the entire code.py document are as follows:

Import Web

urls = (
    '/(. *) ', ' Hello '
)

app = Web.application (URLs, Globals ())

class Hello:
    def Get (self, name):
        i = web.input (Times=1)
        if not name: 
            name = "World" for
        C xrange (int (i.times)): 
            print ' Hello, ', name+ '!
        Return ' Hello, ' + name + '! '

if __name__ = = "__main__":
    App.run ()

In fact, the code for Web applications is just a few lines above, and this is a complete web.py application.


3. Start Service

At your command line, enter:

$ python code.py                               # Use default port 8080
or
$ python code.py 10000                         # change port to 10000

Your web.py application has already started the server. Access through the browser: http://localhost:8080/, you will see "Hello, World." “。


Modify Default Port

When starting the server, if you do not want to use the default port, you can use this command to specify the port number: python code.py 8888.


4. Debugging

Add a line Web.internalerror = Web.debugerror directly. As follows

If __name__== "__main__":
    web.internalerror = Web.debugerror
    app.run ()


5. Template

More about web.py templates can access HTTP://WEBPY.ORG/DOCS/0.3/TEMPLETOR.ZH-CN

Writing HTML code in Python is rather cumbersome, and embedding Python code in HTML is much more interesting. Luckily, web.py makes the process quite easy.

Note: Older versions of web.py are used with the Cheetah Templates template, and you can continue to use them, but the authorities are no longer providing support.

Create a new code.py python file. The contents are as follows:

Import Web


urls = (
    # '/(. *) ', ' Hello ',
    '/hello_1[/]? * ', ' hello_1 ',
    '/hello_2/(. *) ', ' hello_2 ',
)

app = Web.application (URLs, Globals ())
render= Web.template.render (' Templates ')

class Hello_1:

    def get (self): return        
        render.index_1 () 


class Hello_2:

    def get (self, name): Return        
        render.index_2 ("Lisa") 
        
if __name__ = = "__main__":
    App.run ()


Creating Templates

Here, we first create a new directory (for example, templates) in the same level of project code.py to centrally store and organize template files for easy management. Then, under the templates, create a new HTML file (for example, "index.html"). Here is a new two HTML file. Index_1.html and index_2.html


The contents of the index_1.html file are as follows:

<em>hello</em> a world!.

This is one of the simplest HTML page codes.

The contents of the index_2.html file are as follows:

$def with (name)

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >

Note the indentation of the above code.

As you can see, the template above looks similar to this Python file, starting with the DEF with statement, but adding "$" before the keyword.

Note : Variables within the template, if they contain HTML tags, refer to variables in $, and HTML tags are displayed only as plain text. To create an effect on HTML markup, you can use the $: reference variable.


Working with Templates

Now, go back to the code.py file and add on the next line of the import Web:

Render = Web.template.render (' templates/')

This tells web.py where to search for the template directory. Tip: You can add cache = False to the render call to overload the template each time you access the page.

Then modify the class that uses this template, and modify the class Hello_1 and class hello_2 here

Class Hello_1:

    def get (self): return
        render.index_1 () 


class Hello_2:

    def get (self, name):
        # NAME = "Lisa."
        

The "Index_1" and "Index_2" above are the names of the templates, and "Lisa" is the parameter that passes the past.

Modify the URLs at the same time:

URLs = (
    # '/(. *) ', ' Hello ',
    '/hello_1[/]? * ', ' hello_1 ',
    '/hello_2/(. *) ', ' hello_2 ',
)

The above "/(. *)" is a regular expression. Inside the brackets are the parameters to be passed. Then modify the Get method as follows:

def get (self,name):
    print render.index_2 (name)

The Hello_1 page calls the Hello_1 class and uses the index_1.html template. When you open http://localhost:8080/hello_1, the page prints out the words Hello, world.

The hello_2/page calls the Hello_2 class, uses the Index_2.html template, opens the http://localhost:8080/hello_2/, and the page prints out the words Hello, Lisa.



In addition, there are two ways to use a template to specify template files directly using Frender. The last two lines of the Get function are changed to

  Render=web.template.frender ("templates/index.html") return
  render ("Lisa")
Write the template file directly in your code. The last two lines of get are changed to
  Template = "$def with (name) \nhello $name"
  render = web.template.Template (template) return
  render ("Lisa")


Template meaning

Now explain the meaning of this index.html template:

$def with (name)

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >

The first line in index.html $def with (name) to indicate that this template accepts a parameter named name, which is Lisa in the return Render.index ("Lisa") in the Index class.

Render=web.template.render ("templates") means creating a template object, which is stored in the Templates directory, and can then be accessed using the Render object you create.

For example, the index.html in the Templates directory is to use Render.index to express (in fact, matching the search for index.* files, the first match is considered to be the corresponding template file), if the templates under a directory of A, A directory under a pagea.html, then access to the PageA template will be in the form of Render.a.pagea.


Page parameters

The page can receive more than one parameter, or not, if you do not need parameters, you do not need to $def with (name) Such code, delete this sentence, while modifying the template on the name variable reference, modify the last sentence of the index class return Render.index ( ) is OK.

If you have parameters, the first line of code for the template must be this $def with (...), and you can have more than one parameter, such as $def with (Gname, fname).

Change the line below the template to Hi, $gname $fname.

At the same time, the index class get returns with the corresponding two parameters return Render.index ("Lisa", "Hayes").

In this way, the page finally displays the words "Hi, Lisa Hayes" printed out.

In addition, the template accepts this parameter can also be a tuple, such as the following: Return Render.index ("Lisa", "Hayes")

Parameter data can be accessed as a tuple in a template as follows: Hi, $name [0] $name [1]


Template syntax

Template syntax is basically consistent with the Python syntax, and the main differences can be seen in the above code, to use the $ symbol to indicate that this is not text but template code. That is, whenever you use program code, objects, you must use $ to distinguish it from HTML code and page display text.


Object Assignment

Assigning a value to an object requires a blank between $ and the object name, such as assigning an Apple code to $ vara = "Apple" for a string object named Vara.
In addition, an object assignment statement must be exclusive to one line, and other code before or after it will have an error.


Object reference

Refer to objects directly using the form of $+ object names, such as $vara.
You can also explicitly group objects with {} or () when referencing an object, such as $ (VARA) s to represent apples, and if there are no parentheses, the program will $varas as a whole and become a reference to the Varas object and an error occurs. Also, define two numeric objects as follows:

$varb = 1
$varc = 2

Then you want to calculate the two-value and, if the $varb+ $varc form, the page will only get 1+2 instead of 3, then you need to put two objects in parentheses, such as $ (VARB+VARC) in the form of the correct answer 3.


Comments

Single-line annotations are supported in the template to $ #符号开始到行末都是注释内容.
$ #This is comment
Note You can have other content before, but you cannot have assignment code.
The following code is correct: Hi $ #This is comment
But the following error occurs: $ vara = "Apple" $ #This is comment


Print $ symbol

Because the $ symbol has a special purpose in the template, you need to escape when you output $ on the page, and a $ symbol is printed on the page with a continuous two $ notation.

Can you lend me $?


Control code (loop, conditional judgment)

The template supports for, while, if, elif, or else, using the same as in Python, except that the control line of code starts with $ (including the break and Continue commands), and the object in the line of code starts with the $ symbol in front of it, as well as the indent rules, such as:

For loop:

$def with (touser,fromuser,createtime,articlecnt,articles)
<xml>
    <tousername><![ cdata[$toUser]]></tousername>
    <fromusername><![ cdata[$fromUser]]></fromusername>
    <CreateTime> $createTime </CreateTime>
    < msgtype><! [cdata[news]]></msgtype>
    <ArticleCount> $articleCnt </ArticleCount>
    <articles >
        $for A in articles:
            <item>
                <title><![ cdata[$a [' title ']]]></title>
                <description><![ cdata[$a [' desc ']]]></description>
                <picurl><![ cdata[$a [' Picurl ']]]></picurl>
                <url><![ cdata[$a [' url ']]]></url>
            </item>
    </Articles>
</xml>

If else is judged:

$if times > Max:
    stop! In the name of love.
$else:
    Keep on, and can do it.

In the For loop, there is a set of built-in variables that can be used conveniently, as follows: Loop.index: Loop count (1-start) loop.index0: Loop count (0-start) Loop.first: True if the first loop Loop.last: True if it is the last loop loop.odd: True Loop.even if it is an odd number of times: true if it is an even number of cycles loop.parity: If the number of loops is "odd", otherwise " Even "Loop.parent: Outer loop object of this loop

$for A in ["a", "B", "C", "D"]: 
    $loop. Index, $loop. index0, $loop. I, $loop. Last, $loop. Odd, $loop. even,$ Loop.parity<br/>

Will print on the page:

1,0,true,false,true,false,odd
2,1,false,false,false,true,even
3,2,false,false,true,false,odd
4, 3, False,true,false,true,even


Function-$def

The function definition is similar to that in Python, with Def, but also in front of $, and the code should also pay attention to the use and indentation of $:

$def Hello (name= ""):
Hello $name!
function calls are also in the form of a $ plus function name:
$hello ("Lisa")
Of course, when you define a function, you can also mix it with HTML code:
$def Hello (name= ""):
<strong/>hello $name!</strong>
But the call needs to be preceded by the $: prefix for the function name, otherwise the HTML code will print to the page as plain text.
$:hello ("Lisa")


Output program code-$code block

If you want to enter a piece of Python code in the template and don't want to be bothered by $, you can use a $code block.

The output of a piece of code on the page rather than being understood by the system as a template program code requires the use of the $code command, such as writing the following paragraph in the template file:

$code:
    x=10
    def print_num (num): return
    "num is%d"% num

Then add the following code:

$print _num (x)
<br/>
$x

The Print_num function defined in the $code block is used to output one row on the page with an X variable: num is 10

Then the next line references the x variable directly, outputting the number 10 directly on the page.


$var

$var command can define variables in the template, and you can access the variables of this definition when referencing this template object elsewhere.
For example, we can add the following line to the index.html: $var Vara:this is Vara
Indicates that a variable named Vara is defined, and the value of the variable is the string this is Vara.
Change the Get function of index to:

def get (self):
    render=web.template.render ("Templates") return
    Render.index ("Lisa", "Hayes"). Vara

So the result is displayed on the page, which is the phrase this is Vara. It is important to note that this variable is a string, even if the following defines the variable: $var vara:0

Vara is also not a number 0, if the Get function is finally changed to: Return Render.index ("Lisa", "Hayes"). vara+1

can cause a program error. If you want to get the desired result of 1, you need the following form code: Return int (Render.index ("Lisa", "Hayes"). Vara) +1


Builtins and Globals

In a template, users can directly use Python's built-in functions and variables, and write function variables including range, Min, Max, and True and false. In addition, if you want to use other non-built-in features in your template, you need a little special action. To explicitly specify the required functional functions when creating a render.

Import Web
import markdown

globals = {' markdown ': Markdown.markdown}
render =web.template.render (' Templates ', globals=globals)

In this way, you can use $markdown to refer to Markdown.markdown in the template. Similarly, you can use this method to disable Builtins

# Disable all builtins
render = Web.template.render (' Templates ', builtins={})


Template Reuse

When multiple pages have the same structure frame, it is more troublesome to maintain a single template for each page, web.py provides a simple solution.
Use the base parameter when creating render:

Render=web.template.render ("Templates", base= "layout") return
Render.index ("Lisa", "Hayes")

This layout represents a generic template framework for the layout.html template under Templates. So we have to create a new layout.html file in the Templates directory, and write the following code:

$def with (content)
    <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
    
As you can see, this template file must have a parameter content. Then modify the index.html, leaving only the following code, others delete:
$def with (Gname, fname)
    Hi, $ (gname) $ (fname)

Run the program, Print hi on the page, Lisa Hayes, look at the code and see that the final code is the result of merging index.html and layout.html, and that the content in index.html is embedded in layout.html, $:content.
The var variable defined in index.html can also be referenced in the layout.html template, which gives the program more flexibility, for example, when we want different pages to have different title when using the same layout template, you can define one of the following var variables in the template that uses layout: $var Title:this is index.html
Then modify the title in layout.html to:<title> $content .title</title>
In this way, the title that is displayed on the browser when accessing index.html is the This is index.html, not the original layout.


Using the Python code module in the template

In the default state, in the template can not directly invoke other Python code module files in the program, you must do some extra action.
First, we create a new module called module1.py, which writes a function inside:

def hello_from_m1 (name= ""): Return
    "Hello%s, this is Module1"% name

Import Module1:import Module1 in main.py

And the code to create the render in the Get function is:

def get (self):
    render=web.template.render ("Templates", base= "layout", globals={"M1": Module1})
    return Render.index ("Lisa")

The globals parameter is passed a dictionary in which the key represents the name of the module used in the template, and the value part is the real name of the module or object to be used in the module.
Finally, you can use $M1 to refer to this module in the template that you want to use this module. For example, add the following line of code to index.html: $m 1.hello_from_m1 (Gname)
The HELLO_FROM_M1 function in Module1 is invoked and printed on the page: Hello Lisa, this is Module1


Using jquery in the web.py template

In jquery, $ is also a keyword, so if you use jquery in a template that conflicts, you just need to use $ to escape, for example:

<script type= "Text/javascript" >
$ (document). Ready (function ()
{
    alert ("It works.")
; </script>


6. The database


web.py more about the operation of the database: HTTP://WEBPY.ORG/COOKBOOK/INDEX.ZH-CN

Note : Before you start connecting to the database, please install the correct database driver first. such as MySQLdb, PSYCOPG2. If you need to try the connection pool (database pool) feature, you have to install the dbutils. These modules can be installed via Easy_install or PIP.

To connect to a database:

Import Web
db = web.database (dbn= ' postgres ', db= ' MyData ', user= ' dbuser ', pw= ')

Manipulating Database samples

Select query # query Table entries = Db.select (' mytable ') # WHERE Condition MyVar = Dict (name= "Bob") results = db.select (' mytable ', MYV AR, where= "name = $name") results = db.select (' mytable ', where= "id>100") # query specific column results = Db.select (' mytable ', what= ' I D,name ") # ORDER BY results = Db.select (' mytable ', order= ' post_date DESC ') # Group results = db.select (' mytable ', group=" C Olor ") # Limit results = Db.select (' mytable ', limit=10) # Offset results = db.select (' mytable ', offset=10) update db.update ( ' MyTable ', where= "id = ten", value1 = "foo") Delete db.delete (' mytable ', where= "id=10") complex query # count results = db.query ("SE Lect COUNT (*) as total_users from users) Print Results[0].total_users # Join results = db.query (' select * from entries JO In users where entries.author_id = Users.id ") # prevents SQL injection from being able to do so results = Db.query (" SELECT * from Users where id= $id ", vars={  ' ID ': 10} ' multiple database operations (web.py greater than 0.3) DB1 = web.database (dbn= ' MySQL ', db= ' dbname1 ', user= ' foo ') DB2 = web.database (dbn= ' MySQL '), db= ' dbname2 ', user= ' foo') Print db1.select (' foo ', where= ' id=1 ') print db2.select (' Bar ', where= ' id=5 ') transaction T = db.transaction () try:db.inser T (' person ', name= ' foo ') db.insert (' person ', name= ' bar ') Except:t.rollback () Raise Else:t.commit () # PYT Hon 2.5+ can be used with the from __future__ import with_statement with Db.transaction ():
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.