Пример #1
0
def eventsummary(request):
    response = HttpResponse()
    
    # get genes out of request
    try:
        genes = [int(g) for g in request.GET['genes'].split(',')]
    except (KeyError, ValueError):
        genes = None
    
    # get abstracts
    query = request.GET.get('q')
    if query:
        abstracts = get_abstracts(query)
    else:
        abstracts = None
        
    # get gene combinations
    try:
        outergenes = get_gene_combinations(genes=genes, abstracts=abstracts)
    except KeyError:
        # error if no gene or abstracts
        json.dump({'validresult': False, 'errormsg': 'You must supply either genes or a keyword query'}, response)
        return response
    
    # get sorter function from request
    orderby = request.GET.get('orderby', 'abstracts').lower()    
    sorter = {'abstracts': lambda g: -g.count, 'symbol': lambda g: g.symbol}[orderby]

    # sort data structure before rendering it
    outergenes_sorted = []
    for og in sorted(outergenes.values(), key=sorter):
        og.innergenes.sort(key=sorter)
        outergenes_sorted.append(og)
   
    # apply limit
    try:
        limit = int(request.GET.get('limit'))
        outergenes_sorted = outergenes_sorted[:limit]
    except (TypeError, ValueError):
        pass
   
    # render and return JSON response
    if outergenes_sorted:
        json.dump({'validresult': True, 
            'result': render_to_string("eventsummary.html", 
            {'outergenes': outergenes_sorted, 'genes': genes, 'orderby': orderby})}, response)
    else:
        json.dump({'validresult': False, 'errormsg': 'No genes found'}, response)
    return response
Пример #2
0
def eventlist(request):
    """Find and return events matching a query"""
    
    maxlimit = 500 # maximum number of events to fetch at once
    
    # get genes out of request.  First check for internal gene ids, then entrez
    # ids, then gene symbols.
    try:
        genes = [int(g) for g in request.GET['genes'].split(',')]
    except (KeyError, ValueError):
        try:
            gene_eids = [int(i.strip()) for i in request.GET['gene_entrez_ids'].split(',') if i != '']
            genes = [g.id for g in Gene.objects.filter(entrez_id__in=gene_eids)]
            
            # workaround for database mess
            if genes == []:
                raise Http404
        except (KeyError, ValueError):
            try:
                genes = [g.id for g in gene_lookup(request.GET['gene_symbols'])]
            except (KeyError, ValueError):
                genes = None
        
    # get abstracts
    query = request.GET.get('q')
    if query:
        abstracts = get_abstracts(query)
    else:
        abstracts = None
    
    # get limit and offset
    try:
        limit = int(request.GET['limit'])
        if limit > maxlimit:
            limit = maxlimit
    except (KeyError, ValueError):
        limit = maxlimit
        
    try:
        offset = int(request.GET['offset'])
    except (KeyError, ValueError):
        offset = 0
    
    # get events, 404 if we don't supply either genes or abstracts
    try:
        events = get_events(genes=genes, abstracts=abstracts, limit=limit, offset=offset)
    except KeyError:
        events = []
    
    # return the appropriate response
    
    if request.GET.get('preview'):
        genesyms = [g.symbol for g in Gene.objects.filter(id__in=genes).only('symbol')] if genes else []
        
        # show more information about a specific gene
        # TODO: clean this up during the next re-organization of the event search
        detail = gene_lookup(request.GET.get('detail'))
        if len(detail) > 0:
            summaryrow = get_gene_combinations(genes=genes, abstracts=abstracts).get(detail[0].id)
            if summaryrow:
                summaryrow.innergenes.sort(key=lambda g: -g.count)
        else:
            summaryrow = None    
        
        return render_to_response("eventpreview.html", 
            {'events': events, 'geneids':genes, 'genesyms': genesyms, 'q': query, 'summaryrow':summaryrow})
    
    # 404 if there were no events
    if not events: 
        raise Http404
    
    dl = request.GET.get('download')
    if dl:
        if dl.lower() == 'xml':
            # return xml file
            
            response = HttpResponse('<?xml version="1.0" ?>\n<!DOCTYPE eventlist SYSTEM "http://gadget.biostat.wisc.edu/static/eventlist.dtd">\n<eventlist>\n')
            response.write(xmldescription(query=query, genes=genes, limit=limit, offset=offset))
            for ev in events:
                try:
                    # wrap each event in a try block so if something goes wrong,
                    # we still get all the other events.  take this out when debugging.
                    response.write('\n')
                    response.write(ev.xml(indent=2))
                except:
                    print "event {0} failed to render XML".format(ev.id)
            response.write('</eventlist>')
            
            response['Content-Type'] = 'text/xml'
            return response
        
        if dl.lower() == 'csv':
            # create, package, and return a CSV file
            response = HttpResponse(mimetype='text/csv')
            response['Content-Disposition'] = 'attachment; filename=gadget-events.csv'
            response.write('event_id,gene_entrez_ids,gene_symbols,event_types,abstract_count\n'
                + '\n'.join([ev.tablerow() for ev in events]))
            return response
    
    # render HTML    
    return render_to_response("eventlist.html", {'events':events, 'q':query})