13 проектов для python-разработчиков среднего уровня

Об этом курсе

Недавно просмотрено: 76,066

Современная жизнь немыслима без web-сервисов, ежедневно приносящих дивиденды в самых разных областях человеческой деятельности. А значит, профессия web-разработчика еще долго будет оставаться высокооплачиваемой и востребованной на рынке IT-специалистов. Существует множество решений и инструментов на разных языках программирования, упрощающих и ускоряющих web-разработку. В рамках данного курса освещается построение web-приложений на языке Python.

Курс читают разработчики, применяющие Python в проектах, которыми ежедневно используют миллионы людей. В данном курсе вы сможете приобрести как базовые знания о функционировании современного интернета в целом, так и практические навыки создания интернет-приложений на языке Python.

Сертификат, ссылками на который можно делиться с другими людьми

Сертификат, ссылками на который можно делиться с другими людьми
Получите сертификат по завершении

100% онлайн

100% онлайн
Начните сейчас и учитесь по собственному графику.

Специализация

Курс 3 из 4 в программе
Специализация Программирование на Python

Гибкие сроки

Гибкие сроки
Назначьте сроки сдачи в соответствии со своим графиком.

Промежуточный уровень
Промежуточный уровень

Часов на завершение
Прибл. 66 часов на выполнение

Доступные языки

Русский
Субтитры: Русский

Web Applications#

You know how to write useful Python scripts, and now you want to show them off to the world… but how? Most non-programmers won’t have any use for your .py script files. Programs like PyInstaller and cx_Freeze help turn Python scripts into executable programs that run by themselves on different platforms without the need to use Python to interpret the code. More and more, however, we’re seeing a trend away from “desktop”-based applications and toward web applications that can be accessed and run through Internet browsers.

Historically, websites on the Internet were full of plain webpages that offered the exact same information to every user; you would request a page, and the information from that page would be displayed. These webpages were “static” because their content never changed; a web server would simply respond to a user’s request for a webpage by sending along that page, regardless of who the user was or what other actions the user took.

Today, most websites are actually web applications, which offer “dynamic” webpages that can change their content in any number of ways. For instance, a webmail application allows the user to interact with it, displaying all sorts of different information, often while staying in a single webpage.

Built-in Helpers

There are many built-in helpers used in web2py. Some of the HTML built-in helpers are listed as below.

Name Usage Example
A This helper is used to build links. It corresponds to the anchor tag
),
...]
B This helper helps in making the contents of the text, bold.
B('<hello>', XML('<i>world</i>'), _class = 'test', _id = 0)
BODY This helper makes the body of a page. It also includes a multiplication operator to increase the number of breaks.
BR()
CODE It performs syntax highlighting for Python, C, C&plus;&plus; and web2py code. This helper also has the ability to link an API documentation.
CODE('print "hello"', language = 'python').xml()
FIELDSET It creates an input field together with its label.
FIELDSET('Height:', INPUT(_name = 'height'), _class = 'test')
HEAD It helps in tagging <head> tag of an HTML page.
HEAD(TITLE('<hello>'))
IMG It helps in embedding images for the given HTML page.
IMG(_src = 'http://example.com/image.png',_alt = 'test')

Buffering and Streaming

Generally speaking, applications will achieve the best throughput
by buffering their (modestly-sized) output and sending it all at
once. This is a common approach in existing frameworks such as
Zope: the output is buffered in a StringIO or similar object, then
transmitted all at once, along with the response headers.

The corresponding approach in WSGI is for the application to simply
return a single-element iterable (such as a list) containing the
response body as a single string. This is the recommended approach
for the vast majority of application functions, that render
HTML pages whose text easily fits in memory.

For large files, however, or for specialized uses of HTTP streaming
(such as multipart «server push»), an application may need to provide
output in smaller blocks (e.g. to avoid loading a large file into
memory). It’s also sometimes the case that part of a response may
be time-consuming to produce, but it would be useful to send ahead the
portion of the response that precedes it.

