Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to py3, aiohttp #16

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*
!static/*
!*.py
!requirements.txt
7 changes: 7 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM python:3.10
WORKDIR /
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
ENTRYPOINT ["python3", "app.py"]
2 changes: 1 addition & 1 deletion Procfile
Original file line number Diff line number Diff line change
@@ -1 +1 @@
web: gunicorn app:app
web: python app.py
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
Если вам нравится проделанная работа и вы хотите внести свою лепту - помогите проекту OpenCorpora,
это совсем не сложно.

# Веб-сервис

## Веб-сервис

Проект [запущен на Heroku](http://pyphrasy.herokuapp.com/), и имеет API на http://pyphrasy.herokuapp.com/inflect.
Ожидаю запрос с двумя параметрами:
Expand Down Expand Up @@ -50,13 +49,12 @@

2. Установить зависимости

$ pip install -r requirements.txt

$ pip install -r requirements.txt

3. Запустить сервис через gunicorn
3. Запустить сервис


$ gunicorn app:app
$ python app.py

4. Проверить работоспособность

Expand All @@ -73,4 +71,9 @@

- [исправлен](https://github.com/summerisgone/pyphrasy/pull/13) `pip install`
- настроен CI
- обновлены зависимости
- обновлены зависимости

### 1.0.0

- Переход на python3
- Замена Flask + gunicorn на aiohttp
52 changes: 30 additions & 22 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,47 @@
# -*- coding: utf-8 -*-
import json
from os.path import dirname, join

import pymorphy2
from flask import Flask, request, render_template
from aiohttp import web
from aiohttp.web_response import Response
from multidict import MultiDictProxy

from inflect import PhraseInflector, GRAM_CHOICES

app = Flask(__name__)
app.debug = True
PROJECT_ROOT = dirname(__file__)
routes = web.RouteTableDef()

@app.route("/")
def index():
return render_template('index.html')

@app.route("/inflect", methods=['GET', 'POST'])
def inflect():
if request.method == 'POST':
params = request.form
else:
params = request.args
@routes.post('/inflect')
async def post_handler(request: web.Request):
params = await request.post()
return _inflect(params)

if 'phrase' not in params:
return u'укажите слово', 400, {'Content-Type':'text/plain; charset=utf-8'}
if 'forms' not in params and 'cases' not in params :
return u'выберите падежи или/и числа', 400, {'Content-Type':'text/plain; charset=utf-8'}

phrase = params['phrase']
form_sets = params.getlist('forms') if params.getlist('forms') else params.getlist('cases')
@routes.get('/inflect')
async def get_handler(request: web.Request):
params = request.query
return _inflect(params)


def _inflect(params: MultiDictProxy) -> Response:
if 'phrase' not in params:
web.json_response({'error': 'укажите слово'}, status=400)
if 'forms' not in params and 'cases' not in params:
web.json_response({'error': 'выберите падежи или/и числа'}, status=400)
phrase = params['phrase']
form_sets = params.getall('forms') if params.getall('forms') else params.getall('cases')
morph = pymorphy2.MorphAnalyzer()
inflector = PhraseInflector(morph)
result = {'orig': phrase}
for forms_string in form_sets:
form_set = set(forms_string.split(',')) & set(GRAM_CHOICES)
result[forms_string] = inflector.inflect(phrase, form_set)
return json.dumps(result), 200, {'Content-Type':'text/json; charset=utf-8'}
return web.json_response(result)


if __name__ == "__main__":
app.run()
if __name__ == '__main__':
app = web.Application()
app.router.add_routes(routes)
app.add_routes([web.static('/', join(PROJECT_ROOT, 'static'))])
web.run_app(app, port=8000)
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pymorphy2 >=0.9,<0.10
Flask >=1.1,<1.2
gunicorn >=19,<=20
aiohttp >=3.8,<3.9
11 changes: 3 additions & 8 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def recursive(root):
long_description=readme,

# technical info
version='0.2.0',
version='1.0.0',
packages=['pyphrasy'],
provides=['pyphrasy'],
package_dir={'pyphrasy': '.'},
package_data={'pyphrasy': recursive('./static')+recursive('./templates')+['README.md']},
package_data={'pyphrasy': recursive('./static')+['README.md']},

# testing
cmdclass={'test': PyTest},
Expand All @@ -62,13 +62,8 @@ def recursive(root):
'Intended Audience :: Information Technology',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.9',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Software Development :: Libraries :: Python Modules',
],
Expand Down
6 changes: 3 additions & 3 deletions templates/index.html → static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Склонение по падежам русских словосочетаний библиотека и онлайн-сервис</title>
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/main.css">
</head>
<body class="container">
<a href="https://github.com/summerisgone/pyphrasy"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
Expand Down Expand Up @@ -40,7 +40,7 @@ <h2>(на основе <a href="https://pymorphy2.readthedocs.org/">pymorphy2</a
<input class="btn btn-primary" type="submit"/>
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/static/js/main.js"></script>
<script type="text/javascript" src="/js/main.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
Expand Down