Upgrade to Pro — share decks privately, control downloads, hide ads and more …

REST w Pyramidzie

Łukasz Oleś
January 16, 2013
56

REST w Pyramidzie

Łukasz Oleś

January 16, 2013
Tweet

Transcript

  1. Plik api/__init__.py from pyramid.config import Configurator def main(global_config, **settings): config

    = Configurator(settings=settings) config.add_route('completion', '/v1/{account}/{container}') config.scan() return config.make_wsgi_app() pserve development.ini
  2. Plik api/views.py from pyramid.view import view_config @view_config(route_name='completion', renderer='json', request_method='GET') def

    completion(request): account = request.matchdict['account'] container = request.matchdict['container'] query = request.params.get('term', u'') storage = get_storage(account) offers = storage.suggest(container, query)) return offers
  3. Plik api/views.py @view_config(route_name='completion', renderer='json', request_method='DELETE', permission='edit') def delete_container(request): container =

    request.matchdict['container'] account = request.matchdict['account'] storage = get_storage( account) storage.delete_container(container)
  4. Plik api/views.py @view_config(route_name='items', renderer='json', request_method='PUT', permission='edit') def add_item(request): container =

    request.matchdict['container'] account = request.matchdict['account'] item = request.matchdict['item'] storage = get_storage(account) storage.store_item(container, item)
  5. Colander http://docs.pylonsproject.org/projects/colander from colander import MappingSchema, SchemaNode, Int, String class

    City(MappingSchema): province = SchemaNode(String()) population = SchemaNode(Int())
  6. Plik api/views.py @view_config(route_name='items', renderer='json', request_method='PUT', permission='edit') def add_item(request): container =

    request.matchdict['container'] account = request.matchdict['account'] item = request.matchdict['item'] city = City() data = city.deserialize(request.json_body) storage = get_storage(account) storage.store_item(container, item, data)
  7. Plik api/__init__.py from api.auth import RootFactory, auth_check def main(global_config, **settings):

    config = Configurator(settings=settings, root_factory=RootFactory, authentication_policy= AuthenticationPolicy(auth_check))
  8. Plik api/__init__.py from pyramid.events import subscriber, NewResponse @subscriber(NewResponse) def add_access_list(event):

    event.response.headerlist.append( ('Access-Control-Allow-Origin', '*')) COSR – poziom zaawansowany