Skip to content

Commit

Permalink
Merge branch 'fix-improve-docs' of https://github.com/areski/cornice
Browse files Browse the repository at this point in the history
…into areski-fix-improve-docs

Conflicts:
	docs/source/quickstart.rst
	docs/source/validation.rst
  • Loading branch information
leplatrem committed Jun 16, 2015
2 parents 28667f2 + 9441b19 commit 2c65cb1
Show file tree
Hide file tree
Showing 12 changed files with 110 additions and 84 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Cornice:
* Andre Caron <andre.l.caron@gmail.com>
* Andreas Motl <andreas.motl@ilo.de>
* Anton D <anton@screwtop>
* Areski Belaid <areski@gmail.com>
* Ben Bangert <ben@groovie.org>
* Bruno Binet <bruno.binet@gmail.com>
* Bryan Zegar <bryanzegar@gmail.com>
Expand Down
Binary file modified docs/source/cornice.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/source/exhaustive_list.rst
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Exhaustive list of the validations provided by cornice
Exhaustive list of the validations provided by Cornice
######################################################

As you may have noticed, Cornice does some validation for you. This document
Expand Down
4 changes: 2 additions & 2 deletions docs/source/internals.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Cornice internals
#################

Internally, cornice doesn't do a lot of magic. The logic is mainly split in two
Internally, Cornice doesn't do a lot of magic. The logic is mainly split in two
different locations: the `services.py` module and the `pyramid_hook.py` module.

That's important to understand what they are doing in order to add new features
Expand All @@ -12,7 +12,7 @@ The Service class

The cornice.service.Service class is a container for all the definition
information for a particular service. That's what you use when you use the
cornice decorators for instance, by doing things like
Cornice decorators for instance, by doing things like
`@myservice.get(**kwargs)`. Under the hood, all the information you're passing
to the service is stored in this class. Into other things you will find there:

Expand Down
30 changes: 22 additions & 8 deletions docs/source/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,15 @@ to include cornice in your project `includeme`::

config.include("cornice")

You can then start to poke at the :file:`views.py` file it
created in the package.
You can then start poking at the :file:`views.py` file that
has been created.

For example, let's
define a service where you can **GET** and **POST** a value at
**/values/{value}**, where *value* is an ascii value representing the
For example, let's define a service where you can **GET** and **POST** a value
at **/values/{value}**, where *value* is an ascii value representing the
name of the value.

The :file:`views` module can look like this::

import json
from cornice import Service

