WikiSort.ru - Не сортированное

ПОИСК ПО САЙТУ | о проекте

web2py
Тип фреймворк для разработки веб приложений
Автор Massimo Di Pierro
Разработчик web2py developers
Написана на Python
Первый выпуск сентябрь 27, 2007 (2007-09-27)
Аппаратная платформа Cross-platform
Последняя версия 2.11.2 (2015-05-30; 1370 дней тому назад)
Состояние Активное
Лицензия GNU Lesser General Public License version 3 (LGPLv3)
Сайт web2py.com
mailing list

web2py — фреймворк с открытым исходным кодом для разработки веб приложений, написанный на языке программирования Python. Web2py позволяет веб разработчикам создавать динамические сайты используя Python. Web2py призван сократить рутинные процессы веб разработки, такие как написание веб форм с нуля, хотя разработчик может разработать форму с нуля, если в этом возникнет необходимость.[1]

Web2py изначально был придуман как учебный инструмент с акцентом на юзабилити и простоту внедрения, так в нём отсутствуют файлы конфигурации проекта. Архитектура web2py была разработана под влиянием фреймворков Ruby on Rails (RoR) и Django. Как и эти фреймворки, web2py нацелен на rapid development, провозглашает приоритет соглашения над конфигурацией и следует Model-View-Controller (MVC) шаблону проектирования.

Обзор

Web2py является полнофункциональным фреймворком и содержит встроенные компоненты для всех основных функций, включая:

Web2py поощряет лучшие software engineering практики, а именно:

  • Model-View-Controller (MVC) шаблон проектирования;
  • само-отправку[4] веб форм;
  • сессии на стороне сервера (server-side sessions);
  • безопасную обработку загружаемых на сервер файлов.

Web2py использует WSGI, Python-ориентированный протокол для коммуникации между веб сервером и веб приложениями. Также доступны обработчики для CGI и FastCGI протоколов, а в поставку включён многопоточный, поддерживающий SSL WSGI сервер Rocket[5].

Отличительные особенности

Веб интегрированная среда разработки (IDE)

Весь процесс разработки, отладки, тестирования, поддержки и администрирование удалённой базы данных может осуществляться (при желании) без каких-либо сторонних инструментов, через веб интерфейс, которой является в свою очередь web2py приложением. Интернационализация (добавление языков и перевод) также может быть выполнена из этого IDE. Каждое приложение снабжается автоматически сгенерированным интерфейсом администрирования баз данных, по типу Django. Веб интегрированная среда разработки также включает в себя средства тестирования и веб консоль.

Приложения могут быть созданы как из командной строки так и написаны с помощью сторонних IDE.[6] Доступны дополнительные возможности для отладки:[7]

  • Wing IDE allows graphical debugging of web2py applications[8] as you interact with it from your web browser, you can inspect and modify variables, make function calls etc.
  • Eclipse/PyDev — Eclipse with the Aptana PyDev plugin — supports web2py as well.[9][10]
  • The extensible pdb debugger is a module of Python’s standard library.
  • With the platform-independent open-source Winpdb debugger, you can perform remote debugging[11] over TCP/IP, through encrypted connection.[12]

Классическая Hello World программа на web2py в её простейшем виде (будет показана «голая» веб страничка[13] без шаблона) выглядит так:

def hello():
    return 'Hello World'

Web2py включает основанный на чистом Python язык шаблонов, не требующий использования отступов и Document Object Model на стороне сервера (DOM).

Шаблонизатор может быть использован и отдельно от web2py.[14] Joomla 1.x templates can be converted to web2py layouts.[15]

Web2py также поставляется с двумя библиотеками разметки: фильтром markdown2 text-to-HTML, конвертирующим разметку Markdown в HTML на лету; и markmin схожий с предыдущим но поддерживающий и таблицы, html5 видео\аудио и протокол oembed.

Контроллер в случае отсутствия соответствующего представления автоматически использует универсальное представление отображающее переменные возвращённые контроллером, таким образом позволяя разработку бизнес логики приложения до написания HTML вёрстки. Пример «Hello World» использующий шаблон по умолчанию:

def hello():
    return dict(greeting='Hello World')

Значение dict() возвращаемое действием (функцией) автоматически выводится в виде HTML если страница запрашивается с расширением .html, в виде JSON если страница запрашивается с расширением .json, в виде XML если страница запрашивается с расширением .xml. Другие протоколы, такие как jsonp, rss, ics, google maps, и тд. поддерживаются и могут быть расширены.

