Git Product home page Git Product logo

yappa's Introduction

Yappa: Serverless Python for Yandex Cloud Functions

⚠️ 26.07.2021: Актуальная версия проекта - в форке https://github.com/turokg/yappa


Деплоим Python в Yandex Cloud Functions легко и быстро.

Демо

Первый запуск

1. Настраиваем CLI

Для начала нужно скачать и настроить два CLI: яндексовский и амазоновский.

2. Ставим yappa и flask

pip install yappa
pip install flask

3. Создаем Flask-приложение

from yappa.flask_yandex import FlaskYandex

app = FlaskYandex(__name__)


@app.route('/')
def main():
    return 'Hello from Yappa!'

4. Фиксируем requirements

pip freeze > requirements.txt

5. Деплоим

Инициализация и создание конфиг-файла:

yappa init

Деплой:

yappa deploy

Профит! Яндекс выдаст URL вида https://functions.yandexcloud.net/xxxxx, на котором будет работать наша функция.

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

Обновление функции

После первого деплоя обновление функции выполняется командой:

yappa update

Просмотр логов

yappa logs

Команда принимает два необязательных параметра --since и --until (синтаксис см. здесь). Например, так можно просмотреть логи за последнюю минуту:

yappa logs --since 1m

Удаление функции

yappa undeploy

Это удалит функцию из YCF.

Ограничения

Ограничения Яндекса

В одном облаке не может быть более 10 функций. Все ограничения см. здесь

Только один роут Flask

Единственный URL, который может быть у приложения, выглядит так:

https://functions.yandexcloud.net/xxxxxx

В отличие от AWS Lambda, здесь нет возможности создавать роуты, например:

https://functions.yandexcloud.net/xxxxxx/dashboard
https://functions.yandexcloud.net/xxxxxx/users

Поэтому единственный роут, который может быть у вашего Flask-приложения, - это /:

@app.route('/', methods=[...])

И весь роутинг внутри приложения необходимо делать на GET-параметрах:

from flask import request, render_template

@app.route('/', methods=[...])
def main:
    if request.args.get('dashboard'):
        return render_template('dashboard.html')
    elif request.args.get('user'): 
        return render_template('user.html')
    ...        

Разработка навыков для Алисы

Yappa позволяет деплоить можно не только Flask-приложения, но и обычные функции из документации.

Именно такие функции и используются в Алисе.

Для создания навыка Алисы можно написать такую функцию:

def handler(event, context):
    """
    Entry-point for Serverless Function.
    :param event: request payload.
    :param context: information about current execution context.
    :return: response to be serialized as JSON.
    """
    text = 'Hello! I\'ll repeat anything you say to me.'
    if 'request' in event and \
            'original_utterance' in event['request'] \
            and len(event['request']['original_utterance']) > 0:
        text = event['request']['original_utterance']
    return {
        'version': event['version'],
        'session': event['session'],
        'response': {
            # Respond with the original request or welcome the user if this is the beginning of the dialog and the request has not yet been made.
            'text': text,
            # Don't finish the session after this response.
            'end_session': 'false'
        },
    }

и деплоить его точно так же командами yappa init / yappa deploy.

При деплое функции, а не Flask-приложения, необходимо изменить файл yappa-settings.json так, чтобы поле entrypoint указывало на эту функцию, например:

{
    "project_name": "messageboard-yandex2",
    "entrypoint": "myapp.handler",
    ...
}


Благодарности

Проект представляет собой смесь Flask-Lambda и Zappa, адаптированных под особенности YCF.

Если что-то не работает

Проект тестировался только по Mac OS. Если что-то не работает под Windows/Linux - присылайте PR.

yappa's People

Contributors

kurtgn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

yappa's Issues

Не отрабатывает деплой

Добрый день!

Никак не могу понять, почему информацию о профиле get_s3_resource не получает?

  File "~/yappa-test/venv/lib/python3.8/site-packages/yappa/deploy.py", line 17, in get_s3_resource
    profile = config['profiles'][profile_name]
KeyError: None

Пробовал дебажить:

def get_s3_resource(profile_name):
    session = BotocoreSession()
    print(session)
    config = session.full_config
    print(config)

Выдает:

<botocore.session.Session object at 0x1090394f0>
{'profiles': {}}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.