values = Service(name='foo', path='/values/{value}',
Expand All @@ -56,10 +54,26 @@ The :file:`views` module can look like this::
"""
key = request.matchdict['value']
try:
_VALUES[key] = json.loads(request.body)
# json_body is JSON-decoded variant of the request body
_VALUES[key] = request.json_body
except ValueError:
return False
return True


By default, Cornice uses a Json renderer.
.. note::

By default, Cornice uses a Json renderer.


Run your Cornice application with::

$ pserve project.ini --reload


Set a key-value using Curl::

$ curl -X POST http://localhost:6543/values/foo -d '{"a": 1}'


Check out what is stored in a foo values, open http://localhost:6543/values/foo
15 changes: 11 additions & 4 deletions docs/source/resources.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ registered as handlers for the appropriate methods / services.
Here is how you can register a resource::

from cornice.resource import resource, view

_USERS = {1: {'name': 'gawel'}, 2: {'name': 'tarek'}}

@resource(collection_path='/users', path='/users/{id}')
class User(object):
Expand All @@ -17,14 +18,20 @@ Here is how you can register a resource::
self.request = request

def collection_get(self):
return {'users': USERS.keys()}
return {'users': _USERS.keys()}

@view(renderer='json')
def get(self):
return USERS.get(int(self.request.matchdict['id']))
return _USERS.get(int(self.request.matchdict['id']))

@view(renderer='json', accept='text/json')
def collection_post(self):
print(self.request.json_body)
_USERS[len(_USERS) + 1] = self.request.json_body
return True

As you can see, you can define methods for the collection (it will use the
**path** argument of the class decorator. When defining collection_* methods, the
**path** argument of the class decorator. When defining collection_* methods, the
path defined in the **collection_path** will be used.

validators and filters
Expand Down
20 changes: 10 additions & 10 deletions docs/source/sphinx.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ The directive has the following options:
than `services`. **optional**
- **ignore**: a comma separated list of services names to ignore. **optional**

You can use info fields (see
You can use info fields (see
`Info field lists <http://sphinx.pocoo.org/domains.html#info-field-lists>`_)
in your functions, methods and validators.

Expand All @@ -68,7 +68,6 @@ Here's the **full** app::

from cornice import Service
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPNotFound
import string

desc = """\
Expand All @@ -81,7 +80,7 @@ Here's the **full** app::
def check_quote(request):
"""Makes sure the quote starts with a majuscule and ends with a dot"""
quote = request.body
if quote[0] not in uppercase:
if quote[0] not in string.ascii_uppercase:
request.errors.add('body', 'quote', 'Does not start with a majuscule')

if quote[-1] not in ('.', '?', '!'):
Expand All @@ -91,19 +90,20 @@ Here's the **full** app::
request.validated['quote'] = quote


_quote = "Not set, yet !"
_quote = {}
_quote['default'] = "Not set, yet !"


@quote.get()
def get_quote(request):
"""Returns the quote"""
return _quote
return _quote['default']


@quote.post(validator=check_quote)
def post_quote(request):
"""Update the quote"""
global _quote
_quote = request.validated['quote']
_quote['default'] = request.validated['quote']


def main(global_config, **settings):
Expand All @@ -115,12 +115,12 @@ Here's the **full** app::
if __name__ == '__main__':
from wsgiref.simple_server import make_server
app = main({})
httpd = make_server('', 8000, app)
print "Listening on port 8000...."
httpd = make_server('', 6543, app)
print("Listening on port 6543....")
httpd.serve_forever()


And here's the **full** sphinx doc example::
And here's the **full** Sphinx doc example::

Welcome to coolapp's documentation!
===================================
Expand Down
4 changes: 2 additions & 2 deletions docs/source/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ Testing
=======

Testing is nice and useful. Some folks even said it helped saving kittens. And
childs. Here is how you can test your cornices applications.
childs. Here is how you can test your Cornice's applications.

Let's suppose you have this service definition::


from pyramid.config import Configurator

from cornice import Service
Expand Down
51 changes: 33 additions & 18 deletions docs/source/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Setting up the development environment

To create this application, we'll use Python 2.7. Make sure you
have it on your system, then install **virtualenv** (see
http://pypi.python.org/pypi/virtualenv.)
http://pypi.python.org/pypi/virtualenv).

Create a new directory and a virtualenv in it::

Expand All @@ -65,7 +65,17 @@ application::
Copying +package+.ini_tmpl to <...path ...>/messaging/messaging.ini
Copying README.rst_tmpl to <...path ...>/messaging/README.rst
Copying setup.py_tmpl to <...path ...>/messaging/setup.py

===============================================================================
Tutorials: http://docs.pylonsproject.org/projects/pyramid_tutorials
Documentation: http://docs.pylonsproject.org/projects/pyramid

Twitter (tips & updates): http://twitter.com/pylons
Mailing List: http://groups.google.com/group/pylons-discuss

Welcome to Pyramid. Sorry for the convenience.
===============================================================================


Once your application is generated, go there and call *develop* against it::

Expand All @@ -80,16 +90,29 @@ service check::
Starting server in PID 7618.
serving on 0.0.0.0:6543 view at http://127.0.0.1:6543

Once the application is running, visit http://127.0.0.1:6543 in your browser or
Curl and make sure you get::
Once the application is running, visit http://127.0.0.1:6543 in your browser and make sure you get::

{'Hello': 'World'}

You should also get the same results calling the URL via Curl::

$ curl -i http://0.0.0.0:6543/

This will result::

HTTP/1.1 200 OK
Content-Length: 18
Content-Type: application/json; charset=UTF-8
Date: Tue, 12 May 2015 13:23:32 GMT
Server: waitress

{"Hello": "World"}


Defining the services
---------------------

Let's open the file in messaging/views.py, it contains all the Services::
Let's open the file in :file:`messaging/views.py`, it contains all the Services::

from cornice import Service

Expand Down Expand Up @@ -182,16 +205,14 @@ Here's their code::

def valid_token(request):
header = 'X-Messaging-Token'
token = request.headers.get(header)
if token is None:
htoken = request.headers.get(header)
if htoken is None:
raise _401()

token = token.split('-')
if len(token) != 2:
try:
user, token = htoken.split('-', 1)
except ValueError:
raise _401()

user, token = token

valid = user in _USERS and _USERS[user] == token
if not valid:
raise _401()
Expand All @@ -209,14 +230,8 @@ Here's their code::


#
# Services
# Services - User Management
#

#
# User Management
#


@users.get(validators=valid_token)
def get_users(request):
"""Returns a list of all users."""
Expand Down

0 comments on commit 2c65cb1

Please sign in to comment.