Ниже приведён более сложный пример кода, где определяется таблица и зарегистрированным пользователям предоставляется возможность редактировать её поля:

db.define_table('thing',Field('name',notnull=True))

@auth.requires_login()
def hello():
    return dict(grid = SQLFORM.grid(db.thing))

Система отслеживания ошибок

Каждое web2py приложение снабжено системой отслеживания ошибок:

  • If an error occurs, it is logged and a ticket is issued to the user. That allows error tracking.
  • Errors and source code are accessible only to the administrator, who can search and retrieve errors by date or client-IP. No error can result in code being exposed to the users.

Машинонезависимый cron

Cron is a mechanism for creating and running recurrent tasks in background. It looks for an application-specific crontab file which is in standard crontab format. Three modes of operation are available:

  • Soft cron: cron routines are checked after web page content has been served, does not guarantee execution precision. For unprivileged Apache CGI/WSGI installs.
  • Hard cron: a cron thread gets started on web2py startup. For Windows and Rocket/standalone web2py installs.
  • System cron: cron functions get force-called from the command line, usually from the system crontab. For Unix/Linux systems and places where the cron triggers need to be executed even if web2py is not running at the moment; also good for CGI/WSGI installs if you have access to the system crontab.

Планировщик задач

Since version 2.3 the use of cron is discouraged since web2py comes with a master/worker scheduler. Jobs can be defined in models and are scheduled by creating an entry in the database. Users can start work processes who pickup and execute tasks in background. The schedule is better than cron because it allows to specify more parameters (start time, stop time, number of repetitions, number of trials in case of error) and do a better job at running within constant resource utilization.

Распространение в форме байткода

Web2py can compile web applications for distribution in bytecode compiled form, without source code. Unlike frameworks that use specialized template languages for their views, Web2py can also compile the view code into bytecode, since it is pure Python code.

Глобальная среда выполнения

Web2py is unique in the world of Python web frameworks because models and controllers are executed, not imported. They are not modules. They are executed in a single global environment which is initialized at each http request. This design decision has pros and cons.

The major pros is the ease of development, specifically for rapid prototyping. Another pro is that all the objects defined within this environment are cleanly reset at each http request and never shares across requests. This means the developer does not need to worry about changing the state of an object (for example the readable attribute of a database field) or worry about a change leaking to other concurrent requests or other applications. A third advantage is that web2py allows the coexistence of multiple applications under the same instance without conflicts even if they use different versions of the same modules or different modules with the same name.

The main disadvantage of the global environment is that model files and controller files are not modules and the order of execution matters (although it can be specified using conditional models). Naming conflict is more likely to occur than in normal Python modules. Some standard Python development tools may not understand objects defined in models and controllers. Moreover developers must be aware that code in models is executed at every request and this may cause a performance penalty. Nothing in web2py prevents developers from using and importing normal Python modules (model-less approach) and for this purpose web2py provides a thread local object (current) to facilitate access to objects associated to the current request. Yet, in this case, the developer has to be aware of the same pitfalls that other frameworks incur into: changing the state of an object defined in a module may affect other concurrent requests.

Another con is that, because models and controllers are not class-based, efficient code reuse becomes more difficult, particularly as the inability to inherit from a parent controller (e.g. the ApplicationController in Ruby on Rails) means that common controller functionality must be referenced repeatedly across all controller files.

Поддерживаемые платформы

Операционные системы, версии Python, виртуальные машины, аппаратное обеспечение

web2py работает на Windows, Windows CE телефонах, Mac, Unix/Linux, Google App Engine, Amazon EC2, почти любом веб хостинге с Python 2.4[16]/2.5/2.6/2.7.

Release versions of web2py include Python 2.5, but the source version can be run on 2.4 through 2.7.

web2py since v1.64.0 runs unmodified on Java with Jython 2.5, without any known limitation.[17]

web2py code can run with IronPython on .NET.[18] Limitations:

  • no csv module (so no database I/O);
  • no third party database drivers (not even SQLite, so no databases at all);
  • no built-in web server (unless you cripple it by removing signals and logging).

The web2py binary will[19] run from a USB drive or a portable hard drive without dependencies, like Portable Python.

Веб серверы