In these cases, applications will usually return an iterator (often
a generator-iterator) that produces the output in a block-by-block
fashion. These blocks may be broken to coincide with multipart
boundaries (for «server push»), or just before time-consuming
tasks (such as reading another block of an on-disk file).

WSGI servers, gateways, and middleware must not delay the
transmission of any block; they must either fully transmit
the block to the client, or guarantee that they will continue
transmission even while the application is producing its next block.
A server/gateway or middleware may provide this guarantee in one of
three ways:

  1. Send the entire block to the operating system (and request
    that any O/S buffers be flushed) before returning control
    to the application, OR
  2. Use a different thread to ensure that the block continues
    to be transmitted while the application produces the next
    block.
  3. (Middleware only) send the entire block to its parent
    gateway/server

By providing this guarantee, WSGI allows applications to ensure
that transmission will not become stalled at an arbitrary point
in their output data. This is critical for proper functioning
of e.g. multipart «server push» streaming, where data between
multipart boundaries should be transmitted in full to the client.

In order to better support asynchronous applications and servers,
middleware components must not block iteration waiting for
multiple values from an application iterable. If the middleware
needs to accumulate more data from the application before it can
produce any output, it must yield an empty string.

To put this requirement another way, a middleware component must
yield at least one value each time its underlying application
yields a value. If the middleware cannot yield any other value,
it must yield an empty string.

This requirement ensures that asynchronous applications and servers
can conspire to reduce the number of threads that are required
to run a given number of application instances simultaneously.

Note also that this requirement means that middleware must
return an iterable as soon as its underlying application returns
an iterable. It is also forbidden for middleware to use the
write() callable to transmit data that is yielded by an
underlying application. Middleware may only use their parent
server’s write() callable to transmit data that the
underlying application sent using a middleware-provided write()
callable.

Web Client Frameworks

In contrast to server-oriented frameworks which may offer AJAX (asynchronous JavaScript and XML) support by serving pre-packaged (inflexible and highly specific but otherwise very useful) JavaScript components, and offering server-side support for requests made by such JavaScript components, Web client frameworks take more direct advantage of the dynamic capabilities of browser engines. Ways in which the full potential of browser engines can be realised are, for example, by compiling Python code into JavaScript or by embedding a Python interpreter into the Web browser itself. In some cases, Web browser engines can be run within separate customised applications rather than in a «web browser» per se. See Web Browser Programming for details.

Основные инструменты Python-разработчика

Изучение Питона не может быть полноценным без набора полезных инструментов под рукой. Мы собрали небольшой список и разделили его на категории.

Базовые

  • Pip — популярный менеджер пакетов в Python, с помощью которого можно устанавливать и управлять программными пакетами.
  • Pipenv — инструмент для управления виртуальным окружением в Python.
  • Setuptools — целый набор инструментов для создания пакетов в Python.
  • Virtualenv — инструмент для создания виртуального окружения с пакетами.

Документация

  • Sphinx — генератор документации, который изначально создавался для работы с Python, но впоследствии стал инструментом общего пользования.
  • autodoc — расширение Sphinx для создания reStructuredText файлов из исходного кода.

Тестирование

  • py.test — платформа для тестирования на Python со множеством функций. Инструмент автоматически находит тесты, запускает их и выводит отчёты.
  • Selenium WebDriver — в тандеме с другими инструментами позволяет эффективно тестировать веб-приложений.
  • unittest — модуль инструментов с настройкой используемых данных, управлением комплектами и наборами тестов, возможностью запускать тесты в графическом или текстовом режиме.

Optional Platform-Specific File Handling

Some operating environments provide special high-performance file-
transmission facilities, such as the Unix sendfile() call.
Servers and gateways may expose this functionality via an optional
wsgi.file_wrapper key in the environ. An application
may use this «file wrapper» to convert a file or file-like object
into an iterable that it then returns, e.g.:

if 'wsgi.file_wrapper' in environ:
    return environ(filelike, block_size)
