Created
May 17, 2018 21:03
-
-
Save pauleveritt/23384b71fcc84367950e4d5c7092d276 to your computer and use it in GitHub Desktop.
reg and custom views by docid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import reg | |
| from examples.request import Request | |
| class Document(object): | |
| def __init__(self, docid, text): | |
| self.docid = docid | |
| self.text = text | |
| @reg.dispatch( | |
| reg.match_instance('obj'), | |
| reg.match_key( | |
| 'request_method', | |
| lambda obj, request: request.request_method, | |
| fallback=lambda obj, request: 'GET', | |
| default='GET' | |
| ), | |
| reg.match_key( | |
| 'docid', | |
| lambda obj, request: obj.docid, | |
| fallback=lambda obj, request: obj.docid | |
| ) | |
| ) | |
| def view(obj, request): | |
| raise NotImplementedError | |
| @view.register(obj=Document) | |
| def document_all(obj, request): | |
| return "GET document text is: " + obj.text | |
| @view.register(obj=Document, request_method='POST') | |
| def document_post(obj, request): | |
| return "POST document text is: " + obj.text | |
| @view.register(obj=Document, docid='doc2') | |
| def document_custom_get(obj, request): | |
| return "CUSTOM document text is: " + obj.text | |
| if __name__ == '__main__': | |
| doc1 = Document('doc1', 'This is doc1') | |
| print(view(doc1, Request('GET'))) | |
| print(view(doc1, Request('POST'))) | |
| # Custom view for a specific document | |
| doc2 = Document('doc2', 'This is doc2') | |
| print(view(doc2, Request('GET'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment