Python Network Programming Learning Notes (TEN): Webpy framework _python

Source: Internet
Author: User
Tags postgres database

Both Django and webpy are Python's web development frameworks. The main purpose of Django is to develop a database-driven Web site easily and quickly. It emphasizes code reuse, multiple components can be conveniently in the form of "plug-in" service to the entire framework, Django has many powerful third-party plug-ins, you can even easily develop your own toolkit. This allows Django to be highly scalable. It also emphasizes the rapid development and dry (do not Repeat yourself) principles. Webpy small, simple, practical, can quickly complete a simple Web page. Here according to Webpy Cookbook briefly introduce the WEBPY framework, more detailed see HTTP://WEBPY.ORG/COOKBOOK/INDEX.ZH-CN.

I. Installation and development

web.py Download Address: http://webpy.org/static/web.py-0.33.tar.gz. Unzip and copy the Web folders to your application directory. Or, in order for all applications to be available, run:

Copy Code code as follows:

Python setup.py Install

Note: On some Unix-like systems you may need to switch to root or run:

Copy Code code as follows:

sudo python setup.py install

You can also directly put the Web folder inside Site-packages.
web.py built-in Web server, after the code is written, save it, such as file name mywebpy.py, you can use the following method to start the server:

Copy Code code as follows:

Python mywebpy.py

Open your browser and enter http://localhost:8080/to view the page. To develop additional ports, use Python mywebpy.py 1234.

Second, URL processing

The most important part of any website is its URL structure. Your URL is not just for visitors to see and send to friends. It also provides a mental model of how your site works. In some popular websites like del.icio.us, URLs are even part of the UI. Web.py makes this kind of powerful URLs possible.

Copy Code code as follows:

URLs = (
'/', ' index '
)

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. 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 ())
This tells Web.py to create a application based on the list of URLs we just submitted. This application will find the corresponding class in the global namespace of this file.
In general, at the top of each application, you will typically see the entire URL scheduling pattern defined in a tuple:

Copy Code code as follows:

URLs = (
"/tasks/", "signin",
"/tasks/list", "listing",
"/tasks/post", "POST",
"/tasks/chgpass", "Chgpass",
"/tasks/act", "actions",
"/tasks/logout", "logout",
"/tasks/signup", "signup"
)

The format of these tuples is: URL path, processing class.

You can use powerful regular expressions to design more flexible URL paths. For example/(TEST1|TEST2) can capture/test1 or/test2. To understand the key here, the match is based on the URL path. For example, the following URL:
Http://localhost/myapp/greetings/hello?name=Joe
The path to this URL is/myapp/greetings/hello. Web.py will add and $ to the URL path internally so that/tasks/does not match/tasks/addnew. URL matching relies on "path", so it cannot be used like this:/tasks/delete?name= (. +), and then part of the representation is "query" and will not be matched. For more details on the URL component, please visit web.ctx.

You can capture the parameters of the URL and then use it in the processing class:
/users/list/(. +), "List_users"
The block behind the list/is captured and then used as a parameter to get or post:

Copy Code code as follows:

Class List_users:
def get (self, name):
Return "Listing info about User: {0}". Format (name)

You can define more parameters as needed. Also note that the parameters of the URL query (? later) can be obtained by Web.input ().

Third, Hello World

Now we need to write the index class. Although most people will only look at it, you will not notice that your browser is using the HTTP language used to communicate with the World Wide Web. Specific details are not important, but understand the basic idea of a Web visitor requesting a Web server to perform an appropriate function (like get, POST) based on a URL (like/,/foo?f=1). Get is used to request Web page text. When you enter harvard.edu in the browser, it accesses the Harvard Web server directly and goes to get/. Post is often used to submit 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 key because the URL of get can be indexed by the search engine and accessed through the search engine. Although most pages you want to be indexed, a few of the pages like order processing you don't want to be indexed.
In our web.py code, we distinguish between these two methods:

Copy Code code as follows:

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

This get function is invoked at any time by the web.py when someone is asking for it.
All right, all we have to do is limit the last sentence. This line tells Web.py to start providing Web pages:

Copy Code code as follows:

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

This will tell web.py for us to start the application we wrote above.
The above code is then listed as follows:

Copy Code code as follows:

Import Web
URLs = (
'/', ' index '
)

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

if __name__ = = "__main__":
App = Web.application (URLs, globals ())
App.run ()

Save As hello.py and show after run:
http://0.0.0.0:8080/
When you enter http://127.0.0.1:8080 in the browser, the Hello world! page appears.

Four, template

Create a new directory (named templates) for the template, and create a new file in this directory that ends with. html, which is stored as index.html, as follows:

Copy Code code as follows:

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

You can also use the web.py template support code in a template:

Copy Code code as follows:

$def with (name)
$if Name:
I just wanted to the say <em>hello</em> to $name.
$else:
<em>hello</em> a world!.

As above, the template looks just like a python file, except for the top Def with (representing the value that will be taken from the template) and the $ that always precedes the code snippet. Currently, template.py first requests the first line $def of the template file. Of course, you should be aware that web.py will escape any used variables, so when you set the value of name to be a piece of HTML, it is escaped and displayed as plain text. If you want to turn off this option, you can write $:name instead of $name.

Add below the first line of code.py:

Copy Code code as follows:

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

This tells web.py to go to your template directory to find the template. And then put the index. Get change: Tell web.py to look for template files in your template directory. Modify Index. Get:

Copy Code code as follows:

name = ' Bob '
return Render.index (name)

The complete code is:

Copy Code code as follows:

##@ Small Five Righteousness
Import Web
Render = Web.template.render (' templates/')
URLs = (
'/', ' index '
)

Class Index:
def get (self):
Name= ' Bob '
return Render.index (name)
#return "Hello, world!"

if __name__ = = "__main__":
App = Web.application (URLs, globals ())
App.run ()

Visit the site it will show I just wanted to say hello to Bob.

But if we want the user to enter his own name, as follows:

Copy Code code as follows:

i = Web.input (Name=none)
Return Render.index (I.name)

Visit/will show Hello World, visit/?name=joe will show I just wanted to say hello to Joe.
The back of the URL? It doesn't look good. Modify the URL configuration:
'/(. *) ', ' Index '

Then modify the Get:

Copy Code code as follows:

def get (self, name):
return Render.index (name)

The complete code is:

Copy Code code as follows:

##@ Small Five Righteousness
Import Web
Render = Web.template.render (' templates/')
URLs = (
'/(. *) ', ' Index '
)

Class Index:
def get (Self,name):
I=web.input (Name=none)
return Render.index (name)
#return "Hello, world!"

if __name__ = = "__main__":
App = Web.application (URLs, globals ())
App.run ()

Now visit Http://127.0.0.1:8080/TOM, it will show I just wanted to say hello to TOM. If you visit http://127.0.0.1:8080/, it will show Hello, world!

Five, form

1. Introduction

The form includes textbox, Password, Textarea, Dropdown, Radio, Checkbox, button, and the following styles are used:

Copy Code code as follows:

Login = form. Form (
Form. Textbox (' username '),
Form. Password (' Password '),
Form. Password (' Password_again '),

Form. Button (' Login '),
Form. Checkbox (' YES '),
Form. Checkbox (' NO '),
Form. Textarea (' Moe '),
Form. Dropdown (' SEX ', [' Man ', ' woman ']),
Form. Radio (' time ', [' 2012-01-01 ', ' 20120101 ']),
validators = [Form. Validator ("Passwords didn ' t match.", lambda I:i.password = = I.password_again)]
)

appear on the page:

2. Input Properties
Such as:

Copy Code code as follows:

Form.textbox ("FirstName",
Form.notnull, #put validators followed by optional attributes
Class_= "Textentry", #gives a class name to the text box-the underscore
Pre= "Pre", #directly before the text box
Post= "POST", #directly after the text box
description= ' Please enter your name ', #describes field, defaults to form name ("FirstName")
Value= "Bob", #default value
Id= "NameID", #specify the ID
)

3. Example:

Copy Code code as follows:

# #code. py
##@ Small Five Righteousness
Import Web,os
From web Import form

Render = Web.template.render ("D:/webpy/templates") # #这里仿照http://webpy.org/form#example initially used relative path templates/, However, it always occurs that no formtest error is found, and after searching, it is found that replacing the absolute path can solve the problem.

URLs = (
'/', ' Index ',

)
App = Web.application (URLs, globals ())
Login = form. Form (
Form. Textbox (' username '),
Form. Password (' Password '),
Form. Password (' Password_again '),

Form. Button (' Login '),
Form. Checkbox (' YES '),
Form. Checkbox (' NO '),
Form. Textarea (' Moe '),
Form. Dropdown (' SEX ', [' Man ', ' woman ']),
Form. Radio (' time ', [' 2012-01-01 ', ' 20120101 ']),
validators = [Form. Validator ("Passwords didn ' t match.", lambda I:i.password = = I.password_again)]

)


