Brief Introduction to Python's lightweight web framework Bottle and pythonwebbottle

Source: Internet
Author: User

Brief Introduction to Python's lightweight web framework Bottle and pythonwebbottle

Basic ing

Ing is used to generate the corresponding response content based on different URLs requests. Bottle uses the route () modifier to implement ing.

from bottle import route, run@route('/hello')def hello():  return "Hello World!"run() # This starts the HTTP server

Run this program. Access http: // localhost: 8080/hello and you will see "Hello World!" in the browser! ".
GET, POST, HEAD ,...

The method of this ing modifier has Optional keywords. The default value is method = 'get'. It may also be POST, PUT, DELETE, HEAD, or other HTTP request methods.

from bottle import route, request@route('/form/submit', method='POST')def form_submit():  form_data = request.POST  do_something(form_data)  return "Done"

Dynamic ing

You can extract the URL to create a dynamic variable name ing.
 

@route('/hello/:name')def hello(name):  return "Hello %s!" % name

By default, A: placeholder will always match the next Slash. If you need to modify it, you can add the regular character to # s:

@route('/get_object/:id#[0-9]+#')def get(id):  return "Object ID: %d" % int(id)

Or use the complete regular expression matching group:

@route('/get_object/(?P<id>[0-9]+)')def get(id):  return "Object ID: %d" % int(id)

As you can see, the URL parameter is still a string, even if your regular expression contains numbers, you must explicitly perform type forced conversion.
@ Validate () decorator

Bottle provides a convenient decorator validate () to verify multiple parameters. It can process each URL parameter through keywords and filters and then return a request.

from bottle import route, validate# /test/validate/1/2.3/4,5,6,7@route('/test/validate/:i/:f/:csv')@validate(i=int, f=float, csv=lambda x: map(int, x.split(',')))def validate_test(i, f, csv):  return "Int: %d, Float:%f, List:%s" % (i, f, repr(csv))

You may need to throw a ValueError when the verification parameter fails.
Returned file streams and JSON

The WSGI specification cannot process file objects or strings. The Bottle automatically converts the string type to iter objects. The following example can be run in the Bottle, but cannot run in the pure WSGI environment.

@route('/get_string')def get_string():  return "This is not a list of strings, but a single string"@route('/file')def get_file():  return open('some/file.txt','r')

The dictionary Type is also allowed. It is converted to json format and the Content-Type: application/json is automatically returned.

@route('/api/status')def api_status():  return {'status':'online', 'servertime':time.time()}

You can disable this feature: bottle. default_app (). autojson = False
Cookies

Bottle stores cookies in the request. cookie variable. the method for creating a cookie is response. set_cookie (name, value [, ** params]). it can accept additional parameters. SimpleCookie has valid parameters.

from bottle import responseresponse.set_cookie('key','value', path='/', domain='example.com', secure=True, expires=+500, ...)

Set the max-age attribute (it is not a valid Python parameter name). You can modify cookie. SimpleCookie inresponse. COOKIES in the instance.
 

from bottle import responseresponse.COOKIES['key'] = 'value'response.COOKIES['key']['max-age'] = 500

Template

Bottle uses the built-in small template. You can call template (template_name, ** template_arguments) and return the result.
 

@route('/hello/:name')def hello(name):  return template('hello_template', username=name)

In this way, hello_template.tpl is loaded, URL: name is extracted to the variable username, and a request is returned.

Hello_template.tpl is roughly like this:

Template search path

The template is searched based on the bottle. TEMPLATE_PATH list variable. The default path contains ['./% s. tpl', './views/% s. tpl'].
Template Cache

The template is cached in the memory after compilation. Modifying the template will not update the cache until you clear the cache. Call bottle. TEMPLATES. clear ().
Template syntax

The template syntax is a thin layer around Python. The main purpose is to ensure correct indentation blocks. Below are some columns of the template syntax:

  • %... Python code starts. You don't have to deal with indentation. Bottle will do this for you.
  • % End to close some statements % if..., % for... or other. To close the block is required.
  • {...} Printed the result of the Python statement.
  • % Include template_name optional_arguments includes other templates.
  • Each line is returned as text.

Example:

%header = 'Test Template'%items = [1,2,3,'fly']%include http_header title=header, use_js=['jquery.js', 'default.js']

Key/Value Database

Bottle (> 0.4.6) through bottle. the db module variable provides a key/value database. you can use keys or attributes to access a database object. call bottle. db. bucket_name.key_name and bottle. db [bucket_name] [key_name].

Make sure that you can use the correct name, regardless of whether they already exist.

The stored objects are similar to dict dictionaries. keys and values must be strings. The items () and values () methods are not supported. If they are not found, a KeyError is thrown.
Persistence

All requests are cached in the local memory pool. at the end of the request, the modified part is automatically saved so that the updated value is returned for the next request. data is stored in bottle. DB_PATH file. make sure the file can access this file.
Race conditions

Generally, you do not need to consider locking, but it is still a problem in multi-thread or cross-environment. you can call bottle. db. save () or botle. db. bucket_name.save () to refresh the cache, but there is no way to detect operations on the database in other environments until the bottle is called. db. save () or leave the current request.
Example
 

from bottle import route, db@route('/db/counter')def db_counter():  if 'hits' not in db.counter:    db.counter.hits = 0  db['counter']['hits'] += 1  return "Total hits: %d!" % db.counter.hits

Use WSGI and Middleware

Bottle. default_app () returns a WSGI application. If you like the WSGI middleware module, you only need to declare bottle. run () to wrap the application, instead of using the default one.
 

from bottle import default_app, runapp = default_app()newapp = YourMiddleware(app)run(app=newapp)

Ult_app () by default

Create a Bottle. the Bottle () object and decorator call the bottle. run () run. bottle. default_app () is the default value. of course, you can create your own bottle. bottle () instance.

from bottle import Bottle, runmybottle = Bottle()@mybottle.route('/')def index(): return 'default_app'run(app=mybottle)

Release

Bottle is released by default using wsgiref. SimpleServer. This default single-threaded server is used for early development and testing, but may become a performance bottleneck in the future.

There are three ways to modify it:

  1. Use a multi-threaded Adapter
  2. Load multiple Bottle instance applications
  3. Or both

Multi-thread Server

The simplest method is to install an HTTP server with multiple threads and WSGI specifications, such as Paste, flup, cherrypy or fapws3, and use the corresponding adapter.
 
From bottle import PasteServer, FlupServer, FapwsServer, CherryPyServerbottle. run (server = PasteServer) # Example

If you lack your desired server and adapter, You can manually modify the HTTP server and set bottle. default_app () to access your WSGI application.

def run_custom_paste_server(self, host, port):  myapp = bottle.default_app()  from paste import httpserver  httpserver.serve(myapp, host=host, port=port)

Multi-server process

A Python program can only use one CPU at a time, even if there are more CPUs, the key is to use CPU resources to load balance multiple independent Python programs.

For a single instance Bottle application, you can start it through different ports (localhost: 8080,808 1, 8082 ,...). high-performance load as a reverse proxy and new requirements for every random bottle process in the far future, balancer behavior, spread all available support and server instance load. in this way, you can use all the CPU cores, even distributed across different physical servers.

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.