def documentation_view(request): docs = [] for klass in handlers.__dict__.values(): if isinstance(klass, type) and issubclass(klass, BaseHandler): doc = generate_doc(klass) if doc.get_resource_uri_template(): doc.useful_methods = [m for m in doc.get_all_methods() if m.get_doc()] if hasattr(klass, 'example_args'): args = klass.example_args example_url = doc.get_resource_uri_template() for arg, value in args.items(): example_url = example_url.replace('{%s}' % arg, str(value)) doc.example_url = example_url+'query.yaml' doc.example_result = client.get(doc.example_url).content doc.uri_template = doc.get_resource_uri_template() docs.append(doc) elif hasattr(klass, 'example_uri'): doc = generate_doc(klass) example_url = klass.example_uri doc.example_url = example_url+'query.yaml' doc.example_result = client.get(doc.example_url).content doc.uri_template = klass.example_uri_template docs.append(doc) docs.sort(key=lambda doc: doc.uri_template) t = loader.get_template('documentation.txt') rst = t.render(Context({'docs': docs, 'API_BASE': API_BASE})) return HttpResponse(rst, mimetype='text/plain')
def generate_documentation(request): docs = [] for handler in (ProjectHandler, ReleaseHandler): doc = generate_doc(handler) docdic = { "name": doc.name, "model": doc.get_model(), # "uri": doc.resource_uri_template(), "methods": [], } methods = doc.get_methods() for method in methods: # print dir(method) methoddic = {"name": method.name, "sig1": method.signature, "doc": method.get_doc()} sig = "" for argn, argdef in method.iter_args(): sig += argn if argdef: sig += "=%s" % argdef sig += ", " sig = sig.rstrip(", ") methoddic["sig2"] = sig docdic["methods"].append(methoddic) docs.append(docdic) return render_to_response("api/doc.html", {"docs": docs}, context_instance=RequestContext(request))
def describe_handler(handler): """Return a serialisable description of a handler. :type handler: :class:`OperationsHandler` or :class:`AnonymousOperationsHandler` instance or subclass. """ # Want the class, not an instance. if isinstance(handler, BaseHandler): handler = type(handler) path = generate_doc(handler).resource_uri_template path = "" if path is None else path resource_uri = getattr(handler, "resource_uri", lambda: ()) view_name, uri_params, uri_kw = merge(resource_uri(), (None, (), {})) assert uri_kw == {}, ( "Resource URI specifications with keyword parameters are not yet " "supported: handler=%r; view_name=%r" % (handler, view_name)) return { "actions": list(describe_actions(handler)), "doc": getdoc(handler), "name": handler.__name__, "params": uri_params, "path": path, }
def generate_piston_documentation(app, docname, source): e = re.compile(r"^\.\. piston_handlers:: ([\w\.]+)$") old_source = source[0].split("\n") new_source = old_source[:] for line_nr, line in enumerate(old_source): m = e.match(line) if m: module = m.groups()[0] try: __import__(module) except ImportError: pass else: new_lines = [] for handler in handler_tracker: doc = generate_doc(handler) new_lines.append(doc.name) new_lines.append("-" * len(doc.name)) new_lines.append('::\n') new_lines.append('\t' + doc.get_resource_uri_template() + '\n') new_lines.append('Accepted methods:') for method in doc.allowed_methods: new_lines.append('\t* ' + method) new_lines.append('') if doc.doc: new_lines.append(doc.doc) new_source[line_nr:line_nr+1] = new_lines source[0] = "\n".join(new_source) return source
def generate_piston_documentation(app, docname, source): e = re.compile(r"^\.\. piston_handlers:: ([\w\.]+)$") old_source = source[0].split("\n") new_source = old_source[:] for line_nr, line in enumerate(old_source): m = e.match(line) if m: module = m.groups()[0] try: __import__(module) except ImportError: pass else: new_lines = [] for handler in handler_tracker: doc = generate_doc(handler) new_lines.append(doc.name) new_lines.append("-" * len(doc.name)) new_lines.append('::\n') new_lines.append('\t' + doc.get_resource_uri_template() + '\n') new_lines.append('Accepted methods:') for method in doc.allowed_methods: new_lines.append('\t* ' + method) new_lines.append('') if doc.doc: new_lines.append(doc.doc) new_source[line_nr:line_nr + 1] = new_lines source[0] = "\n".join(new_source) return source
def pca_index(request): context = { 'form': TagForm(), 'title': TagJobHandler.name, 'domain': get_platrom_url(request), 'hanlder_doc': generate_doc(TagJobHandler) } return TemplateResponse(request, 'pca.html', context)
def handle_noargs(self, **options): h_doc = generate_doc(LocationHandler) print "handler: ", h_doc.name print "model: ", h_doc.handler.model print "resource_uri", h_doc.resource_uri_template print "methods --" for m in h_doc.get_methods(): print " %s(%s)" % (m.name, m.signature)
def documentation(handler): """Return dict with documentation on handler. Intended for injection into the handler's answer. """ result = {} doc = generate_doc(handler) result['name'] = doc.name result['description'] = doc.doc return result
def documentation_view(request): """ Generic documentation view. Generates documentation from the handlers you've defined. """ docs = [ ] issuedoc = generate_doc(IssueList) issuedoc.url = reverse("api_sort_order", args=["new"]) docs.append(issuedoc) tagcloud = generate_doc(TagCloudHandler) tagcloud.url = reverse("api_tagcloud") docs.append(tagcloud) for handler, (model, anonymous) in typemapper.iteritems(): docs.append(generate_doc(handler)) def _compare( doc1 , doc2 ): return cmp(doc1.name, doc2.name) docs.sort(_compare) return render_to_response('documentation.html', { 'docs': docs }, RequestContext(request))
def documentation_view(request): """ Generic documentation view. Generates documentation from the handlers you've defined. """ docs = [] issuedoc = generate_doc(IssueList) issuedoc.url = reverse("api_sort_order", args=["new"]) docs.append(issuedoc) tagcloud = generate_doc(TagCloudHandler) tagcloud.url = reverse("api_tagcloud") docs.append(tagcloud) for handler, (model, anonymous) in typemapper.iteritems(): docs.append(generate_doc(handler)) def _compare(doc1, doc2): return cmp(doc1.name, doc2.name) docs.sort(_compare) return render_to_response('documentation.html', {'docs': docs}, RequestContext(request))
def doc_view(request): ''' Generates API's documentation for logged users. @param request: ''' import sys module = sys.modules[__name__] docs = [] logging.warning('Module %s' % module) for k, v in module.__dict__.items(): if isinstance(v, Resource): doc = generate_doc(type(v.handler)) logging.warning('Doc: %s' % doc.__dict__) docs.append(doc) return {'docs': docs}
def generate_api_docs(resources): """Generate ReST documentation objects for the ReST API. Yields Piston Documentation objects describing the given resources. This also ensures that handlers define 'resource_uri' methods. This is easily forgotten and essential in order to generate proper documentation. :return: Generates :class:`piston.doc.HandlerDocumentation` instances. """ sentinel = object() for resource in resources: handler = type(resource.handler) if getattr(handler, "resource_uri", sentinel) is sentinel: raise AssertionError("Missing resource_uri in %s" % handler.__name__) yield generate_doc(handler)
def generate_api_docs(resources): """Generate ReST documentation objects for the ReST API. Yields Piston Documentation objects describing the given resources. This also ensures that handlers define 'resource_uri' methods. This is easily forgotten and essential in order to generate proper documentation. :return: Generates :class:`piston.doc.HandlerDocumentation` instances. """ sentinel = object() for resource in resources: handler = type(resource.handler) if getattr(handler, "resource_uri", sentinel) is sentinel: raise AssertionError( "Missing resource_uri in %s" % handler.__name__) yield generate_doc(handler)
def get_handlers(): handler_path = '%s.%s' % (settings.API_MODULE, settings.API_HANDLER) handler_class = __import__(handler_path, fromlist = [settings.API_HANDLER]) handlers = [] for name, obj in inspect.getmembers(handler_class): if inspect.isclass(obj) and issubclass(obj, BaseHandler) and obj is not BaseHandler: uri = obj.resource_uri() doc = generate_doc(obj) if doc.resource_uri_template is None: urls = return_urls(obj) else: urls = [doc.resource_uri_template] handlers.append({'name': name, 'handler': obj, 'urls': urls}) return handlers
def documentation(request): """ Generic documentation view. Generates documentation from the handlers you've defined. """ docs = [ ] for handler in handler_tracker: doc = generate_doc(handler) setattr(doc,'type', handler.type) docs.append(doc) def _compare(doc1, doc2): #handlers and their anonymous counterparts are put next to each other. name1 = doc1.name.replace("Anonymous", "") name2 = doc2.name.replace("Anonymous", "") return cmp(name1, name2) #docs.sort(_compare) return render_to_response('api_doc.html', { 'docs': docs }, RequestContext(request))
def documentation_view(request): """ Generic documentation view. Generates documentation from the handlers you've defined. """ docs = [ ] handlers = [ParliamentHandler, ParliamentSessionHandler, TagHandler, SpeechHandler] for handler in handlers: docs.append(generate_doc(handler)) # docs = [generate_doc(ParliamentHandler)] import pdb; pdb.set_trace() def _compare(doc1, doc2): #handlers and their anonymous counterparts are put next to each other. name1 = doc1.name.replace("Anonymous", "") name2 = doc2.name.replace("Anonymous", "") return cmp(name1, name2) docs.sort(_compare) return render_to_response('api/documentation.html', { 'docs': docs }, RequestContext(request))
def create(self, request): """Add a new device location.""" attrs = self.flatten_dict(request.POST) try: device = Device.objects.get(user=request.user, name=attrs['device_name'], mobile_id=attrs['device_id']) except Device.DoesNotExist: return rc.NOT_FOUND gmaps = GoogleMaps() try: address = gmaps.latlng_to_address(float(attrs['lat']), float(attrs['lon'])) except GoogleMapsError: address = None device_location = DeviceLocation(device=device, address=address, lat=float(attrs['lat']), lon=float(attrs['lon']), created=datetime.datetime.now()) device_location.save() return rc.CREATED doc = generate_doc(DeviceLocationHandler)
from piston.doc import generate_doc from .handlers import * session_doc = generate_doc(SessionHandler) concept_doc = generate_doc(ConceptHandler) encounter_doc = generate_doc(EncounterHandler) obs_doc = generate_doc(ObservationHandler) procedure_doc = generate_doc(ProcedureHandler) subj_doc = generate_doc(SubjectHandler)
##Handling the request for APIs class DateHandler(BaseHandler): allowed_methods = ("GET",) model = Tax_transaction def read(self, request, year=1111, month=11, day=11): if year and month and day: date1 = datetime.date(int(year), int(month), int(day)) setquer = Tax_transaction.objects.filter(date=date1) return setquer else: return Tax_transaction.objects.all() doc = generate_doc(TaxHandler) print doc.name # print doc.model methods = doc.get_methods() for method in methods: print method.name # -> 'read' print method.signature # -> 'read(post_slug=<optional>)' sig = "" for argn, argdef in method.iter_args(): sig += argn
from piston.handler import handler_tracker from django.template import RequestContext from piston.doc import generate_doc from django.shortcuts import render_to_response def documentation(request): """ Generic documentation view. Generates documentation from the handlers you've defined. """ docs = [ ] for handler in handler_tracker: doc = generate_doc(handler) setattr(doc,'type', handler.type) docs.append(doc) def _compare(doc1, doc2): #handlers and their anonymous counterparts are put next to each other. name1 = doc1.name.replace("Anonymous", "") name2 = doc2.name.replace("Anonymous", "") return cmp(name1, name2) #docs.sort(_compare) return render_to_response('api_doc.html', { 'docs': docs }, RequestContext(request)) from piston.doc import generate_doc DocHandler = generate_doc(TextPreEditHandler)
def read(self, request): return {} def create(self, request): """Add a new device location.""" attrs = self.flatten_dict(request.POST) try: device = Device.objects.get(user=request.user, name=attrs['device_name'], mobile_id=attrs['device_id']) except Device.DoesNotExist: return rc.NOT_FOUND gmaps = GoogleMaps() try: address = gmaps.latlng_to_address(float(attrs['lat']), float(attrs['lon'])) except GoogleMapsError: address = None device_location = DeviceLocation(device=device, address=address, lat=float(attrs['lat']), lon=float(attrs['lon']), created=datetime.datetime.now()) device_location.save() return rc.CREATED doc = generate_doc(DeviceLocationHandler)