Python network programming learning notes (10): webpy framework

Source: Internet
Author: User

Django and webpy are both python web development frameworks. The main purpose of Django is to develop a database-driven website easily and quickly. It emphasizes code reuse. Multiple components can easily serve the entire framework in the form of plug-ins. Django has many powerful third-party plug-ins, you can even develop your own toolkit easily. This makes Django highly scalable. It also emphasizes the fast development and DRY (Do Not Repeat Yourself) principles. Webpy is small, simple, and practical. It can quickly complete simple web pages. Here we will briefly introduce the webpy framework based on webpy Cookbook. For more details, see http://webpy.org/cookbook/index.zh-cn.

I. Installation and development

Web. py: http://webpy.org/static/web.py-0.33.tar.gz. Decompress and copy the web folder to your application directory. Or, to make all applications usable, run:

Copy codeThe Code is as follows:
Python setup. py install

Note: On Some unix-like systems, you may need to switch to the root user or run:

Copy codeThe Code is as follows:
Sudo python setup. py install

You can also directly put the WEB folder in site-packages.
Web. py has a built-in web server. After the code is written, save it. For example, if the file name is mywebpy. py, you can start the server using the following method:

Copy codeThe Code is as follows:
Python mywebpy. py

Open your browser and enter http: // localhost: 8080/to view the page. To create another port, use python mywebpy. py 1234.

Ii. URL Processing

The most important part of any website is its URL structure. Your URL is not only visible to visitors but also accessible to friends. It also specifies the mental model for running your website. In some popular websites like del. icio. us, URLs are even part of the UI. Web. py makes such powerful URLs possible.

Copy codeThe Code is as follows:
Urls = (
'/', 'Index'
)

The first part is the regular expression that matches the URL, such as/,/help/faq,/item/(\ d +) and so on (\ d + will match the number ). Parentheses indicate capturing the corresponding data for later use. The second part is the name of the class that receives the request, such as index, view, welcomes. hello (hello class of the welcomes module), or get _ \ 1. \ 1 will be replaced by the content captured by the regular expression, and the rest of the captured content will be passed to your function. This line indicates that the URL/(homepage) is processed by an index class. Now we need to create an application to list these URLs.
App = web. application (urls, globals ())
This will tell web. py to create an application based on the URL list we just submitted. This application will find the corresponding class in the global namespace of this file.
Generally, at the top of each application, you usually see that the entire URL scheduling mode is defined in the tuples:

Copy codeThe Code is 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, matching is based on the URL path. For example, the following URL:
Http: // localhost/myapp/greetings/hello? Name = Joe
The URL path is/myapp/greetings/hello. Web. py adds the URL path and $ internally, so that/tasks/does not match/tasks/addnew. URL matching depends on "path", so it cannot be used like this, for example:/tasks/delete? Name = (. + ),? The following part indicates "query" and will not be matched. For more details about the URL component, visit web. ctx.

You can capture URL parameters and use them in the processing class:
/Users/list/(. +), "list_users"
The block following list/will be captured and used as a parameter in GET or POST:

Copy codeThe Code is as follows:
Class list_users:
Def GET (self, name ):
Return "Listing info about user: {0}". format (name)

You can define more parameters as needed. Pay attention to the URL query parameters (? Can also be obtained using web. input.

3. hello world

Now we need to write the index class. Although most people will only look at it, they will not notice that your browser is using the HTTP language used to communicate with the World Wide Web. The specific details are not important, but we need to understand that the web visitor requests the web server according to the URL (like/,/foo? F = 1) execute the basic idea of an appropriate function (such as GET and POST. GET is used to request webpage text. When you enter harvard.edu in the browser, it will directly access the Harvard web server and go to GET /. POST is often used to submit forms, 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 get url can be indexed by the search engine and accessed by the search engine. Although you want to be indexed for most pages, you do not want to be indexed for a few pages similar to order processing.
In our web. py code, we clearly distinguish the two methods:

Copy codeThe Code is as follows:
Class index:
Def GET (self ):
Return "Hello, world! "

When a GET request/is used, the GET function is called by web. py at any time.
Well, we only need to finish writing the last sentence. This will tell web. py to start providing web pages:

Copy codeThe Code is as follows:
If _ name _ = "_ main _": app. run ()

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

Copy codeThe Code is 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. After running, it is displayed:
Http: // 0.0.0.0: 8080/
Enter http: // 127.0.0.1: 8080 in the browser to display hello world! Page.

Iv. Template

Create a directory (named templates) for the template, and create a file ending with. html under the directory. The file is index.html and the content is as follows:

Copy codeThe Code is as follows:
<Em> Hello </em>, world!

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

Copy codeThe Code is as follows:
$ Def with (name)
$ If name:
I just wanted to say <em> hello </em> to $ name.
$ Else:
<Em> Hello </em>, world!

As shown above, the template looks like a python file, except for the def with at the top (meaning that the slave template will be taken after this) and always located before the code snippet $. Currently, template. py first requests $ def from the first line of the template file. Of course, you should note that web. py will escape any variables used, so when you set the name value to an HTML segment, it will be escaped and displayed as plain text. If you want to disable this option, you can write $: name instead of $ name.

Add the following under the first line of code. py:

Copy codeThe Code is as follows:
Render = web. template. render ('templates /')

This will tell web. py to search for the template in your template directory. Then change index. GET to: Tell web. py to search for the template file in your template directory. Modify index. GET:

Copy codeThe Code is as follows:
Name = 'bob'
Return render. index (name)

Complete code:

Copy codeThe Code is as follows:
##@ Xiao Wuyi
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 ()

The access site will display I just wanted to say hello to Bob.

However, if we want the user to enter his/her name, as follows:

Copy codeThe Code is as follows:
I = web. input (name = None)
Return render. index (I. name)

Access/will display hello world, access /? Name = Joe will display I just wanted to say hello to Joe.
? It looks bad. Modify the URL Configuration:
'/(. *)', 'Index'

Then modify GET:

Copy codeThe Code is as follows:
Def GET (self, name ):
Return render. index (name)

Complete code:

Copy codeThe Code is as follows:
##@ Xiao Wuyi
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 ()

Access http: // 127.0.0.1: 8080/TOM. It will display I just wanted to say hello to TOM. if you access http: // 127.0.0.1: 8080/, it will display Hello, world!

V. Forms

1. Introduction

The form includes Textbox, Password, Textarea, Dropdown, Radio, Checkbox, And Button. The specific usage and style are as follows:

Copy codeThe Code is 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', ['2017-01-01 ', '20180101']),
Validators = [form. Validator ("Passwords didn't match.", lambda I: I. password = I. password_again)]
)

Displayed on the page:

2. Input attributes
For example:

Copy codeThe Code is as follows:
Form. textbox ("firstname ",
Form. notnull, # put validators first followed by optional attributes
Class _ = "textEntry", # gives a class name to the text box -- note 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 codeThe Code is as follows:
# Code. py
##@ Xiao Wuyi
Import web, OS
From web import form

Render = web. template. render ("d:/webpy/templates") # This is the example.

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', ['2017-01-01 ', '20180101']),
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/templatesfolder and save the formtest.html file. The file code is as follows:

Copy codeThe Code is 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 browse the page in the browser as follows:



After entering the form, if the two passwords are the same, the HAHA !, Otherwise, Try again, Passwords didn 'tmatch: is displayed :.

Vi. Database

1. Database Connection
Make sure that the appropriate database access library is installed before you start using the database. For example, for MySQL databases, use MySQLdb and for ipvs databases use psycopg2.
Create a database object: db = web. database (dbn = 'domains', user = 'username', pw = 'Password', db = 'dbname ')
2. Database reading
For example, there is a table testtable in the database test with the field name, which is modified in code. py above. If login is successful, the content in the test table is listed.

Code. py

Copy codeThe Code is as follows:
##@ Xiao Wuyi
Import web, OS
From web import form
Db = web. database (dbn = 'users', user = 'users' s', 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', ['2017-01-01 ', '20180101']),
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 ()

Registry.index.html

Copy codeThe Code is as follows:
$ Def with (testtables)
<Ul>
$ For testtable in testtables:
<Li id = "t $ testtable. name"> $ testtable. name </li>
</Ul>

When login is correct, the name field values in the testtable table are listed.

3. Database writing
For example, adding the user in the FORM table above to the name field of the testtable table is very simple. You only need to add n = db in the code above. insert ('voa ', filename = f ['username']. value ).
After the code. py is modified, the username is added to the testtable table after the form is entered correctly. The complete code is as follows:

Copy codeThe Code is as follows:
##@ Xiao Wuyi
Import web, OS
From web import form
Db = web. database (dbn = 'users', user = 'users' s', 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', ['2017-01-01 ', '20180101']),
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.