Python.
И веб-разработка.



Что это?
Веб-разработка

Составные части


Фронтенд


HTML
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
</body>
</html>

CSS
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}

JavaScript
function myFunction() {
var x = document.getElementById("form");
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("output").innerHTML = text;
}

Подходы к организации web-приложений
- Отдельные ресурсы для каждого адреса
- Single-page applications (SPA)

Популярные js-библиотеки
- Angular JS
- ReactJS
- Миллион других

Темная сторона бекенда
Почему Python?

Темная сторона бекенда
"Чистый" Python или фреймворк?

Что должен уметь бекенд
- Бизнес-логика приложения, работа с базой данных
- Входные точки - обработка HTTP запросов
- Подготовка ответа - сериализованные данные (JSON) или server-side шаблонизация
- Авторизация
- Кеширование, логирование, отказоустойчивость, производительность

Python web-фреймворки
- Django
- Flask
- Bottle
- Tornado
- Многие другие

WSGI
https://www.python.org/dev/peps/pep-0333/


Bottle
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(host='localhost', port=8080)


Flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()


Tornado
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()


MVC


Django
- ORM, абстракция над несколькими RDBMS
- Аутентификация, сессии
- Авторизация
- Роутинг
- Шаблоны
- Миграции
- Админка
- Формы
- Интернациолизация и локализация
- Кеширование
- Многое другое


WSGI-совместимые веб-серверы
- Gunicorn
- uWSGI
- Chaussette

Python и real-time web




Зачем?



Как доставить контент моментально?
- Long-polling
- XHR-streaming
- Eventsource (SSE)
- Websockets


Библиотеки-полифиллы


Если на бекенде Python
- Асинхронный фреймворк (Tornado, Asyncio)
- Gevent - патчим стандартную библиотеку
- Nginx-push-stream module
- Hosted-сервер c API (LightStreamer, Centrifugo)
- Облачный сервис с API (pusher.com, pubnub.com)
- Django-channels




Схема работы


Использование в браузере


Особенности
- Информация о подключениях в канале
- События подписки на канал/отписки от канала
- История сообщений в канале
- Восстановление пропущенных сообщений
- Разные типы каналов
- Масштабирование с помощью Redis
- Метрики
- Административный веб-интерфейс
- RPM и DEB пакеты, Docker-контейнер

API и клиентские библиотеки
- Клиентские - браузер, Android, iOS
- HTTP API - Python, PHP, Go, NodeJS, Ruby

Ссылки
- Код - https://github.com/centrifugal/centrifugo
- Документация
- Демо-инстанс на Heroku (пароль demo)

Спасибо!
Python_12
By Emelin Alexander
Python_12
- 1,022