Of 10: webpy framework

  • 2020-04-02 13:43:23
  • OfStack

Django and webpy are both python's web development frameworks. The main purpose of Django is to make it easy and fast to develop database-driven websites. It emphasizes code reuse, multiple components can easily be "plugins" to the entire framework, Django has many powerful third-party plugins, and you can even easily develop your own toolkit. This makes Django very extensible. It also emphasizes rapid development and DRY(Do Not Repeat Yourself) principles. Webpy is compact, simple, practical, and can quickly complete simple web pages. Here according to webpy Cookbook briefly introduce webpy framework, more details please see (link: http://webpy.org/cookbook/index.zh-cn).

I. installation and development

      Web. Py download address: (link: 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 usable, run:


python setup.py install 

Note: on some unix-like systems you may need to switch to root or run:


sudo python setup.py install

You can also put the WEB folder inside site-packages.
      Web.py has a web server built into it. After the code is written, save it. For example, the file name is mywebpy.


python mywebpy.py

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

Two, URL processing

      The most important part of any website is its URL structure. Your URL is not just something that visitors can see and send to friends. It also dictates the mental model of how your site will work. On popular sites like del.icio.us, the URL is even part of the UI. Web.py makes such powerful urls possible.


urls = (
  '/', 'index'
)

The first part is the regular expression that matches the URL, such as /, /help/ FAQ, /item/(\d+), etc. (\d+ will match the number). Parentheses indicate capturing the corresponding data for later use. The second part is to accept the request of the class name, as the index, the view, welcomes. Hello hello class (welcomes module), or get_ \ 1. \1 will be replaced by the contents captured by the regular expression, and the rest captured will be passed to your function. This line says we want the URL/(home page) to be handled by a class called index. Now we need to create an application that lists these urls.
App = web application (urls, globals ())
This tells web.py to create an application based on the list of urls we just submitted. The application looks for the corresponding class in the file's global namespace.
      Generally speaking, at the very top of each application, you will often see the entire URL scheduling pattern defined in tuples:


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 path to this URL is /myapp/greetings/hello. Web.py internally adds $to the URL path so that /tasks/ does not match /tasks/addnew. URL matching depends on "path", so cannot be used like this: /tasks/delete? Name = (. +),? The rest is "query" and will not be matched. For more details on the URL component, visit web.ctx.

You can capture URL parameters and use them in the handler class:
/ users/list/(+), "list_users"
The block after list/ is captured and then used as an argument in GET or POST:


class list_users:
    def GET(self, name):
        return "Listing info about user: {0}".format(name)

You can define more parameters as needed. Also note the parameters of the URL query (? Later) can also be obtained with web.input().

Third, hello world

      Now we need to write the index class. While most people will just look, they won't notice that your browser is using the HTTP language used to communicate with the world wide web. The specifics are not important, but it is important to understand that web visitors request web servers based on urls (like /, /foo? F =1) the basic idea of performing an appropriate function (like GET, POST). GET is used to request web page text. When you type harvard.edu in the browser, it will go directly to the Harvard web server, go GET /. POST is often used to submit forms, such as requesting something to buy. You can use POST whenever you submit a request to do something (like handle a transaction with a credit card). This is key because the GET URL can be indexed and accessed by the search engine. While most pages you want to be indexed, a few like order processing pages you don't want to be indexed.
In our web.py code, we make a clear distinction between the two methods:


class index:
    def GET(self):
        return "Hello, world!"

When someone requests/with GET, this GET function is called at any time by web.py.
Okay, so the limit is that we just need the last sentence. This row tells web.py to start serving web pages:


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

This will tell web.py to launch the application we wrote above for us.
The above code is listed 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 display after running:
http://0.0.0.0:8080/
Enter http://127.0.0.1:8080 in your browser and hello world! Page.

Four, templates,

      Create a new directory for your templates (named templates). In that directory, create a new file that ends in.html.


<em>Hello</em>, world!

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


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

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

Under the first line of code.py add:


render = web.template.render('templates/')

This tells web.py to look up templates in your templates directory. Then change index.get to: tell web.py to look up template files in your template directory. Modified index. The GET:


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

The complete code is:


##@ Small 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()

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

But if we want the user to type in his name, here's what it looks like:


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.
After the URL? It doesn't look good, so modify the URL configuration:
'/ (. *)', 'index'

Then modify GET:


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

The complete code is:


##@ Small 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()

Visit http://127.0.0.1:8080/TOM now, it will show the I just wanted to say hello to TOM. If you visit http://127.0.0.1:8080/, it will show the hello, world!

Five, forms,

1, the introduction of

            The form includes Textbox, Password, Textarea, Dropdown, Radio, Checkbox, Button and the specific usage and style are 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)]
)

Appears on the page:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201406/201406091037314207.jpg" >

2. Enter attributes
Such as:


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. Examples:


##code.py
##@ Small WuYi 
import web,os
from web import form
render = web.template.render("d:/webpy/templates")## Modeled on here http://webpy.org/form#example Relative paths were initially used templates/, But it always happens and can't be found formtest So after searching, I found that changing to an absolute path can solve this 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:


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

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201406/2014060914542777.jpg" >

After filling in the form, if the password is the same twice, it will display HAHA! , otherwise show Try again, Passwords didn't match:.

Vi. Database

1. Database connection
      Before you start working with the database, make sure you have the appropriate database access libraries installed. For example, for MySQL databases, use MySQLdb, and for Postgres databases, use psycopg2.
Create a database object: db= web.database(DBN ='postgres', user='username', pw='password', db='dbname')
2. Database reading
      For example, in the database test, there is a table testtable, the field is name, the above code.py changes, if the login is successful, then list the contents of the testtable.

Code. Py


##@ Small WuYi 
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


$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 writing
If you add the user from the above FORM FORM to the name field of the testtable table, you can simply add a line in the above code: n=db.insert('voa',filename=f['username'].value).
Now, after changing the code.py code, when the form is filled correctly, username will be added to the testtable table. The full code is as follows:


##@ Small WuYi 
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 articles: