bottle/tutorial.rst at master · bottlepy/bottle · GitHub

Application-wide installation

Plugins can be installed application-wide or just to some specific routes that need additional functionality. Most plugins can safely be installed to all routes and are smart enough to not add overhead to callbacks that do not need their functionality.

Let us take the SQLitePlugin plugin for example. It only affects route callbacks that need a database connection. Other routes are left alone. Because of this, we can install the plugin application-wide with no additional overhead.

To install a plugin, just call :func:`install` with the plugin as first argument:

The plugin is not applied to the route callbacks yet. This is delayed to make sure no routes are missed. You can install plugins first and add routes later, if you want to. The order of installed plugins is significant, though. If a plugin requires a database connection, you need to install the database plugin first.

Uninstall Plugins

You can use a name, class or instance to :func:`uninstall` a previously installed plugin:

Plugins can be installed and removed at any time, even at runtime while serving requests. This enables some neat tricks (installing slow debugging or profiling plugins only when needed) but should not be overused. Each time the list of plugins changes, the route cache is flushed and all plugins are re-applied.

Auto reloading

During development, you have to restart the server a lot to test your
recent changes. The auto reloader can do this for you. Every time you
edit a module file, the reloader restarts the server process and loads
the newest version of your code.

How it works: the main process will not start a server, but spawn a new
child process using the same command line arguments used to start the
main process. All module-level code is executed at least twice! Be
careful.

Blacklisting plugins

You may want to explicitly disable a plugin for a number of routes. The :func:`route` decorator has a skip parameter for this purpose:

The skip parameter accepts a single value or a list of values. You can use a name, class or instance to identify the plugin that is to be skipped. Set skip=True to skip all plugins at once.

Похожее:  Связной Клуб: проверить баллы по номеру карты

Debug mode

During early development, the debug mode can be very helpful.

Development

So you have learned the basics and want to write your own application? Here are
some tips that might help you being more productive.

Dynamic routes

Routes that contain wildcards are called dynamic routes (as opposed to static routes) and match more than one URL at the same time. A simple wildcard consists of a name enclosed in angle brackets (e.g. <name>) and accepts one or more characters up to the next slash (/).

Each wildcard passes the covered part of the URL as a keyword argument to the request callback. You can use them right away and implement RESTful, nice-looking and meaningful URLs with ease. Here are some other examples along with the URLs they’d match:

Filters can be used to define more specific wildcards, and/or transform the covered part of the URL before it is passed to the callback. A filtered wildcard is declared as <name:filter> or <name:filter:config>. The syntax for the optional config part depends on the filter used.

The following filters are implemented by default and more may be added:

  • :int matches (signed) digits only and converts the value to integer.
  • :float similar to :int but for decimal numbers.
  • :path matches all characters including the slash character in a non-greedy way and can be used to match more than one path segment.
  • :re allows you to specify a custom regular expression in the config field. The matched value is not modified.

Let’s have a look at some practical examples:

You can add your own filters as well. See :doc:`routing` for details.

Excluding views from path-based authorization:

Routes can be excluded from path-based authorization requirements using the skip=[auth] method.

Generating content

In pure WSGI, the range of types you may return from your application is very limited. Applications must return an iterable yielding byte strings. You may return a string (because strings are iterable) but this causes most servers to transmit your content char by char. Unicode strings are not allowed at all. This is not very practical.

Похожее:  Как загрузить документы в личный кабинет росгосстрах - Вопросы права

Html <form> handling

Let us start from the beginning. In HTML, a typical <form> looks something like this:

Json content

Some JavaScript or REST clients send application/json content to the server. The :attr:`BaseRequest.json` attribute contains the parsed data structure, if available.

License¶

Code and documentation are available according to the MIT License:

Copyright(c)2009-2022,MarcelHellkamp.Permissionisherebygranted,freeofcharge,toanypersonobtainingacopyofthissoftwareandassociateddocumentationfiles(the"Software"),todealintheSoftwarewithoutrestriction,includingwithoutlimitationtherightstouse,copy,modify,merge,publish,distribute,sublicense,and/orsellcopiesoftheSoftware,andtopermitpersonstowhomtheSoftwareisfurnishedtodoso,subjecttothefollowingconditions:TheabovecopyrightnoticeandthispermissionnoticeshallbeincludedinallcopiesorsubstantialportionsoftheSoftware.THESOFTWAREISPROVIDED"AS IS",WITHOUTWARRANTYOFANYKIND,EXPRESSORIMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENTSHALLTHEAUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHERLIABILITY,WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISINGFROM,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSINTHESOFTWARE.

Opt-out is required for path-based authorization:

Path-based routes only function in Opt-Out mode (i.e.auth_all_routes=True) This better matches intent of path-based restrictions.

Prefix-based authorization

Often sites have structured layouts based on paths and formed in a logical tree, say, based on project, department, or customer. Prefix-based authorization provides an easy way to provide authorization restrictions.

Example logical tree of Departments:

/ -- - helpdesk
    |
     - infrastructure 
    |       |
    |        -- Networking
    |       |
    |        -- Servers
    |       |
    |        -- Storage
     - desktop
            |
             -- PC_support
            |
             -- MAC_support

There are implicit authorization rules that can be created based on the prefix path of views routes:

Example prefix-based authorization

Query variables

The query string (as in /forum?id=1&page=5) is commonly used to transmit a small number of key/value pairs to the server. You can use the :attr:`BaseRequest.query` attribute (a :class:

Похожее:  Часто задаваемые вопросы об услугах мобильной связи | Киевстар

Quickstart

pypi installation:

Request routing

In the last chapter we built a very simple web application with only a single route. Here is the routing part of the “Hello World” example again:

Route-based authorization

Route authorization restrictions are added to a views with the authz={…} config option in app.route(…) decorator.

Route based authorization can be used in either Opt-in or Opt-out mode, and any authz statement provides implicit authn=True authentication.

Authorization restrictions of authz={attr:value} are defined by attribute/value pairs in Python dict form.

route-based authorization:

Route-based authorization examples

Consider these examples:

Multiple authz examples:

Route-specific installation

The apply parameter of the :func:`route` decorator comes in handy if you want to install plugins to only a small number of routes:

Routing static files

Static files such as images or CSS files are not served automatically. You have to add a route and a callback to control which files get served and where to find them:

The :func:`static_file` function is a helper to serve files in a safe and convenient way (see :ref:`tutorial-static-files`). This example is limited to files directly within the /path/to/your/static/files directory because the <filename> wildcard won’t match a path with a slash in it. To serve files in subdirectories, change the wildcard to use the path filter:

Be careful when specifying a relative root-path such as root=’./static/files’. The working directory (./) and the project directory are not always the same.

Static files

You can directly return file objects, but :func:`static_file` is the recommended way to serve static files. It automatically guesses a mime-type, adds a Last-Modified header, restricts paths to a root directory for security reasons and generates appropriate error responses (403 on permission errors, 404 on missing files).

You can raise the return value of :func:`static_file` as an exception if you really need to.

Forced Download

Wsgi environment

Each :class:`BaseRequest` instance wraps a WSGI environment dictionary. The original is stored in :attr:`BaseRequest.environ`, but the request object itself behaves like a dictionary, too.

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 5,00 из 5)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован.

Adblock
detector