A summary of the basic knowledge of Python's bottle framework _nginx

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

The ejector adorner has an optional keyword method by default 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 ('/F Ile ')
def get_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 response
Response.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 in response. COOKIES.

From bottle import Response
response. 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 Default_app, run
app = Default_app ()
Newapp = Yourmiddleware (APP)
run (App=newapp)

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.

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, run
mybottle = 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, Cherrypyserver bottle.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. In this way, you can use all the CPU cores, or even the load between different physical servers.

But there are some drawbacks:

    • Data cannot be shared in multiple Python processes.
    • A large amount of memory may be required at the same time to run Python and bottle applications and replicas.

One of the fastest loads is pound of course other HTTP servers can do well.

Soon I will join LIGHTTPD and Apache.
Apache Mod_wsgi

The release of your application of course is not with the bottle method, you can again Apache server using the Mod_wsgi template and bottles Wsgi interface.

You need to create APP.WSGI files and provide application objects. This object is invoked using MOD_WSGI to start your program and follow the WSGI specification.

#/var/www/yourapp/app.wsgi
import Bottle
# ... add or import your bottle app code here ...
# import MyApp
application = Bottle.default_app ()
# Don't use Bottle.run () with Mod_wsgi

The Apache configuration may be as follows:

<virtualhost *>
  ServerName example.com wsgidaemonprocess yourapp user=www-data group=www-data

  Processes=1 threads=5
  wsgiscriptalias//var/www/yourapp/app.wsgi

  <Directory/var/www/yourapp>
    Wsgiprocessgroup YourApp
    Wsgiapplicationgroup%{global} order
    Deny,allow
    allow from all
  </Directory>
</ Virtualhost>

Google AppEngine

Import bottle from
google.appengine.ext.webapp import util 
# ... add or import your bottle app code here ...
# import MyApp
# Don't use Bottle.run () with AppEngine
Util.run_wsgi_app (Bottle.default_app ())

CGI mode

Run slowly, but you can work properly.

Import Bottle
# ... add or import your bottle app code here ...
Bottle.run (Server=bottle. Cgiserver)


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.