Re: Media types with parameters (@cherrypy.tools.accept)
Michiel Overtoom <motoom-qWit8jRvyhVmR6Xm/[email protected]> Fri, 4 Aug 2017 19:17:48 +0200
| Newsgroups | gmane.comp.python.cherrypy |
|---|---|
| Message-ID | <[email protected]> |
Hi Aaron,
I hope the following code helps. The version number can be parsed out of the 'Accept' header which is available in the cherrypy.request.headers mapping.
import cherrypy
import re
class Root(object):
exposed = True
@cherrypy.tools.accept(media="mycompany/api")
def GET(self, id=None):
accept = cherrypy.request.headers.get("Accept")
version = None
if accept:
m = re.search(r".*version=(\d+).*", accept)
if m:
version = m.groups()[0]
return "Congratulations! You've done a GET with id: %r and API version %r" % (id, version)
conf = {
"/": {
"request.dispatch": cherrypy.dispatch.MethodDispatcher(),
},
}
cherrypy.quickstart(Root(), "/", conf)
(user@air) ~/Desktop $ curl -iv --header "Accept: mycompany/api; version=2" http://127.0.0.1:8080/?id=17
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> GET /?id=17 HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/7.43.0
> Accept: mycompany/api; version=2
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Date: Fri, 04 Aug 2017 17:14:38 GMT
Date: Fri, 04 Aug 2017 17:14:38 GMT
< Content-Length: 69
Content-Length: 69
< Content-Type: text/html;charset=utf-8
Content-Type: text/html;charset=utf-8
< Allow: GET, HEAD
Allow: GET, HEAD
< Server: CherryPy/3.8.0
Server: CherryPy/3.8.0
<
* Connection #0 to host 127.0.0.1 left intact
Congratulations! You've done a GET with id: u'17' and API version '2'
(user@air) ~/Desktop $ _
Greetings,
--
You received this message because you are subscribed to the Google Groups "cherrypy-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cherrypy-users+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
To post to this group, send email to cherrypy-users-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
Visit this group at https://groups.google.com/group/cherrypy-users.
For more options, visit https://groups.google.com/d/optout.