Simple and Direct Python web framework: Web. py

Source: Internet
Author: User

From: http://www.oschina.net/question/5189_4306

 

Web. py is a Python web framework, which is simple and powerful. Web. py is public, no matter what use it is, there is no limit.

Let's take a look at the simple and powerful web. py:

import web

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

class hello:
def GET(self, name):
i = web.input(times=1)
if not name: name = 'world'
for c in xrange(int(i.times)): print 'Hello,', name+'!'

if __name__ == "__main__": web.run(urls, globals())

Look, the above is a complete Web Application Based on Web. py. Believe it ?! Save the above Code as the file code. py and execute Python code. py in the command line. Then open your browser and open the address http: // localhost: 8080/roswan to check the result. If there is no accident, install the Web first. PY, which will be introduced below), the browser will display "Hello, roswan! ". This is the simplest Hello world web application. Is it easy ?! The following describes web. py in detail. Find fun

1. Install

Click here to download web. install the py file, decompress the downloaded file web.py-0.21.tar.gz, enter the decompressed folder, and execute: Python setup. PY install. in Linux and other systems, the root permission is required. Run: sudo Python setup. PY install.

After the installation is complete, you can start the Web. py tour...

2. URL Processing

For a site, the URL organization is the most important part, because this is what the user sees and directly affects how the site works, such as Del. icio. us, its URLs, or even part of the web page. Web. py can construct a powerful URLs in a simple way.

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

import web

Now, we need to tell the Web. py URL how to organize it. Let's start with a simple example:

urls = (
'/', 'index' )

In the above example, the first part ('/') is a regular expression that matches the URL, such as/,/help/FAQ,/item/(/d +), and so on; the second part ('index') is a class name, And the matched request will be sent.

Now, we need to write the index class. When most people browse the Web page, they did not notice that the browser communicates with the World Wide Web through HTTP. The communication details are not very important, but you need to understand that the user is using URLs (such as // or/Foo? F = 1) to request the Web server to complete certain requests (such as get or post ).

Get is the most common method used to request a page. When we enter "Harvard.edu" in the browser, it actually requests get "/" to the web server. Another common method is post, which is often used to submit a specific type of form, such as using a credit card to pay and process an order. Note: Get URLs can be indexed by search engines (IMAGINE Google trying to buy the items on your website ).

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

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

When a GET request is received, the above get method will be called by web. py.

Okay. Now, we only need to add the last line of code for Web. py to start the web application:

if __name__ == "__main__": web.run(urls, globals())

The above shows how to configure the URLs for Web. py and the global namespace of the searched class in the file.

The content of the entire code. py file is as follows:

import web

urls = (
'/', 'index' )

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

if __name__ == "__main__": web.run(urls, globals())

I have mentioned a lot of things, but in fact the web application code only needs the above lines, and this is a complete Web. py application. Enter:

$ python code.py
Launching server: http://0.0.0.0:8080/

Now, your web. py application has started the server. If you access http: // localhost: 8080/through a browser, you will see "Hello, world! ". When starting the server, you can add an IP address/port after Python code. py to control the server started by web. py. For example, Python code. py 8888.

3. debugging

Web. py also provides debugging tools. In the final "If name ..." Add the following code before the Code:

web.webapi.internalerror = web.debugerror

And in the final "If name ..." Add "Web. reloader":

if __name__ == "__main__": web.run(urls, globals(), web.reloader)

The code above will give you more useful information during the debugging phase. Web. reloader is actually a middleware. When you are running, you modify the code. after the py file, the web. reloader reloads the code. py file, so that you can immediately see the changes in the browser. If there are many changes, you still need to restart the server. Web. py also provides Web. profiler to output useful information about the number of function calls on each page, which helps you improve your code.

4. Template

Writing HTML code in python is quite cumbersome, while embedding Python code in HTML is much more interesting. Fortunately, Web. py makes the process quite easy.

Note: The old version of Web. py uses the cheetah templates template. You can continue to use it, but it is no longer officially supported.

In our web application, add a new folder to organize template files (for example, "/templates"). Then create an HTML file (for example, javasindex.html "):

<em>Hello</em>, world!

Alternatively, you can use the web. py template language to compile this HTML file:

$def with (name)

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

Note the indentation of the above Code!

As you can see, the template above looks very similar to this python file, starting with the def with statement, but you need to add "$" before the keyword.

Note: If a variable in the template contains an HTML Tag that references the variable in the $ format, the HTML Tag is only displayed in plain text. To generate an HTML Tag, you can use $: to reference a variable.

Now, return to the code. py file and add it in the next line of "Import web:

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

This shows where web. py can search for the template directory.

Tip: You can add cache = false in the render call so that the template is reloaded every time you access the page.

Next, modify the get method of the Code. py file:

def GET(self):
name = 'Bob'
print render.index(name)

The above "Index" is the Template Name, and "name" is the parameter passed in the past.

Modify the URLs variable of the Code. py file:

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

The above "/(. *)" is a regular expression.

Modify the get method as follows:

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

Now, if you access "/", "Hello, world!" will be displayed! "; Access"/Joe "will display" I just want to say hello to Joe ".

If you want to learn more about Web. py templates, you can access the templetor page.

5. Database

Note: Install the correct database driver before you start connecting to the database. For example, MySQL uses mysaldb and postgre uses psycopg2.

Add the following code to correctly configure your database:

web.config.db_parameters = dict(
dbn='postgres',
user='username',
pw='password',
db='dbname'
)

Now, create a simple table in the database:

CREATE TABLE todo (
id serial primary key,
title text,
created timestamp default now(),
done boolean default 'f'
);

Initialize a row:

INSERT INTO todo (title) VALUES ('Learn web.py');

Return to code. py and modify the get method as follows:

def GET(self):
todos = web.select('todo')
print render.index(todos)

Modify the URLs variable:

urls = (
'/', 'index')

Recompile the index.html file as follows:

$def with (todos)
<ul>
$for todo in todos:
<li id="t$todo.id">$todo.title</li>
</ul>

Now, you can access "/". If "learn web. py" is displayed, congratulations!

Now let's look at how to write data to the database.

Add the following content at the end of the index.html file:

<form method="post" action="add">
<p>
<input type="text" name="title" />
<input type="submit" value="Add" />
</p>
</form>

Modify the URLs variable of the Code. py file as follows:

urls = (
'/', 'index',
'/add', 'add'
)

Add a class in code. py:

class add:
def POST(self):
i = web.input()
n = web.insert('todo', title=i.title)
web.seeother('/')

Web. input allows you to easily access the variables submitted by users through forms. Web. insert is used to insert data to the "Todo" table of the database and return the ID of the newly inserted row. Web. seeother is used for redirection to "/".

Tip: database operations include web. transact (), Web. Commit (), Web. rollback (), and Web. Update ().

In web. py, there are also web. Input, Web. query, and other functions that return "storage objects", which can be used like a dictionary class (dictionaries.

6. Summary

Web. py is indeed quite small and should belong to a lightweight Web framework. However, this does not affect the strength of Web. py, and it is very simple and straightforward to use. In practical applications, Web. py is more of an academic value, because you can see more underlying web applications, this cannot be learned in today's "very abstract" Web Framework: If you want to know more about the web. PY to access the Web. PY official documentation.

This tutorial is about to end here. If you are interested in Web. py, you can search for more documents about Web. py. You will surely find something cooler. Have fun!

Tags:Python web. py supplementary topic description»

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.