diff --git a/sources/43-web2py-russian-translation-in-progress/07.markmin b/sources/43-web2py-russian-translation-in-progress/07.markmin index b3470d91..07e084e3 100644 --- a/sources/43-web2py-russian-translation-in-progress/07.markmin +++ b/sources/43-web2py-russian-translation-in-progress/07.markmin @@ -477,7 +477,7 @@ SQLFORM(table, record=None, fields = ['name'] ``:code -- ``labels`` является словарем из меток полей. Ключ словаря является именем поля, а соответствующее значение явялется тем, что ключ отображает в метке поля. Если метка не предоставлена, то web2py получает метку от имени поля (он капитализирует имя поля и заменяет знаки подчеркивания на пробелы). Например: +- ``labels`` является словарем из меток полей. Ключ словаря является именем поля, а соответствующее значение является тем, что ключ отображает в метке поля. Если метка не предоставлена, то web2py получает метку от имени поля (он капитализирует имя поля и заменяет знаки подчеркивания на пробелы). Например: `` labels = {'name':'Your Full Name:'} ``:code @@ -627,51 +627,51 @@ def display_manual_form(): ``:code -Notice that the action does not return the form because it does not need to pass it to the view. The view contains a form created manually in HTML. The form contains a hidden field "_formname" that must be the same ``formname`` specified as an argument of ``accepts`` in the action. web2py uses the form name in case there are multiple forms on the same page, to determine which one was submitted. If the page contains a single form, you can set ``formname=None`` and omit the hidden field in the view. +Заметим, что действие не возвращает форму, так как его не нужно передавать в представление. Представление содержит форму, созданную вручную в HTML. Форма содержит скрытое поле "_formname", которое должно быть таким же как и ``formname``, указанное в качестве аргумента ``accepts`` в действии. web2py использует имя формы в случае, если существует множество форм на одной странице, чтобы определить, какая из них была подана. Если страница содержит единственную форму, вы можете установить ``formname = None`` и не указывать скрытое поле в представлении. -``form.accepts`` will look inside ``response.vars`` for data that matches fields in the database table ``db.person``. These fields are declared in the HTML in the format +``form.accepts`` будет смотреть внутри ``response.vars`` для данных, которые соответствуют полям в таблице базы данных ``db.person``. Эти поля объявлены как HTML в формате `` ``:code -Note that in the example given, the form variables will be passed on the URL as arguments. If this is not desired, the ``POST`` protocol will have to be specified. Note furthermore, that if upload fields are specified, the form will have to be set up to allow this. Here, both options are shown: +Обратите внимание, что в данном примере, переменные формы будут переданы к URL в качестве аргументов. Если этого не требуется, то должен быть указан протокол ``POST``. Заметим к тому же, что если заданы поля загрузки, то форму необходимо будет настроить так, чтобы разрешить это. Здесь показаны оба варианта: ``
``:code -#### ``SQLFORM`` and uploads +#### ``SQLFORM`` и загрузки -Fields of type "upload" are special. They are rendered as INPUT fields of ``type="file"``. Unless otherwise specified, the uploaded file is streamed in using a buffer, and stored under the "uploads" folder of the application using a new safe name, assigned automatically. The name of this file is then saved into the field of type uploads. +Поля "upload" типа являются специальными. Они визуализируются как поля INPUT ``type="file"``. Если не указано иное, то загруженный файл передается в потоке с использованием буфера и храниться в папке "uploads" приложения под новым безопасным именем, назначенным автоматически. Имя этого файла затем сохраняется в поле upload типа. -As an example, consider the following model: +В качестве примера рассмотрим следующую модель: `` db.define_table('person', Field('name', requires=IS_NOT_EMPTY()), Field('image', 'upload')) ``:code -You can use the same controller action "display_form" shown above. +Вы можете использовать то же самое действие "display_form" контроллера, показанного выше. -When you insert a new record, the form allows you to browse for a file. -Choose, for example, a jpg image. The file is uploaded and stored as: +При вставке новой записи, форма позволяет выбрать файл. +Выберите, например, JPG изображение. Файл загружается и хранится в виде: `` applications/test/uploads/person.image.XXXXX.jpg ``:code -"XXXXXX" is a random identifier for the file assigned by web2py. +"XXXXXX" является случайным идентификатором для файла, присвоенным web2py. ``content-disposition``:inxx ------- -Notice that, by default, the original filename of an uploaded file is b16encoded and used to build the new name for the file. This name is retrieved by the default "download" action and used to set the content disposition header to the original filename. +Заметим, что по умолчанию, исходное имя файла из загруженного файла является закодированным в b16 и используется для создания нового имени файла. Это имя извлекается с помощью "download" действия по умолчанию и используется для установки заголовка расположения содержимого в исходное имя файла. ------- -Only its extension is preserved. This is a security requirement since the filename may contain special characters that could allow a visitor to perform directory traversal attacks or other malicious operations. +Сохраняется только его расширение. Это требование безопасности, так как имя файла может содержать специальные символы, которые могли бы позволить посетителю выполнить атаку обхода каталогов или другие вредоносные операции. -The new filename is also stored in ``form.vars.image``. +Новое имя файла также хранится в ``form.vars.image``. -When editing the record using an UPDATE form, it would be nice to display a link to the existing uploaded file, and web2py provides a way to do it. +При редактировании записи с использованием формы UPDATE, было бы неплохо отображать ссылку на существующий загруженный файл, и web2py предоставляет способ сделать это. -If you pass a URL to the ``SQLFORM`` constructor via the upload argument, web2py uses the action at that URL to download the file. Consider the following actions: +Если передать URL в ``SQLFORM`` конструктор через аргумент upload, то web2py использует действие по этому URL для скачивания файла. Рассмотрим следующие действия: `` def display_form(): record = db.person(request.args(0)) @@ -687,22 +687,21 @@ def download(): return response.download(request, db) ``:code -Now, insert a new record at the URL: +Теперь, вставим новую запись по URL: `` http://127.0.0.1:8000/test/default/display_form ``:code -Upload an image, submit the form, and then edit the newly created record -by visiting: +Загрузите изображение, отправьте форму, а затем отредактируйте вновь созданную запись, посетив: `` http://127.0.0.1:8000/test/default/display_form/3 ``:code -(here we assume the latest record has id=3). The form will display an image preview as shown below: +(Здесь мы предполагаем, что последняя запись имеет id=3). Форма будет отображать изображение для предварительного просмотра, как показано ниже: [[image @///image/en6300.png center 300px]] -This form, when serialized, generates the following HTML: +Эта форма, когда сериализована генерирует следующий HTML: ``
``:code -which contains a link to allow downloading of the uploaded file, and a checkbox to remove the file from the database record, thus storing NULL in the "image" field. +которая содержит ссылку, чтобы разрешить скачивание загруженного файла, и флажок, чтобы удалить файл из записи базы данных, при этом сохраняя NULL в поле "image". -Why is this mechanism exposed? Why do you need to write the download function? Because you may want to enforce some authorization mechanism in the download function. See Chapter 9 for an example. +Почему этот механизм выставлен? Зачем вам нужно писать функцию скачивания (download)? Потому что вы можете навязать некоторый механизм авторизации к функции download. Смотрите Главу 9 для примера. -Normally uploaded files are stored into "app/uploads" but you can specify an alternate location: +Обычно загруженные файлы сохраняются в папке "app/upload", но вы можете указать другое место: `` Field('image', 'upload', uploadfolder='...') `` -In most operating system, accessing the file system can become slow when there are many files in the same folder. If you plan to upload more than 1000 files you can ask web2py to organize the uploads in subfolders: +В большинстве операционных систем, доступ к файловой системе может быть медленным, когда имеется слишком большое количество файлов в одной папке. Если вы планируете загружать более 1000 файлов, то вы можете попросить web2py организовать загрузки в подпапках: `` Field('image', 'upload', uploadseparate=True) `` -#### Storing the original filename +#### Сохранение оригинального имени файла -web2py automatically stores the original filename inside the new UUID filename and retrieves it when the file is downloaded. Upon download, the original filename is stored in the content-disposition header of the HTTP response. This is all done transparently without the need for programming. +web2py автоматически сохраняет исходное имя файла внутри нового UUID имени файла и возвращает его, когда файл скачивается. После скачивания, исходное имя файла хранится в content-disposition (расположение содержимого) заголовке ответа HTTP. Это все делается прозрачно без необходимости программирования. -Occasionally you may want to store the original filename in a database field. In this case, you need to modify the model and add a field to store it in: +Иногда вы можете захотеть хранить исходное имя файла в поле базы данных. В этом случае вам нужно изменить модель и добавить поле для хранения его там: `` db.define_table('person', Field('name', requires=IS_NOT_EMPTY()), @@ -739,7 +738,7 @@ db.define_table('person', Field('image', 'upload')) ``:code -Then you need to modify the controller to handle it: +Тогда вам нужно изменить контроллер для обработки его: `` def display_form(): @@ -756,26 +755,24 @@ def display_form(): return dict(form=form) ``:code -Notice that the ``SQLFORM`` does not display the "image_filename" field. -The "display_form" action moves the filename of the ``request.vars.image`` -into the ``form.vars.image_filename``, so that it gets processed by ``accepts`` and -stored in the database. The download function, before serving the file, checks in the database for the original filename and uses it in the content-disposition header. +Заметим, что ``SQLFORM`` не отображает поле "image_filename". +"display_form" действие перемещает имя файла из ``request.vars.image`` в ``form.vars.image_filename``, так что оно будет обрабатываться через ``accepts`` и храниться в базе данных. Функция download, перед подачей файла, проверяет в базе данных исходное имя файла и использует его в заголовке content-disposition. -#### ``autodelete`` +#### Автоудаление ``autodelete`` ``autodelete``:inxx -The ``SQLFORM``, upon deleting a record, does not delete the physical uploaded file(s) referenced by the record. The reason is that web2py does not know whether the same file is used/linked by other tables or used for other purpose. If you know it is safe to delete the actual file when the corresponding record is deleted, you can do the following: +``SQLFORM``, при удалении записи, не удаляет физически загруженный файл(ы), на который ссылается запись. Причина заключается в том, что web2py не знает, будет ли этот же файл использоваться/связан с другими таблицами или использоваться для других целей. Если вы уверены в безопасности удаления фактического файла, когда соответствующая запись будет удалена, то вы можете сделать следующее: `` db.define_table('image', Field('name', requires=IS_NOT_EMPTY()), Field('source','upload',autodelete=True)) ``:code -The ``autodelete`` attribute is ``False`` by default. When set to ``True`` is makes sure the file is deleted when the record is deleted. +Атрибут ``autodelete`` по умолчанию установлен на ``False``. При установке на ``True`` гарантируется, что файл будет удален при удалении записи. -#### Links to referencing records +#### Ссылки на ссылающиеся записи -Now consider the case of two tables linked by a reference field. For example: +Теперь рассмотрим случай двух таблиц, связанных через ссылочное поле. Например: `` db.define_table('person', Field('name', requires=IS_NOT_EMPTY())) @@ -785,13 +782,12 @@ db.define_table('dog', db.dog.owner.requires = IS_IN_DB(db,db.person.id,'%(name)s') ``:code -A person has dogs, and each dog belongs to an owner, which is a person. The dog owner is required to reference a valid ``db.person.id`` by ``'%(name)s'``. +Человек (person) имеет собаку (dog), и каждая собака принадлежит владельцу (owner), которым является человек. Владелец собаки обязан ссылаться на правильный ``db.person.id`` через ``'%(name)s'``. -Let's use the **appadmin** interface for this application to add a -few persons and their dogs. +Давайте воспользуемся интерфейсом **appadmin** для этого приложения, чтобы добавить несколько человек и их собак. -When editing an existing person, the **appadmin** UPDATE form shows a link to a page that lists the dogs that belong to the person. This behavior can be replicated using the ``linkto`` argument of the ``SQLFORM``. ``linkto`` has to point to the URL of a new action that receives a query string from the ``SQLFORM`` and lists the corresponding records. -Here is an example: +При редактировании существующего человека, **appadmin** форма UPDATE показывает ссылку на страницу, которая содержит список собак, которые принадлежат к человеку. Такое поведение может быть воспроизведено с помощью ``linkto`` аргумента из ``SQLFORM``. ``linkto`` должен указывать на URL нового действия, который принимает строку запроса от ``SQLFORM`` и перечисляет соответствующие записи. +Здесь приведен пример: `` def display_form(): record = db.person(request.args(0)) or redirect(URL('index')) @@ -806,26 +802,25 @@ def display_form(): return dict(form=form) ``:code -Here is the page: +Здесь страница: [[image @///image/en6400.png center 300px]] -There is a link called "dog.owner". The name of this link can be changed via the ``labels`` argument of the ``SQLFORM``, for example: +Существует ссылка называется "dog.owner". Название этой ссылки может быть изменено с помощью ``labels`` аргумента из ``SQLFORM``, например: `` labels = {'dog.owner':"This person's dogs"} ``:code -If you click on the link you get directed to: +Если вы нажмете на ссылку, то вы будете направлены на: `` /test/default/list_records/dog?query=db.dog.owner%3D%3D5 ``:code -"list_records" is the specified action, with ``request.args(0)`` set to the name of the referencing table and ``request.vars.query`` set to the SQL query string. -The query string in the URL -contains the value "dog.owner=5" appropriately url-encoded -(web2py decodes this automatically when the URL is parsed). +"list_records" это указанное действие, где ``request.args(0)`` устанавливает имя ссылаемой таблицы и ``request.vars.query`` устанавливает строку SQL запроса. +Строка запроса в URL содержит значение "dog.owner=5", которая надлежащим образом закодирована +(web2py декодирует это автоматически при разборке URL). -You can easily implement a very general "list_records" action as follows: +Вы можете легко реализовать очень общий "list_records" действие следующим образом: `` def list_records(): import re @@ -838,24 +833,26 @@ def list_records(): return dict(records=records) ``:code -with the associated "default/list_records.html" view: +с ассоциативно связанным "default/list_records.html" представлением: `` {{extend 'layout.html'}} {{=records}} ``:code -When a set of records is returned by a select and serialized in a view, it is first converted into a SQLTABLE object (not the same as a Table) and then serialized into an HTML table, where each field corresponds to a table column. +Когда набор записей возвращается через выборку (select) и сериализуется в представлении, он сначала преобразуется в SQLTable объект (не путайте с Table), а затем сериализуется в HTML-таблицу, где каждое поле соответствует столбцу таблицы. + +#### Предварительное заполнение формы -#### Pre-populating the form -It is always possible to pre-populate a form using the syntax: +Всегда можно предварительно заполнить форму, используя синтаксис: `` form.vars.name = 'fieldvalue' ``:code -Statements like the one above must be inserted after the form declaration and before the form is accepted, whether or not the field ("name" in the example) is explicitly visualized in the form. +Выражения, подобные приведенным выше, должны быть вставлены после объявления формы и перед принятием для формы решения о том, является ли или нет поле ("name" в приведенном выше примере) явно отображаемым в форме. + +#### Добавление дополнительных элементов формы в ``SQLFORM`` -#### Adding extra form elements to ``SQLFORM`` -Sometimes you may wish to add an extra element to your form after it has been created. For example, you may wish to add a checkbox which confirms the user agrees with the terms and conditions of your website: +Иногда вы можете добавить дополнительный элемент в форму после того, как она была создана. Например, вы можете захотеть добавить флажок, который подтверждает, что пользователь согласен с условиями вашего сайта: `` form = SQLFORM(db.yourtable) my_extra_element = TR(LABEL('I agree to the terms and conditions'), \ @@ -863,38 +860,38 @@ my_extra_element = TR(LABEL('I agree to the terms and conditions'), \ form[0].insert(-1,my_extra_element) ``:code -The variable ``my_extra_element`` should be adapted to the formstyle. In this example, the default ``formstyle='table3cols'`` has been assumed. +Переменная ``my_extra_element`` должна быть адаптирована к formstyle. В этом примере, по умолчанию предполагается ``formstyle='table3cols'``. -After submission, ``form.vars.agree`` will contain the status of the checkbox, which could then be used in an ``onvalidation`` function, for instance. +После подачи, ``form.vars.agree`` будет содержать статус флажка, который затем может быть использован, к примеру, в ``onvalidation`` функции. -#### ``SQLFORM`` without database IO +#### ``SQLFORM`` без ввода-вывода базы данных -There are times when you want to generate a form from a database table using ``SQLFORM`` and you want to validate a submitted form accordingly, but you do not want any automatic INSERT/UPDATE/DELETE in the database. This is the case, for example, when one of the fields needs to be computed from the value of other input fields. This is also the case when you need to perform additional validation on the inserted data that cannot be achieved via standard validators. +Есть моменты, когда вы хотите создать форму из таблицы базы данных с помощью ``SQLFORM`` и вы хотите проверять поданную форму соответствующим образом, но вы не хотите выполнение какого-либо автоматического действия по INSERT/UPDATE/DELETE в базе данных. Это имеет место, например, когда одно из полей должно быть вычислено из значения других полей ввода. Это также тот случай, когда вам необходимо выполнить дополнительную проверку вставляемых данных, которая не может быть достигнута с помощью стандартных валидаторов. -This can be done easily by breaking: +Это может быть сделано без труда путем разбивки: `` form = SQLFORM(db.person) if form.process().accepted: response.flash = 'record inserted' ``:code -into: +в: `` form = SQLFORM(db.person) if form.validate(): - ### deal with uploads explicitly + ### имеем дело с загрузками в явном виде form.vars.id = db.person.insert(**dict(form.vars)) response.flash = 'record inserted' ``:code -The same can be done for UPDATE/DELETE forms by breaking: +То же самое можно сделать для UPDATE/DELETE форм путем разбивки: `` form = SQLFORM(db.person,record) if form.process().accepted: response.flash = 'record updated' ``:code -into: +в: `` form = SQLFORM(db.person,record) if form.validate(): @@ -905,20 +902,20 @@ if form.validate(): response.flash = 'record updated' ``:code -In the case of a table including an "upload"-type field ("fieldname"), both ``process(dbio=False)`` and ``validate()`` deal with the storage of the uploaded file as if ``process(dbio=True)``, the default behavior. +В случае с таблицей, включающей в себя поле типа "upload" ("fieldname"), оба аргумента ``process(dbio=False)`` и ``validate()`` имеют дело с хранением загруженного файла, как если бы ``process(dbio=True)``, поведение по умолчанию. -The name assigned by web2py to the uploaded file can be found in: +Имя, назначенное web2py для загружаемого файла можно найти в: `` form.vars.fieldname ``:code -### Other types of Forms +### Формы другого типа -#### ``SQLFORM.factory`` +#### Фабрика ``SQLFORM.factory`` -There are cases when you want to generate forms ''as if'' you had a database table but you do not want the database table. You simply want to take advantage of the ``SQLFORM`` capability to generate a nice looking CSS-friendly form and perhaps perform file upload and renaming. +Есть случаи, когда вы хотите генерировать формы ''как если бы'' вы имели таблицу базы данных, но вы не хотите заводить таблицу базы данных. Вы просто хотите воспользоваться возможностью ``SQLFORM`` для создания приятной выглядящей CSS-дружественной формы и, возможно, выполнить загрузку файлов и переименование. -This can be done via a ``form_factory``. Here is an example where you generate the form, perform validation, upload a file and store everything in the ``session`` : +Это можно сделать через ``form_factory``. Здесь приведен пример, где вы генерируете форму, выполняете проверку, загружаете файл и сохраняете все в ``session``: `` def form_from_factory(): form = SQLFORM.factory( @@ -933,38 +930,36 @@ def form_from_factory(): return dict(form=form) ``:code -The Field object in the SQLFORM.factory() constructor is fully documented in the [[DAL chapter ../06#field_constructor]]. -A run-time construction technique for SQLFORM.factory() is +Объект Field в конструкторе SQLFORM.factory() полностью документирован в [[Главе DAL ../06#field_constructor]]. + +Техникой во время выполнения конструкции для SQLFORM.factory() является `` fields = [] fields.append(Field(...)) form=SQLFORM.factory(*fields) ``:code -Here is the "default/form_from_factory.html" view: +Здесь указано представление "default/form_from_factory.html": `` {{extend 'layout.html'}} {{=form}} ``:code -You need to use an underscore instead of a space for field labels, or explicitly pass a dictionary of ``labels`` to ``form_factory``, as you would for a ``SQLFORM``. By default ``SQLFORM.factory`` generates the form using html "id" attributes generated as if the form was generated from a table called "no_table". To change this dummy table name, use the ``table_name`` attribute for the factory: +Вам необходимо использовать подчеркивание вместо пробела для меток (labels) полей, или явно передать словарь ``labels`` в ``form_factory``, как если бы это сделали для ``SQLFORM``. По умолчанию ``SQLFORM.factory`` генерирует форму с помощью html атрибутов "id", которые генерируется, как если бы форма была сгенерирована из таблицы под названием "no_table". Чтобы изменить это фиктивное имя таблицы, используйте атрибут ``table_name`` для фабрики: `` form = SQLFORM.factory(...,table_name='other_dummy_name') ``:code -Changing the ``table_name`` is necessary if you need to place two factory generated forms in the same table and want to avoid CSS conflicts. +Изменение ``table_name`` необходимо в случае, если вам требуется разместить две фабрично сгенерированные формы в этой же таблице, и вы хотите избежать конфликтов CSS. -##### Uploading files with SQLFORM.factory +##### Загрузка файлов с SQLFORM.factory -#### One form for multiple tables +#### Одна форма для нескольких таблиц -It often happens that you have two tables (for example 'client' and -'address' which are linked together by a reference and you want to -create a single form that allows to insert info about one client and -its default address. Here is how: +Часто бывает так, что у вас есть две таблицы (например "client" и "address", которые связаны друг с другом с помощью ссылки, и вы хотите создать единую форму, которая позволяет вставлять информацию об одном клиенте и его адрес по умолчанию. Вот как: -model: +Модель: `` db.define_table('client', Field('name')) @@ -974,7 +969,7 @@ db.define_table('address', Field('street'),Field('city')) ``:code -controller: +Контроллер: `` def register(): form=SQLFORM.factory(db.client,db.address) @@ -986,53 +981,50 @@ def register(): return dict(form=form) ``:code -Notice the SQLFORM.factory (it makes ONE form using public fields from -both tables and inherits their validators too). -On form accepts this does two inserts, some data in one table and some -data in the other. +Обратите внимание на SQLFORM.factory (она делает одну форму, используя публичные поля из обеих таблиц и также наследует их валидаторы). +Для формы, которая принимает эти данные, делается две вставки, некоторые данные вставляются в одну таблицу, а некоторые данные в другую. ------- -This only works when the tables don't have field names in common. +Это работает только тогда, когда таблицы не имеют общие имена полей. ------- - -#### Confirmation Forms +#### Формы подтверждения ``confirm``:inxx -Often you need a form with a confirmation choice. The form should be accepted if the choice is accepted and none otherwise. The form may have additional options that link other web pages. web2py provides a simple way to do this: +Часто вам нужна форма с подтверждением выбора. Форма должна быть принята, если выбор принят и не принята в противном случае. Форма может иметь дополнительные опции, которые связывают другие веб-страницы. web2py обеспечивает простой способ сделать это: `` form = FORM.confirm('Are you sure?') if form.accepted: do_what_needs_to_be_done() ``:code -Notice that the confirm form does not need and must not call ``.accepts`` or ``.process`` because this is done internally. You can add buttons with links to the confirmation form in the form of a dictionary of ``{'value':'link'}``: +Заметим, что форма подтверждения не нуждаются и не должна вызывать ``.accepts`` или ``.process``, так как это делается внутренне. Вы можете добавить кнопки со ссылками на форму подтверждения в виде словаря ``{'value':'link'}``: `` form = FORM.confirm('Are you sure?',{'Back':URL('other_page')}) if form.accepted: do_what_needs_to_be_done() ``:code -#### Form to edit a dictionary +#### Форма для редактирования словаря -Imagine a system that stores configurations options in a dictionary, +Представьте себе систему, которая хранит параметры конфигурации в словаре, `` config = dict(color='black', language='English') ``:code -and you need a form to allow the visitor to modify this dictionary. -This can be done with: +и вам нужна форма, чтобы позволить посетителю изменить этот словарь. +Это можно сделать с помощью: `` form = SQLFORM.dictform(config) if form.process().accepted: config.update(form.vars) ``:code -The form will display one INPUT field for each item in the dictionary. It will use dictionary keys as INPUT names and labels and current values to infer types (string, int, double, date, datetime, boolean). +Форма будет отображать одно поле INPUT для каждого элемента в словаре. Она будет использовать ключи словаря в качестве имен и меток INPUT и выводит типы текущих значений (string, int, double, date, datetime, boolean). -This works great but leave to you the logic of making the config dictionary persistent. For example you may want to store the ``config`` in a session. +Это прекрасно работает, но при этом оставляет вам устойчивую логику создания словаря конфигурации. Например, вы можете хранить ``config`` в сессии. `` session.config or dict(color='black', language='English') @@ -1042,36 +1034,36 @@ if form.process().accepted: ``:code -### CRUD +### Интерфейс CRUD ``CRUD``:inxx ``crud.create``:inxx ``crud.update``:inxx ``crud.select``:inxx ``crud.search``:inxx ``crud.tables``:inxx ``crud.delete``:inxx -One of the recent additions to web2py is the Create/Read/Update/Delete (CRUD) API on top of SQLFORM. -CRUD creates an SQLFORM, but it simplifies the coding because it incorporates the creation of the form, the processing of the form, the notification, and the redirection, all in one single function. +Одним из последних дополнений web2py является Create/Read/Update/Delete (CRUD) API поверх SQLFORM. +Интерфейс CRUD создает SQLFORM, но он упрощает написание кода, так как он включает в себя создание формы, обработку формы, уведомление и перенаправление, то есть все в одной функции. -The first thing to notice is that CRUD differs from the other web2py APIs we have used so far because it is not already exposed. It must be imported. It also must be linked to a specific database. For example: +Первое, что нужно заметить это то, что CRUD отличается от других web2py API, которые мы использовали до сих пор, потому что он уже не выставляется. Он должен быть импортирован. Он также должен быть связан с определенной базой данных. Например: `` from gluon.tools import Crud crud = Crud(db) ``:code -The ``crud`` object defined above provides the following API: +Объект ``crud``, определенный выше, предоставляет следующие API: ``crud.tables``:inxx ``crud.create``:inxx ``crud.read``:inxx ``crud.update``:inxx ``crud.delete``:inxx ``crud.select``:inxx . -- ``crud.tables()`` returns a list of tables defined in the database. -- ``crud.create(db.tablename)`` returns a create form for table tablename. -- ``crud.read(db.tablename, id)`` returns a readonly form for tablename and record id. -- ``crud.update(db.tablename, id)`` returns an update form for tablename and record id. -- ``crud.delete(db.tablename, id)`` deletes the record. -- ``crud.select(db.tablename, query)`` returns a list of records selected from the table. -- ``crud.search(db.tablename)`` returns a tuple (form, records) where form is a search form and records is a list of records based on the submitted search form. -- ``crud()`` returns one of the above based on the ``request.args()``. +- ``crud.tables()`` возвращает список таблиц, определенный в базе данных. +- ``crud.create(db.tablename)`` возвращает созданную форму для таблицы tablename. +- ``crud.read(db.tablename, id)`` возвращает readonly форму для tablename и записи id. +- ``crud.update(db.tablename, id)`` возвращает форму обновления для tablename и записи id. +- ``crud.delete(db.tablename, id)`` удаляет запись. +- ``crud.select(db.tablename, query)`` возвращает список записей, выбранных из таблицы. +- ``crud.search(db.tablename)`` возвращает кортеж (форма, записи), где форма представляет собой форму поиска и записи являются списком записей на основе представленной формы поиска. +- ``crud()`` возвращает одно из вышеуказанного на основе ``request.args()``. -For example, the following action: +Для примера, следующее действие: `` def data(): return dict(form=crud()) ``:code -would expose the following URLs: +выставляет следующие URL-адреса: `` http://.../[app]/[controller]/data/tables http://.../[app]/[controller]/data/create/[tablename] @@ -1082,84 +1074,84 @@ http://.../[app]/[controller]/data/select/[tablename] http://.../[app]/[controller]/data/search/[tablename] ``:code -However, the following action: +Тем не менее, следующее действие: `` def create_tablename(): return dict(form=crud.create(db.tablename)) ``:code -would only expose the create method +будет выставлять только метод create `` http://.../[app]/[controller]/create_tablename ``:code -While the following action: +В то время как следующее действие: `` def update_tablename(): return dict(form=crud.update(db.tablename, request.args(0))) ``:code -would only expose the update method +будет выставлять только метод update `` http://.../[app]/[controller]/update_tablename/[id] ``:code -and so on. +и так далее. -The behavior of CRUD can be customized in two ways: by setting some attributes of the ``crud`` object or by passing extra parameters to each of its methods. +Поведение CRUD можно настроить двумя способами: посредством установки некоторых атрибутов ``crud`` объекта или путем передачи дополнительных параметров для каждого из его методов. -#### Settings +#### Настройки -Here is a complete list of current CRUD attributes, their default values, and meaning: +Ниже приведен полный список текущих атрибутов CRUD, их значения по умолчанию, и смысл: -To enforce authentication on all crud forms: +Для применения аутентификации на всех формах crud: `` crud.settings.auth = auth ``:code -The use is explained in chapter 9. +Использование объясняется в Главе 9. -To specify the controller that defines the ``data`` function which returns the ``crud`` object +Укажите контроллер, который определяет ``data`` функции, которая возвращает ``crud`` объект `` crud.settings.controller = 'default' ``:code -To specify the URL to redirect to after a successful "create" record: +Укажите URL для перенаправления после успешного "создания" (create) записи: `` crud.settings.create_next = URL('index') ``:code -To specify the URL to redirect to after a successful "update" record: +Укажите URL для перенаправления после успешного "обновления" (update) записи: `` crud.settings.update_next = URL('index') ``:code -To specify the URL to redirect to after a successful "delete" record: +Укажите URL для перенаправления после успешного "удаления" (delete) записи: `` crud.settings.delete_next = URL('index') ``:code -To specify the URL to be used for linking uploaded files: +Укажите URL, который будет использоваться для связывания загруженных файлов: `` crud.settings.download_url = URL('download') ``:code -To specify extra functions to be executed after standard validation procedures for ``crud.create`` forms: +Укажите дополнительные функции, которые будут выполняться после стандартных процедур проверки для ``crud.create`` формы: `` crud.settings.create_onvalidation = StorageList() ``:code -``StorageList`` is the same as a ``Storage`` object, they are both defined in the file "gluon/storage.py", but it defaults to ``[]`` as opposed to ``None``. It allows the following syntax: +``StorageList`` такой же, как ``Storage`` объект, они оба определены в файле "gluon/storage.py", но он по умолчанию ``[]`` в отличие от ``None``. Он позволяет следующий синтаксис: `` crud.settings.create_onvalidation.mytablename.append(lambda form:....)