Some tips for using Python's bottle framework are described _python

Source: Internet
Author: User

Before the bottle did a lot of introduction, but also wrote some articles to explain the shortcomings of bottle, recently found that in fact, some places said before the unfair, so take advantage of this opportunity to correct.

Bottle is the syntax that supports similar flask url_for, the specific use method is described below
Bottle Request.query parameters such as the default is the STR type, there are reasons, for example, when I give Google as an agent, coding is not necessarily utf8, if the forced conversion UTF8 will be the error
Previous bugs have been fixed, such as mount ('/x ', app), and/x/and/x can access

OK, now officially into the topic, let's introduce some advanced use of some bottle


A. Smart Create URL

This part of the bottle document is not introduced (in fact, bottle realized a lot of intimate functions, do not know why are not written on the document).
In the bottle class, there is a member function:

def get_url (self, Routename, **kargs): "" "return
  a string that matches a named route" ""
  ScriptName = request.env Iron.get (' Script_name ', '). Strip ('/') + '/'
  location = Self.router.build (Routename, **kargs). Lstrip ('/')
  Return Urljoin (Urljoin ('/', scriptname), location)
 
def get_url (self, Routename, **kargs): "" "Return
  a string That matches a named route "" "
  ScriptName = Request.environ.get (' script_name ', '). Strip ('/') + '/'
  location = sel F.router.build (Routename, **kargs). Lstrip ('/') return
  urljoin (Urljoin ('/', scriptname), location)

So where did this routename come from? Look at the parameters of the route adorner:

def route (self, path=none, method= ' get ', Callback=none, Name=none,
     Apply=none, Skip=none, **config):
 
def Route (self, path=none, method= ' get ', Callback=none, Name=none,
     Apply=none, Skip=none, **config):

Where the name parameter is Routename (it has to be said here, this way is better than flask, to use to specify name, and do not need to implement URL_FOR, the entire framework to achieve a complex)

So it's clear to everyone here that bottle's URL Builder is bound to the bottle instance, so the default across instance access is not.
And perhaps due to the bottle of the micro, so its source code deliberately to the default bottle sample packaging a function:

For name in ' "' Route get post put delete error mount
        hook install uninstall '. Split ():
  globals () [Name] = Make_def Ault_app_wrapper (name)
URL = make_default_app_wrapper (' Get_url ')
del name for name in ' "'
 
route get post put Delete Error mount
        hook install uninstall '. Split ():
  globals () [Name] = Make_default_app_wrapper (name)
url = make_default_app_wrapper (' Get_url ')
del name

The advantage of this is that if the project uses only the default bottle instance, the URL can be used directly in the template without having to pass a bottle instance.

To correct it, bottle's get_url cannot be invoked across apps, such as the Get_url of a mount app that invokes the main app, because at this point script_name is the path of the current page, so assembling it will be messy, so don't try.

But how do you get a template to access a local variable? We'll now introduce


Two. Assign a default variable to a template

Because the author uses most is the JINJA2, therefore the template related introduction All is takes the JINJA2 as the example.
Since many instances of bottle are proxy patterns used, such as request,response,local, we can safely pass these variables to the template default variable.
The code is simple too:

From bottle import basetemplate

BaseTemplate.defaults.update (dict (
  request=request,
  local=local,
  )
 
from bottle import basetemplate
 
BaseTemplate.defaults.update (dict (
  request=request,
  Local=local,
  )
)

If you are interested, you can also go to see the source directly, very understood


three. Add filters to the template

Or take jinja2 as an example, give the code directly as follows:

From bottle import basetemplate

if ' filters ' not in basetemplate.settings:
  basetemplate.settings[' filters '] = { }

filters = basetemplate.settings[' Filters ']

def urlencode_filter (params):
  "'
  urlencode
  '" From
  urllib import urlencode return

  UrlEncode (params)

filters.update
  (dict Filter,
  )
) from
 
bottle import basetemplate
 
if ' filters ' to basetemplate.settings:
  basetemplate.settings[' filters '] = {}
 
filters = basetemplate.settings[' Filters ']
 
def urlencode_filter ( params):
  ' UrlEncode '
  from
  urllib import urlencode return
 
  UrlEncode (params)
 
Filters.update (Dict (
  urlencode=urlencode_filter,
  )
)

OK, that's all this, here is the bottle version is 0.10.9, if there is no match, please check the bottle version.

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.