Web2py отвечает на запросы сделанные по HTTP и HTTPS с помощью встроенного Rocket сервера,[20] а также Apache,[21] Lighttpd,[22] Cherokee,[23] Hiawatha, Nginx и почти любого другого данного веб сервера поддерживающего CGI, FastCGI, WSGI, mod proxy,[24][25][26] и/или mod python.

IDEs и отладчики

While a number of web2py developers use text editors such as Vim, Emacs or TextMate Web2py also has a built-in web-based IDE. Others prefer more specialized tools providing debugging, refactoring, etc.

Работа с базами данных

Уровень абстракции баз данных (DAL) web2py прозрачно и динамически генерирует SQL запросы и выполняет их на множестве совместимых СУБД без необходимости использования специфичных для базы данные SQL команд (в то же время SQL команды также могут быть выполнены напрямую).

SQLite is included in Python and is the default web2py database. A connection string change allows connection to Firebird, IBM DB2, Informix, Ingres, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, and Google App Engine (GAE) with some caveats. Specialities:

  • Multiple database connections.
  • Automatic table creates and alters.
  • Automatic transactions.
  • Distributed transactions:
    • Since web2py v1.17 with PostgreSQL v8.2 and later,[28][29] because it provides API for two-phase commits.
    • Since web2py v1.70.1 with Firebird and MySQL (experimental).
  • GAE is not a relational store, but web2py emulates certain operations.

DAL обещает высокую скорость работы, по крайней мере по сравнению с SQLAlchemy и Storm.[30]

Web2py implements a DAL, not an ORM. An ORM maps database tables into classes representing logical abstractions from the database layer (e.g., a User class or a PurchaseOrder class), and maps records into instances of those classes. The DAL instead maps database tables and records into instances of classes representing sets and records instead of higher-level abstractions. It has very similar syntax to an ORM but it is faster, and can map almost any SQL expressions into DAL expressions. The DAL can be used independently of the rest of web2py.[31]

Ниже приведёны некоторые примеры синтаксиса DAL:

db = DAL('postgresql://user:pass@localhost/db', pool_size=10)
db.define_table('person',Field('name'),Field('image','upload'))
db.person.insert(name='Martin', image=open('filename.png'))
rows = db((db.person.name=='Martin')|db.person.name.contains('T')).select(orderby=db.person.name.lower())

The latest version of the DAL has support for 2D GIS functions with Spatialite and PostGIS. The current API are experimental because of a possible move to 3D APIs.

Автоматизированная миграция баз данных

web2py поддерживает автоматизированную миграцию баз данных — стоит изменить определение таблицы и web2py изменит (ALTER) её соответственно. Migrations are automatic, but can be disabled for any table, and migration is typically disabled when an application is ready for live distribution. Migrations and migration attempts are logged, documenting the changes.

Ограничения:

  • SQLite cannot alter table and change a column type, but rather simply stores new values according to the new type.
  • GAE has no concept of alter-table, so migrations are limited.

Лицензия

Web2py code is released under GNU Lesser General Public License (LGPL) version 3 as of web2py version 1.91.1.[32]

Web2py code before version 1.91.1 was released under GNU GPL v2.0 with commercial exception.

Various third-party packages distributed with web2py have their own licenses, generally Public-domain, MIT or BSD-type licenses. Applications built with web2py are not covered by the LGPL license.

Авторские права на Web2py принадлежат Massimo DiPierro. Торговая марка «web2py framework» принадлежит Massimo DiPierro.

Награды

В 2011 году InfoWorld поставил web2py во главе шести Python веб фреймворков , присудив web2py награду Bossie 2011 года в номинации best open source application development software. В 2012 году web2py выиграл премию технологии года за то, что Web2py содержит в себе всё необходимое для создания веб приложений — даже интерпретатор Python. Its creator’s mission to build an easy-to-use framework extends throughout. Web2py’s database abstraction layer allows you to manipulate a variety of databases without having to write any SQL. Once you’ve defined your database tables, Web2py will automatically build an administration interface for your app. In fact, Web2py’s combination console and dashboard is where all your application development activities take place—even editing your application files. Finally, Web2py lets you embed Python code into your Web page’s HTML, so you don’t have to learn a new template language. With all its built-in assistance, Web2py is as painless as it gets.

Библиография

Учебник по web2py

Документация по web2py собрана в Полное справочное руководство, от Massimo DiPierro. The manual is also available in printed form or as a read-only PDF.