else:
    return iter(lambda: filelike.read(block_size), '')

If the server or gateway supplies wsgi.file_wrapper, it must be
a callable that accepts one required positional parameter, and one
optional positional parameter. The first parameter is the file-like
object to be sent, and the second parameter is an optional block
size «suggestion» (which the server/gateway need not use). The
callable must return an iterable object, and must not perform
any data transmission until and unless the server/gateway actually
receives the iterable as a return value from the application.
(To do otherwise would prevent middleware from being able to interpret
or override the response data.)

To be considered «file-like», the object supplied by the application
must have a read() method that takes an optional size argument.
It may have a close() method, and if so, the iterable returned
by wsgi.file_wrapper must have a close() method that
invokes the original file-like object’s close() method. If the
«file-like» object has any other methods or attributes with names
matching those of Python built-in file objects (e.g. fileno()),
the wsgi.file_wrapper may assume that these methods or
attributes have the same semantics as those of a built-in file object.

The actual implementation of any platform-specific file handling
must occur after the application returns, and the server or
gateway checks to see if a wrapper object was returned. (Again,
because of the presence of middleware, error handlers, and the like,
it is not guaranteed that any wrapper created will actually be used.)

Apart from the handling of close(), the semantics of returning a
file wrapper from the application should be the same as if the
application had returned iter(filelike.read, ''). In other words,
transmission should begin at the current position within the «file»
at the time that transmission begins, and continue until the end is
reached.

Of course, platform-specific file transmission APIs don’t usually
accept arbitrary «file-like» objects. Therefore, a
wsgi.file_wrapper has to introspect the supplied object for
things such as a fileno() (Unix-like OSes) or a
java.nio.FileChannel (under Jython) in order to determine if
the file-like object is suitable for use with the platform-specific
API it supports.

Note that even if the object is not suitable for the platform API,
the wsgi.file_wrapper must still return an iterable that wraps
read() and close(), so that applications using file wrappers
are portable across platforms. Here’s a simple platform-agnostic
file wrapper class, suitable for old (pre 2.2) and new Pythons alike:

class FileWrapper:

    def __init__(self, filelike, blksize=8192):
        self.filelike = filelike
        self.blksize = blksize
        if hasattr(filelike, 'close'):
            self.close = filelike.close

    def __getitem__(self, key):
        data = self.filelike.read(self.blksize)
        if data:
            return data
        raise IndexError

and here is a snippet from a server/gateway that uses it to provide
access to a platform-specific API:

environ = FileWrapper
result = application(environ, start_response)

try:
    if isinstance(result, FileWrapper):
        # check if result.filelike is usable w/platform-specific
        # API, and if so, use that API to transmit the result.
        # If not, fall through to normal iterable handling
        # loop below.

    for data in result:
        # etc.

finally:
    if hasattr(result, 'close'):
        result.close()

HTML Helpers

web2py includes helper class which can be used to build HTML programmatically. It corresponds to the HTML tags, termed as “HTML helpers”.

For example −

), ...]

Here, A is the helper corresponding to the anchor <a> tag of HTML. It builds the HTML anchor <a> tag programmatically.

HTML helpers consists of two types, namely positional and named arguments.

  • Positional arguments are interpreted as objects contained between the HTML open and close tags.

  • Named arguments begins with an underscore are interpreted as HTML tag.

Helpers are also useful in serialization of strings, with the _str_ and xml methods. For example −

>>> print str(DIV(“hello world”))

Output

<div> hello world </div>

Note − HTML helpers provide a server-side representation of the Document Object Model (DOM).

web.session¶

Session Management
(from web.py)

class (app, store, initializer=None)

Session management for web.py

()

Called when an expired session is atime

()

Kill the session, make it no longer available

class

Base class for session stores

(timeout)

removes all the expired sessions

(session_data)

decodes the data to get back the session dict

(session_dict)

encodes session dict as a string

class (root)

Store for saving a session on disk.

