Python Network Programming Learning Note: WEBPY framework

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 quickly and easily. It emphasizes code reuse, multiple components can be conveniently in the form of "plug-in" to serve the entire framework, Django has many powerful third-party plug-ins, you can even easily develop their own toolkit. This makes Django highly extensible. It also emphasizes the principle of rapid development and dry (do not Repeat yourself). Webpy is small, simple, and practical, and can quickly complete a simple Web page. Here according to Webpy Cookbook Brief introduction of the WEBPY framework, more detailed see HTTP://WEBPY.ORG/COOKBOOK/INDEX.ZH-CN.

First, installation and development

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

The 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:

The code is 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, for example, the file name is mywebpy.py, you can use the following method to start the server:

The code is as follows:


Python mywebpy.py


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

Second, URL processing

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

The code is as follows:


URLs = (
'/', ' index '
)

The first part is a regular expression that matches the URL, such as/,/help/faq,/item/(\d+), and so on (\d+ will match the number). The parentheses indicate that the corresponding data is captured for later use. The second part is the class name that accepts the request, such as index, view, Welcomes.hello (the welcomes module's Hello Class), 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 means we want to url/(home) is handled by a class called Index. Now we need to create a application that lists these URLs.
App = Web.application (URLs, globals ())
This will tell 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 app, you will typically see the entire URL scheduling pattern defined in the tuple:

The 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 a more flexible URL path. 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 internally give the URL path plus and $, so/tasks/will not match/tasks/addnew. URL matching relies on "path", so it cannot be used, such as:/tasks/delete?name= (. +), or "query" after part, 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"
This block behind the list/is captured and then used as a parameter in Get or post:

The 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. Also note that the parameters of the URL query (the following) can be obtained using web.input ().

Third, Hello World

Now we need to write the index class. While 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 specifics do not matter, but it is important to understand that Web visitors are requesting the Web server to execute a proper function (like get, POST) based on the URL (like/,/foo?f=1). Get is used to request Web page 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 a form, such as a request to buy something. 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 get URLs can be indexed by search engines and accessed through search engines. Although most of the pages you want to be indexed, there are a handful of pages like order processing that you don't want to be indexed.
In our web.py code, we distinguish these two methods clearly:

The code is as follows:


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

When someone uses a GET request/, the Get function is called at any time by web.py.
Well, the limit is that we just need the last sentence to finish. The guild tells Web.py to start providing Web pages:

The 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 then fully listed as follows:

The 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, run after display:
http://0.0.0.0:8080/
Enter http://127.0.0.1:8080 in the browser and the Hello world! page will appear.

Four, template

To create a new directory for the template (named templates), create a new file in the directory that ends in. html, which is saved as index.html, as follows:

The code is as follows:


Hello, world!.

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

The code is as follows:


$def with (name)
$if Name:
I just wanted to say hello to $name.
$else:
Hello, world!.

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

Below the first line of code.py, add:

The code is as follows:


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

This will tell web.py to find the template in your template directory. then put index. Get changed to: Tell web.py to find the template file under your template directory. Modify Index. GET:

The code is as follows:


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

The complete code is:

The code is as follows:


##@ Xiao Wu Yi
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:

The code is as follows:


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

Access/will show Hello World, Access/?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 below:
'/(. *) ', ' Index '

Then modify the next GET:

The code is as follows:


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

The complete code is:

The code is as follows:


##@ Xiao Wu Yi
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 access Http://127.0.0.1:8080/TOM, it will show I just wanted to say hello to TOM. If you access http://127.0.0.1:8080/, it will show Hello, world!

V. Forms

1. Introduction

The form includes a textbox, Password, Textarea, Dropdown, Radio, Checkbox, button specific use and style as follows:

The 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 ', [' 2012-01-01 ', ' 20120101 ']),
validators = [Form. Validator ("Passwords didn ' t match.", lambda I:i.password = = I.password_again)]
)

appear in the page:

2. Input attributes
Such as:

The 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:

The code is as follows:


# #code. py
##@ Xiao Wu Yi
Import Web,os
From web Import form

Render = Web.template.render ("D:/webpy/templates") # #这里仿照http://webpy.org/form#example originally used relative path templates/, However, it is always possible to find a formtest error, so after searching, finding an 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:

The code is as follows:


$def with (form)


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



After filling out the form, if two times password is 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, use PSYCOPG2 for Postgres database.
Create a Database object: db = Web.database (dbn= ' postgres ', user= ' username ', pw= ' password ', db= ' dbname ')
2. Database Read
Example, there is a table testtable in the database test, the field is name, is modified in the code.py above, and if login succeeds, the contents of the test table are listed.

code.py

The code is as follows:


##@ Xiao Wu Yi
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

The code is as follows:


$def with (testtables)


      $for testtable in Testtables:
    • $testtable. Name


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

3. Database Write
If you add the user from the form table above to the TestTable table name field, it is simple to add a sentence in 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:

The code is as follows:


##@ Xiao Wu Yi
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 ()

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