Class Index:

def get (self):
F=login ()
Return Render.formtest (f)
def POST (self):
F=login ()
If not f.validates ():
Return Render.formtest (f)

Else
Return "haha!"

if __name__ = = "__main__":
Web.internalerror = Web.debugerror

App.run ()

D:/webpy/templates folder to store the formtest.html file, the file code is as follows:

Copy Code code as follows:

$def with (form)

<form name= "main" method= "POST" >
$if not form.valid: <p class= "error" >try again,passwords didn ' t match:</p>
$:form.render ()
<input type= "Submit"/> </form>

Run code.py, and then browse through the page in the browser as follows:



After filling out the form, if two times password the same, then the haha! is displayed, otherwise the try again is displayed, passwords didn ' t match:.

VI. Database

1, the database connection
Before you start using the database, make sure that you have the appropriate database access library installed. For example, for MySQL database, use MYSQLDB, for Postgres database use PSYCOPG2.
Create a Database object: db = Web.database (dbn= ' postgres ', user= ' username ', pw= ' password ', db= ' dbname ')
2. Database Reading
For example, in database test, there is a table testtable, the field is name, modified in the code.py above, and if login succeeds, the contents of the test table are listed.

code.py

Copy Code code as follows:

##@ Small Five Righteousness
Import Web,os
From web Import form
db = Web.database (dbn= ' postgres ', user= ' postgres ', pw= ' password ', db= ' test ')
Render = Web.template.render ("D:/webpy/templates")
URLs = (
'/', ' Index ',

)
App = Web.application (URLs, globals ())
Login = form. Form (
Form. Textbox (' username '),
Form. Password (' Password '),
Form. Password (' Password_again '),
Form. Button (' Login '),
Form. Checkbox (' YES '),
Form. Checkbox (' NO '),
Form. Textarea (' Moe '),
Form. Dropdown (' SEX ', [' Man ', ' woman ']),
Form. Radio (' time ', [' 2012-01-01 ', ' 20120101 ']),
validators = [Form. Validator ("Passwords didn ' t match.", lambda I:i.password = = I.password_again)]

)

Class Index:

def get (self):
F=login ()
Return Render.formtest (f)
def POST (self):
F=login ()
If not f.validates ():
Return Render.formtest (f)

Else
Testtables = Db.select (' testtable ')
Return Render.index (Testtables)


if __name__ = = "__main__":
Web.internalerror = Web.debugerror

App.run ()

# #index. html

Copy Code code as follows:

$def with (testtables)
<ul>
$for testtable in Testtables:
<li id= "T$testtable.name" > $testtable .name</li>
</ul>

When login is correct, the value of the Name field in the TestTable table is listed.

3. Database Write
If you add user in the form table above to the TestTable table name field, simply add a sentence to the code above: N=db.insert (' VOA ', filename=f[' username '].value).
Now, after modifying the code.py code, when the form is filled in correctly, the username is added to the TestTable table with the complete code as follows:

Copy Code code as follows:

##@ Small Five Righteousness
Import Web,os
From web Import form
db = Web.database (dbn= ' postgres ', user= ' postgres ', pw= ' password ', db= ' bbstime ')
Render = Web.template.render ("D:/webpy/templates")
URLs = (
'/', ' Index ',

)
App = Web.application (URLs, globals ())
Login = form. Form (
Form. Textbox (' username '),
Form. Password (' Password '),
Form. Password (' Password_again '),
Form. Button (' Login '),
Form. Checkbox (' YES '),
Form. Checkbox (' NO '),
Form. Textarea (' Moe '),
Form. Dropdown (' SEX ', [' Man ', ' woman ']),
Form. Radio (' time ', [' 2012-01-01 ', ' 20120101 ']),
validators = [Form. Validator ("Passwords didn ' t match.", lambda I:i.password = = I.password_again)]

)

Class Index:

def get (self):
F=login ()
Return Render.formtest (f)
def POST (self):
F=login ()
If not f.validates ():
Return Render.formtest (f)

Else
N=db.insert (' VOA ', filename=f[' username '].value)
Voas = Db.select (' VOA ')
Return Render.index (Voas)
if __name__ = = "__main__":
Web.internalerror = Web.debugerror
App.run ()

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.