Skip to content

Commit

Permalink
Merge branch 'develop': v 1.2.2. Add original_request field to AliceR…
Browse files Browse the repository at this point in the history
…equest

Add some hints about testing and deployment into README
  • Loading branch information
mahenzon committed Nov 27, 2018
2 parents 39dfe01 + 143607f commit f142993
Show file tree
Hide file tree
Showing 9 changed files with 122 additions and 9 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,4 @@ venv.bak/

# mypy
.mypy_cache/
Pipfile*
37 changes: 37 additions & 0 deletions README-en.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,40 @@ async def handle_all_requests(alice_request):
### JSON serializing

If you want to use a faster json library, install [rapidjson](https://github.com/python-rapidjson/python-rapidjson) or [ujson](https://github.com/esnme/ultrajson), it will be detected and used automatically

___

### Skills using aioAlice

* [The Erundopel game](https://github.com/Goodsmileduck/erundopel)


___

### Testing and deployment


In all examples the next configuration is used:

```python
WEBHOOK_URL_PATH = '/my-alice-webhook/' # webhook endpoint

WEBAPP_HOST = 'localhost' # running on local machine
WEBAPP_PORT = 3001 # we can use any port that is not use by other apps
```

For testing purposes you can use [ngrok](https://ngrok.com/), so set webhook to `https://1a2b3c4d5e.ngrok.io/my-alice-webhook/` (endpoint has to be `WEBHOOK_URL_PATH`, because WebApp expects to get updates only there), post has to be `WEBAPP_PORT` (in this example it is 3001)


For production you can use Nginx, then edit Nginx configuration and add these lines inside the `server` block:

```
location /my-alice-webhook/ { # WEBHOOK_URL_PATH
proxy_pass http://127.0.0.1:3001/; # addr to reach WebApp, in this case it is localhost and port is 3001
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
```
37 changes: 37 additions & 0 deletions README-pypa.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,40 @@ async def handle_all_requests(alice_request):
### JSON serializing

If you want to use a faster json library, install [rapidjson](https://github.com/python-rapidjson/python-rapidjson) or [ujson](https://github.com/esnme/ultrajson), it will be detected and used automatically

___

### Skills using aioAlice

* [The Erundopel game](https://github.com/Goodsmileduck/erundopel)


___

### Testing and deployment


In all examples the next configuration is used:

```python
WEBHOOK_URL_PATH = '/my-alice-webhook/' # webhook endpoint

WEBAPP_HOST = 'localhost' # running on local machine
WEBAPP_PORT = 3001 # we can use any port that is not use by other apps
```

For testing purposes you can use [ngrok](https://ngrok.com/), so set webhook to `https://1a2b3c4d5e.ngrok.io/my-alice-webhook/` (endpoint has to be `WEBHOOK_URL_PATH`, because WebApp expects to get updates only there), post has to be `WEBAPP_PORT` (in this example it is 3001)


For production you can use Nginx, then edit Nginx configuration and add these lines inside the `server` block:

```
location /my-alice-webhook/ { # WEBHOOK_URL_PATH
proxy_pass http://127.0.0.1:3001/; # addr to reach WebApp, in this case it is localhost and port is 3001
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
```
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,40 @@ async def handle_all_requests(alice_request):
### JSON serializing

Если вы хотите использовать более быструю библиотеку для работы с JSON, установите [rapidjson](https://github.com/python-rapidjson/python-rapidjson) или [ujson](https://github.com/esnme/ultrajson). Библиотека определится и будет использована автоматически.

___

### Навыки с использованием aioAlice

* [Игра в Ерундопель](https://github.com/Goodsmileduck/erundopel)


___

### Тестирование и деплой


В примерах используется следующая конфигурация:

```python
WEBHOOK_URL_PATH = '/my-alice-webhook/' # webhook endpoint

WEBAPP_HOST = 'localhost' # запускаем на локальной машине
WEBAPP_PORT = 3001 # испльзуем любой не занятый порт
```

Для тестирования можно использовать [ngrok](https://ngrok.com/), тогда вебхук нужно будет установить на `https://1a2b3c4d5e.ngrok.io/my-alice-webhook/` (endpoint должен быть `WEBHOOK_URL_PATH`, так как WebApp ожидает получать обновления именно там), порт в настройках нужно указать `WEBAPP_PORT` (в данном случае 3001)


Для продакшена можно использовать Nginx, тогда в конфигурации Nginx внутри блока `server` необходимо добавить:

```
location /my-alice-webhook/ { # WEBHOOK_URL_PATH
proxy_pass http://127.0.0.1:3001/; # адрес до запущенного WebApp, в нашем случае это localhost и порт 3001
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
```
2 changes: 1 addition & 1 deletion aioalice/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


__version__ = '1.2.1'
__version__ = '1.2.2'
2 changes: 1 addition & 1 deletion aioalice/dispatcher/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ async def parse_request(self):
"""
data = await self.request.json()
try:
return AliceRequest(**data)
return AliceRequest(self.request, **data)
except Exception:
log.exception('Exception loading AliceRequest from\n%r', data)
raise
Expand Down
3 changes: 2 additions & 1 deletion aioalice/types/alice_request.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from attr import attrs, attrib
from aiohttp.web import Request as WebRequest
from aioalice.utils import ensure_cls
from . import AliceObject, Meta, Session, \
Card, Request, Response, AliceResponse
Expand All @@ -7,7 +8,7 @@
@attrs
class AliceRequest(AliceObject):
"""AliceRequest is a request from Alice API"""

original_request = attrib(type=WebRequest)
meta = attrib(convert=ensure_cls(Meta))
request = attrib(convert=ensure_cls(Request))
session = attrib(convert=ensure_cls(Session))
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
if sys.version_info < MINIMAL_PY_VERSION:
raise RuntimeError('aioAlice works only with Python {}+'.format('.'.join(map(str, MINIMAL_PY_VERSION))))

__version__ = '1.2.1'
__version__ = '1.2.2'


def get_description():
Expand Down
10 changes: 5 additions & 5 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def _test_alice_request(self, arq, dct):
self._test_meta(arq.meta, dct['meta'])

def _test_alice_request_from_dct(self, dct):
alice_request = types.AliceRequest(**dct)
alice_request = types.AliceRequest(None, **dct)
self._test_alice_request(alice_request, dct)

def test_alice_request(self):
Expand All @@ -215,23 +215,23 @@ def test_alice_response(self):
self._test_alice_response(alice_response, ALICE_RESPONSE_WITH_BUTTONS)

def test_response_from_request(self):
alice_request = types.AliceRequest(**ALICE_REQUEST)
alice_request = types.AliceRequest(None, **ALICE_REQUEST)

alice_response = alice_request.response(
EXPECTED_RESPONSE['response']['text']
)
self._assert_payload(alice_response, EXPECTED_RESPONSE)

def test_response_from_request2(self):
alice_request = types.AliceRequest(**ALICE_REQUEST)
alice_request = types.AliceRequest(None, **ALICE_REQUEST)
alice_response = alice_request.response(
RESPONSE_TEXT, tts=TTS,
buttons=[types.Button(BUTTON_TEXT, url=URL)]
)
self._assert_payload(alice_response, EXPECTED_RESPONSE_WITH_BUTTONS)

def test_response_big_image_from_request(self):
alice_request = types.AliceRequest(**ALICE_REQUEST)
alice_request = types.AliceRequest(None, **ALICE_REQUEST)
alice_response = alice_request.response_big_image(
RESPONSE_TEXT, IMAGE_ID, CARD_TITLE, CARD_DESCR,
types.MediaButton(BUTTON_TEXT, URL, MB_PAYLOAD),
Expand All @@ -240,7 +240,7 @@ def test_response_big_image_from_request(self):
self._assert_payload(alice_response, EXPECTED_ALICE_RESPONSE_BIG_IMAGE_WITH_BUTTON)

def test_response_items_list_from_request(self):
alice_request = types.AliceRequest(**ALICE_REQUEST)
alice_request = types.AliceRequest(None, **ALICE_REQUEST)
alice_response = alice_request.response_items_list(
RESPONSE_TEXT, CARD_HEADER_TEXT,
[types.Image(**IMAGE)],
Expand Down

0 comments on commit f142993

Please sign in to comment.