A brief introduction to Python's lightweight web framework Bottle_python

Source: Internet
Author: User
Tags http request

Basic mapping

Mappings are used to generate corresponding return content based on different URL requests. Bottle uses the route () modifier to implement the mapping.

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 will see "Hello world!" in the browser.
Get , POST, head, ...

This mapping adorner has an optional keyword method that defaults to method= ' get '. It is also possible to post,put,delete,head or listen to 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 to
  "Done"

Dynamic mapping

You can extract the part of the URL to create a map of the dynamic variable name.

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

By default, one: Placeholder will always match to the next slash. If you need to change, you can add regular characters to the #s:

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

Or you can use a complete regular matching group to:

@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 you are just a number inside. You must explicitly type cast.
@validate () Adorner

Bottle provides a convenient adorner validate () to validate multiple parameters. It can process each URL parameter by keyword and filter and then return the 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 checksum parameter fails.
returns the file stream and JSON

The WSGI specification cannot handle file objects or strings. Bottle the automatic conversion string type is a ITER object. The following example can be run under bottle, but it cannot be run in a pure WSGI environment.

@route ('/get_string ') def get_string (): Return "This isn't
  a list of strings, but a single string" @route ('/file ') def G Et_file (): Return
  open (' Some/file.txt ', ' R ')

The dictionary type is also allowed. Converts to JSON format and returns Content-type:application/json automatically.

@route ('/api/status ') def api_status (): Return
  {' status ': ' Online ', ' servertime ': Time.time ()}

You can turn off this feature: Bottle.default_app (). Autojson = False
Cookies

Bottle Store cookies in request.cookies variables. The new cookie method is Response.set_cookie (name, value[, **params]). It can accept additional parameters, which belong to Simplecookie with valid parameters.

From bottle import Responseresponse.set_cookie (' key ', ' value ', path= '/', domain= ' example.com ', secure=true, expires=+ 500, ...)

Set the Max-age property (it is not a valid python parameter name) You can modify the cookie in the instance. Simplecookie Inresponse. COOKIES.

From bottle import Responseresponse. cookies[' key ' = ' value ' response. cookies[' key ' [' max-age '] = 500

Template

Bottle uses a small, self-contained template. You can use the call template (Template_name, **template_arguments) and return the result.

@route ('/hello/:name ') def Hello (name): Return
  template (' Hello_template ', username=name)

This loads the HELLO_TEMPLATE.TPL and extracts url:name to the variable username, returning the request.

Hello_template.tpl roughly like this:

 
 

Template Search Path

Template is based on bottle. Template_path list variables to search. The default path contains ['./%s.tpl ', './views/%s.tpl '].
Template Caching

The template is cached in memory after compilation. Modifying the template does not update the cache until you clear the cache. Call Bottle.TEMPLATES.clear ().
template Syntax

Template syntax is a thin layer around python. The main purpose is to ensure the correct indentation of the block. Here are some examples of template syntax:

    • %... The Python code begins. You do not have to deal with indentation issues. Bottle will do this for you.
    • %end closes some statements%if ...,%for ... or something. Closing blocks are required.
    • {{...}} Print out the results of the Python statement.
    • %include template_name optional_arguments includes other templates.
    • Each row is returned as text.

Example:

%header = ' Test Template '
%items = [1,2,3, ' Fly ']
%include http_header, Title=header ' use_js=[', ' Default.js '] 
 

Key/value Database

Bottle (>0.4.6) provides a key/value database by Bottle.db module variables. You can use key or properties to access a database object. Call Bottle.db.bucket_name.key_ Name and Bottle.db[bucket_name][key_name].

Just make sure you use the right name, regardless of whether they already exist or not.

Stored objects are similar to dict dictionaries, keys and values must be strings. These methods are not supported for items () and values (). The Keyerror will be thrown if it is not found.
Persistence of

For requests, all changes are cached in the local memory pool. At the end of the request, the modified section is automatically saved so that the next request returns the updated value. The data is stored in the Bottle.db_path file. To make sure that the file is accessible to this file.
Race conditions

In general, it is not necessary to consider the lock problem, but it is still a problem in a multi-threaded 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 the operation of other environments on the database. Until you call Bottle.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

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

From bottle import Default_app, RunApp = Default_app () Newapp = Yourmiddleware (APP) run (App=newapp)

Default Default_app () work

Bottle creates a Bottle.bottle () object and adorner that invokes the Bottle.run () run. Bottle.default_app () is the default. 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 The default is to use Wsgiref.simpleserver publishing. This default single-threaded server is used for early development and testing, but may later become a performance bottleneck.

There are three ways to modify:

    1. Using a multithreaded Adapter
    2. Load multiple Bottle instance applications
    3. or both.

Multithreaded server

The easiest way to do this is to install a multithreaded and WSGI-spec HTTP server such as paste, Flup, cherrypy or FAPWS3 and use the appropriate adapters.

From bottle import Pasteserver, Flupserver, Fapwsserver, Cherrypyserverbottle.run (server=pasteserver) # Example

Without your favorite servers and adapters, 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 with more CPUs. The key is to leverage CPU resources to load balance multiple standalone Python programs.

Single instance bottle applications, you can start with different ports (localhost:8080, 8081, 8082, ...). High performance load as a reverse proxy and a new requirement for each random bottle process, the balancer behaves to propagate all available support and server instance loads. This way, you can use all the CPU cores and even scatter them in different physical suits

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.