Онлайн документация

Online documentation is linked from the web2py home page, with cookbook, videos, interactive examples, interactive API reference, epydoc s (complete library reference), FAQ, cheat sheet, online tools etc.

Видео

Печатные материалы

Общие сведения

Поддержка

Community support is available through the web2py knowledge base, the web2py mailing list at Google Groups, and the #web2py channel on freenode.[33] As of 2009-10-02, commercial web2py support is provided by fifteen companies worldwide.[34]

Разработчики

Ведущим разработчиком web2py является профессор Massimo DiPierro, доцент Computer Science в университете DePaul University в городе Chicago. As of 2011, the web2py homepage lists over 70 «main contributors».[35]

Исходный код

Исходный код web2py доступен из двух репозиториев:

Сторонние компоненты используемые в web2py

История и название

Исходный код первой общедоступной версии web2py был опубликован под лицензией GNU GPL v2.0 27 сентября 2007 года Massimo DiPierro под названием Enterprise Web Framework (EWF). Из-за конфликта наименований имя пришлось менять два раза: EWF v1.7 было заменено на Gluon v1.0, а за Gluon v1.15 последовало web2py v1.16. Лицензия была сменена на LGPLv3 с выпуском web2py версии 1.91.1 2010-12-21.

Приложения созданные с использованием Web2py

  • Movuca CMS и движок социальной сети.
  • Instant Press Блог платформа.
  • Ourway Социальная сеть.
  • NoobMusic Портал о рок музыке.
  • LinkFindr Инструмент диагностики вычислительной сети.
  • StarMaker Создание karaoke музыкально-социальных приложений.

A longer list with screenshots can be found here and here. A list of plugins can be found here

Заметки

  1. Web2py (2013), What is web2py?, web2py.com, retrieved 11 October 2013, <http://www.web2py.com/init/default/what>
  2. Web2py поддерживает множество протоколов начиная с версии v1.63
  3. Using SOAP with web2py
  4. Writing Smart Web-based Forms
  5. Rocket Web Server
  6. Web2py online IDE with It’s All Text! Firefox addon and Ulipad (open source Python IDE)
  7. How to debug Web2py applications?
  8. Wing IDE supports debugging for web2py
  9. Eclipse/PyDev supports debugging for web2py
  10. Using web2py on Eclipse
  11. With Winpdb one can do remote debugging over TCP/IP (недоступная ссылка)
  12. Encrypted communication in Winpdb (недоступная ссылка)
  13. Simplest web page with web2py: «Hello World» example
  14. How to use web2py templates without web2py
  15. Using Joomla templates with web2py
  16. How to run web2py with Python 2.4
  17. Web2py runs fully on Java and J2EE using Jython
  18. Web2py runs with IronPython on .NET, with limitations
  19. MySQL with web2py Windows binary on a USB thumb-drive
  20. How to run the built-in SSL server
  21. Web2py with Apache and mod_ssl
  22. Web2py with Lighttpd and FastCGI
  23. Web2py with Cherokee
  24. Apache Module mod_proxy
  25. Web2py with mod_proxy
  26. Web2py with mod_proxy and mod_proxy_html
  27. Using Wing IDE with web2py
  28. Distributed transactions with PostgreSQL Архивировано 14 апреля 2009 года.
  29. Distributed transactions with PostgreSQL — further details
  30. ORM Benchmark
  31. How to use web2py DAL without web2py
  32. web2py License Agreement
  33. IRC #web2py channel Архивировано 27 октября 2009 года.
  34. Commercial support for web2py
  35. List of main contributors to web2py

Ссылки

Данная страница на сайте WikiSort.ru содержит текст со страницы сайта "Википедия".

Если Вы хотите её отредактировать, то можете сделать это на странице редактирования в Википедии.

Если сделанные Вами правки не будут кем-нибудь удалены, то через несколько дней они появятся на сайте WikiSort.ru .




Текст в блоке "Читать" взят с сайта "Википедия" и доступен по лицензии Creative Commons Attribution-ShareAlike; в отдельных случаях могут действовать дополнительные условия.

Другой контент может иметь иную лицензию. Перед использованием материалов сайта WikiSort.ru внимательно изучите правила лицензирования конкретных элементов наполнения сайта.

2019-2024
WikiSort.ru - проект по пересортировке и дополнению контента Википедии