>>> import tempfile
>>> root = tempfile.mkdtemp()
>>> s = DiskStore(root)
>>> s'a' = 'foo'
>>> s'a'
'foo'
>>> time.sleep(0.01)
>>> s.cleanup(0.01)
>>> s'a'
Traceback (most recent call last):
    ...
KeyError: 'a'

Applications

web2py applications are shown below in a diagrammatic form.

The Applications developed in web2py are composed of the following parts −

  • Models − Represents data and database tables.

  • Controllers − Describes the application logic and workflow.

  • Views − Helps rendering the display of the data.

  • Languages − describe how to translate strings in the application into various supported languages.

  • Static files − Do not require processing (e.g. images, CSS style sheets etc).

  • ABOUT and README − Details of the project.

  • Errors − Stores error reports generated by the application.

  • Sessions − Stores information related to each particular user.

  • Databases − store SQLite databases and additional table information.

  • Cache − Store cached application items.

  • Modules − Modules are other optional Python modules.

  • Private − Included files are accessed by the controllers but not directly by the developer.

  • Uploads − Files are accessed by the models but not directly by the developer.

Server-side DOM Rendering

Server-side rendering allows a user to pre-render the initial state of web2py components. All the derived helpers provide search element and elements to render DOM on server side.

The element returns the first child element matching a specified condition. On the other hand, elements return a list of all the matching children. Both use same syntax.

This can be demonstrated with the following example −

a = DIV(DIV(DIV('a', _id = 'target',_class = 'abc')))
d = a.elements('div#target')
d = 'changed'
print a

The output is given as −

<div><div><div id = "target" class = "abc">changed</div></div></div>

Popular Full-Stack Frameworks

A web application may use a combination of a base HTTP application server, a storage mechanism such as a database, a template engine, a request dispatcher, an authentication module and an AJAX toolkit. These can be individual components or be provided together in a high-level framework.

These are the most popular high-level frameworks. Many of them include components listed on the WebComponents page.

Name

Latest version

Latest update date

description

2.2.7 (LTS)

2019-11-04

The Web framework for perfectionists (with deadlines). Django makes it easier to build better Web apps more quickly and with less code. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performing, elegant Web applications quickly. Django focuses on automating as much as possible and adhering to the DRY (Don’t Repeat Yourself) principle. The last release supporting Python 2.7 is 1.11 LTS. See Django

2.4.2

2019-10-20

the rapid Web development webframework you’ve been looking for. Combines SQLAlchemy (Model) or Ming (MongoDB Model), Kajiki (View), Repoze and ToscaWidgets2. Create a database-driven, ready-to-extend application in minutes. All with designer friendly templates, easy AJAX on the browser side and on the server side, with an incredibly powerful and flexible Object Relational Mapper (ORM), and with code that is as natural as writing a function. After reviewing the Documentation, check out

2.18.5

2019-04-07

* Python 2.7, Python 3.5+, PyPy * All in one package with no further dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface, but not required. * web2py has no configuration files, requires no installation, can be run off a USB drive. * web2py uses Python for the Model, View and the Controller * Built-in ticketing system to manage errors * Internationalization engine and pluralisation, caching system * Flexible authentication system (LDAP, MySQL, janrain etc) * NIX(Linux, BSD), Windows, Mac OSX, tested on EC2, Webfaction * works with MySQL, PostgreSQL, SQLite , Firebird, Oracle, MSSQL and the Google App Engine via an ORM abstraction layer. * Includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. * Production ready, capable of upload/download of very large files * Emphasis on backward compatibility.

See below for some other arguably less popular full-stack frameworks!

Google App Engine#

The task of getting Python code to run on a website is a complicated one, but there are a number of different web frameworks available for Python that automatically take care the details.

The first thing that you will need is a web hosting plan that allows and supports the ability to run Python code. Since these usually cost money (and since not everyone even has a website), we’ll stick with a free alternative that is one of the simplest to set up: Google App Engine, which uses a web framework called webapp2.

