Some tips for using the Python Bottle framework, pythonbottle framework

Source: Internet
Author: User

Some tips for using the Python Bottle framework, pythonbottle framework

I have made a lot of introductions to bottle before, and I have written some articles to describe the shortcomings of bottle. Recently, I found that it is unfair in some places, so I should take this opportunity to correct it.

Bottle supports syntax similar to flask url_for.
Bottle request. query and other parameters are of the str type by default. For example, when I perform a proxy for google, the encoding is not necessarily utf8. If it is forcibly converted to utf8, an error is returned.
The previous bug was also corrected. For example, after mount ('/X', app),/x/AND/x can be accessed.

OK. Now we will officially enter the topic. Let's introduce some advanced usage of some bottle.


1. Create a url intelligently

This part is not introduced in the bottle document (in fact, bottle has implemented many intimate functions, and I don't know why it is not written in 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.environ.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 = self.router.build(routename, **kargs).lstrip('/')  return urljoin(urljoin('/', scriptname), location)

So where does the routename come from? View the parameters of the route decorator:

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):

Here, the name parameter is routename (this method is better than flask. You need to specify the name only when using it, instead of implementing url_for. It is very complicated to implement the entire framework)

As you can see, the bottle url generator is bound to the Bottle instance, so cross-instance access is not possible by default.
The bottle may be regarded as micro-oriented, so the source code specifically wraps a function for the default Bottle example:

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 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 doing so is that if the project only uses the default Bottle instance, you can directly use the url in the template without having to upload more Bottle instances.

Correct: The get_url of the bottle cannot be called across apps. For example, if the mounted app calls the get_url of the main app, the system will get an error because the SCRIPT_NAME is the path of the current page, so the Assembly will be messy, so don't try again.

But how can we make the template accessible to the local variable? Next we will introduce


2. Specify the default variables for the Template

Because the most widely used is jinja2, the introduction to the template is based on jinja2.
Many bottle instances use proxy modes, such as request, response, and local, so we can safely pass these variables into the default template variables.
The Code is also simple:

from bottle import BaseTemplateBaseTemplate.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 take a look at the source code.


3. Add filters to the template

Take jinja2 as an example. The Code is as follows:

from bottle import BaseTemplateif '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(  urlencode=urlencode_filter,  )) 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(  urlencode=urlencode_filter,  ))

OK. The bottle version is 0.10.9. If any inconsistency exists, 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.