官术网_书友最值得收藏!

Application logic

Since our handler function is so simple, let's take a look at the application code to see what exactly is going on. Our coffee cupping API is fairly simple and only handles a single resource type at this point, a coffee cupping session object. Before moving forward, it's helpful to take a look at the shape of this resource type:

    {
"name": "Cupping session for Serverless Patterns",
"formName": "Modified SCAA",
"cuppings": [
{
"name": "Guatemala Huehuetenango",
"overallScore": "85.5",
"scores": {
"Aroma": 8.6,
"Body": 8,
"Flavor": 10
},
"notes": "This was pretty good",
"descriptors": ["woody", "berries"]
},
{
"name": "Ethiopia Yirgacheffe",
"overallScore": "90",
"scores": {
"Aroma": 8.6,
"Body": 8,
"Flavor": 10
},
"notes": "Nice",
"descriptors": ["blueberry"]
}
]
}

Much of the logic of this application is simply the transformation back and forth between JSON and database records. The actual application code isn't that important in the context of this book. If you'd like to learn more about the actual implementation, I encourage you to view the source code at https://github.com/brianz/serverless-design-patterns.

The logic in handler.py will delegate the API requests to the cupping/handlers/session.py file, which you can see in the following code. The purpose here is to service requests for a particular URL pattern (which is /session, /session/{id}) and particular HTTP verb (that is, GET, POST, DELETE) and execute the appropriate application code:

from schematics.exceptions import DataError

from .decorators import decode_json
from .helpers import (
create_session_from_json_payload,
prettify_schematics_errors,
)

from ..models import (
CuppingModel,
SessionModel,
)
from ..persistence import Session, queries
from ..exceptions import Http404, InvalidInputData


def get_sessions(data):
sessions = queries.get_sessions()
models = [SessionModel.from_row(s) for s in queries.get_sessions()]
return {'sessions': [m.to_native() for m in models]}


@decode_json
def create_session(json_payload):
if not json_payload or not hasattr(json_payload, 'get'):
return {'errors': ['Invalid input data']}

print('Creating session', json_payload)

try:
session = create_session_from_json_payload(json_payload)
print('Created session: %s' % (session.id, ))
response = {
'session': {
'id': session.id,
'name': session.name,
}
}
except InvalidInputData as e:
response = {'errors': e.errors}

return response


def _get_session_from_path_parameters(data):
try:
session_id = int(data.get('pathParameters', {}).get('id'))
except (AttributeError, TypeError, ValueError):
raise Http404('Invalid session id')

session = queries.get_session_by_id(session_id)
if session is None:
raise Http404('Invalid session id')

return session


def get_session(data):
print('Reading session', data)
session = _get_session_from_path_parameters(data)
model = SessionModel.from_row(session)
return {'session': model.to_native()}


def handle_session(http_method, payload):
method_map = {
'GET': get_sessions,
'POST': create_session,
}
method = http_method.upper()
return method_map[method](payload)


def handle_session_detail(http_method, payload):
method_map = {
'GET': get_session,
'DELETE': delete_session,
}
method = http_method.upper()
return method_map[method](payload)

The final two functions are the gateway into this part of our application, where HTTP verbs are mapped to different functions.

主站蜘蛛池模板: 柳林县| 鲁山县| 临沧市| 枞阳县| 华坪县| 彭山县| 临沂市| 南雄市| 茌平县| 年辖:市辖区| 醴陵市| 偃师市| 鄂尔多斯市| 明水县| 中超| 双牌县| 玉环县| 滕州市| 泰兴市| 永和县| 资中县| 萍乡市| 绿春县| 泸定县| 永清县| 泗水县| 桐柏县| 仁怀市| 奉贤区| 桓台县| 灵台县| 田林县| 磐石市| 馆陶县| 平湖市| 贞丰县| 景洪市| 南丹县| 珲春市| 阿拉善右旗| 兴宁市|