There are a number of other alternatives (both free and paid) that are more customizable, and you can use webapp2 on its own later without relying on Google App Engine, but getting started with Google App Engine will be the quickest and easiest way to begin learning about web application development in Python.

Задача 2 – создание веб-приложения

Теперь, когда наш конвейер машинного обучения и модель готовы, мы начнем создавать веб-приложение, которое может подключаться к ним и генерировать прогнозы по новым данным в режиме реального времени. Есть две части этого приложения:

  1. front-end (разработанный с использованием HTML);
  2. back-end (разработан с использованием Flask в Python).

Интерфейс веб-приложения

Как правило, интерфейсные веб-приложения строятся с использованием HTML, который не является предметом данной статьи. Мы использовали простой HTML-шаблон и таблицу стилей CSS для разработки формы ввода. Вот HTML-фрагмент начальной страницы нашего веб-приложения.

Фрагмент кода: HTML-файл

Вам не нужно быть экспертом в HTML, чтобы создавать простые приложения. Существует множество бесплатных платформ, которые предоставляют шаблоны HTML и CSS, а также позволяют быстро создавать красивые HTML-страницы с помощью drag-and-drop интерфейса .

Таблица веб-стилей CSS

CSS (Cascading Style Sheets, каскадные таблицы стилей) – язык описания внешнего вида HTML-документов. Это эффективный способ управления макетом вашего приложения. Таблицы стилей содержат такую информацию, как цвет фона, размер и цвет шрифта, поля и т.д. Они сохраняются внешне как .css-файл и связаны с HTML, но включают в себя 1 строку кода.

Фрагмент кода: HTML-файл

Бэк-энд веб-приложения

Бэк-энд веб-приложения разрабатывается с использованием фреймворка Flask. Для начинающих интуитивно понятно рассматривать Flask как библиотеку, которую вы можете импортировать так же, как и любую другую библиотеку в Python. Смотрите пример фрагмента кода нашего бэк-энда, написанного с использованием фреймворка Flask на Python.

Фрагмент кода из файла app.py

Как вы помните из первой задачи, мы создали линейную регрессионную модель, обученную на 62 признаках, которые были автоматически спроектированы PyCaret. Однако на передней панели нашего веб-приложения есть форма ввода, которая собирает только шесть признаков: возраст, пол, индекс массы тела, дети, наличие вредных привычек (курение), регион.

Как мы преобразуем 6 признаков нового элемента данных в реальном времени в 62 признака, по которым была обучена модель? С последовательностью преобразований, применяемых во время обучения модели, кодирование становится все более сложной и трудоемкой задачей.

В PyCaret все преобразования – категориальное кодирование, масштабирование, условный расчет отсутствующих значений, проектирование признаков и даже выбор признаков – автоматически выполняются в режиме реального времени перед созданием прогнозов.

Представьте себе объем кода, который вам пришлось бы написать, чтобы применить все преобразования в строгой последовательности, прежде чем вы смогли бы использовать модель для прогнозов. На практике, когда речь идёт о машинном обучении, необходимо думать обо всем конвейере машинного обучения, а не только о модели.

Тестирование приложения

Один из последних шагов, предваряющий публикацию приложение на Heroku, — локальное тестирование веб-приложения. Откройте приглашение Anaconda и перейдите в папку, где сохраняется на вашем компьютере. Запустите файл Python с приведенным ниже кодом:

Вывод в Anaconda Prompt при выполнении app.py

После выполнения скопируйте URL-адрес в браузер: он должен открыть веб-приложение, размещенное на вашем локальном компьютере (127.0.0.1). Попробуйте ввести тестовые значения, чтобы проверить, работает ли функция прогнозирования. В приведенном ниже примере ожидаемый счет для 19-летней курильщицы без детей на юго-западе составляет 20 900 долларов.

Веб-приложение, открытое на локальном компьютере

Поздравляю! Вы только что создали свое первое приложение для машинного обучения. Теперь пришло время перенести это приложение с вашего локального компьютера в облако, чтобы другие люди могли использовать его с веб-URL.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *