当前位置: 首页>>代码示例>>Python>>正文


Python Emitter.register方法代码示例

本文整理汇总了Python中piston.emitters.Emitter.register方法的典型用法代码示例。如果您正苦于以下问题:Python Emitter.register方法的具体用法?Python Emitter.register怎么用?Python Emitter.register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在piston.emitters.Emitter的用法示例。


在下文中一共展示了Emitter.register方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: read

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
 def read(self, request):
   Emitter.register('xml', OpProfessionXMLEmitter, 'text/xml; charset=utf-8')
   
   if 'type' in request.GET and request.GET['type'] == 'basic':
     return OpProfession.objects.db_manager('op').getBasic().values('id', 'description', 'odescription')
   else:
     return OpProfession.objects.using('op').all()
开发者ID:openpolis,项目名称:op_api,代码行数:9,代码来源:handlers.py

示例2: RootHandler

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
from piston.handler import AnonymousBaseHandler
from piston.utils import rc

from django.core.exceptions import ObjectDoesNotExist
from django.forms.models import model_to_dict

from djeuscan.models import Version, Package, Herd, Maintainer, EuscanResult, \
    VersionLog
from djeuscan.helpers import catch_and_return

# replace default XMLEmitter with ours
from piston.emitters import Emitter
from .emitters import EuscanXMLEmitter
Emitter.register('xml', EuscanXMLEmitter, 'text/xml; charset=utf-8')


# /api/1.0/
class RootHandler(AnonymousBaseHandler):
    allowed_methods = ('GET',)

    def read(self, request):
        return {'api-version': '1.0'}


# /api/1.0/statistics
class StatisticsHandler(AnonymousBaseHandler):
    allowed_methods = ('GET',)

    def read(self, request):
        data = {}
        data['n_packaged'] = Package.objects.n_packaged()
开发者ID:EvaSDK,项目名称:euscan,代码行数:33,代码来源:handlers.py

示例3: CSVEmitter

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
class CSVEmitter(Emitter):
    """Emitter that returns CSV file"""
    
    def render(self, request):
        result = StringIO.StringIO()
        
        field_names = tuple(get_flattened_field_names(self.fields))
        
        dict_writer = unicodecsv.UnicodeDictWriter(result, field_names, dialect=csv.excel_tab)
        dict_writer.writerow(dict(zip(field_names, field_names)))
        dict_writer.writerows(get_flattened_data(self.construct()))
        
        return result.getvalue()

Emitter.register('csv', CSVEmitter, 'application/csv')

def detect_style(val):
    if isinstance(val, str):
        for typ in [int, float]:
            try:
                val = typ(val)
                return val, typ
            except ValueError:
                pass

class ExcelEmitter(Emitter):
    """Emitter that returns Excel file"""
    def render(self, request):

        result = StringIO.StringIO()
开发者ID:Arpaso,项目名称:ETS,代码行数:32,代码来源:handlers.py

示例4: AnonymousArtInstallationHandler

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
import logging
from piston.handler import BaseHandler, AnonymousBaseHandler
from piston.emitters import Emitter, JSONEmitter
from brc.models import *
from api.emitters import GeoJSONEmitter
from swingtime.models import Event, Occurrence
import time

JSONEmitter.unregister('json')
Emitter.register('json', GeoJSONEmitter, content_type='text/javascript; charset=utf-8')

art_fields = ('id', 'name', ('year', ('id','year')), 'slug', 'artist', 'description', 'url', 'contact_email', 'location_point', 'location_poly', 'circular_street', 'time_address')
event_fields = ('id', 'title','description', 'print_description', ('year', ('id','year')), 'slug', 'event_type', ('hosted_by_camp', ('id','name')), ('located_at_art', ('id','name')), 'other_location', 'check_location', 'url', 'location_point', 'location_track', 'all_day', ('occurrence_set', ('start_time', 'end_time')))
camp_fields = ('id', ('year', ('id','year')), 'name', 'description', 'type', 'start_date_time', 'end_date_time', 'duration', 'repeats', 'hosted_by_camp', 'located_at_art', 'url', 'location_point', 'location_poly', 'contact_email') 
cstreet_fields = ('id', ('year', ('id','year')), 'name', 'order', 'width', 'distance_from_center', 'street_line')
tstreet_fields = ('id', ('year', ('id','year')), 'hour', 'minute', 'name', 'width', 'street_line')
infrastructure_fields = ('id', ('year', ('id','year')), 'name', 'location_point', 'location_line', 'location_poly', 'location_multigeom', 'tags')
year_fields = ('id', 'location', 'location_point', 'participants', 'theme')
user_fields = ('id', 'username', 'first_name', 'last_name', 'active')


class AnonymousArtInstallationHandler(BaseHandler):
	allow_methods = ('GET',)
	model = ArtInstallation 
	fields = art_fields
	
	def read(self, request, year_year=None, art_id=None):
		base = ArtInstallation.objects.filter()
		if(year_year):
		        year = Year.objects.get(year=year_year)
			if(art_id):
开发者ID:cjs,项目名称:bme,代码行数:33,代码来源:handlers.py

示例5: super

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
            resp = super(Resource, self).__call__(request, *args, **kwargs)

            try:
                db.logs.insert({'key': request.apikey['_id'],
                                'method': self.handler.__class__.__name__,
                                'query_string': request.META['QUERY_STRING'],
                                'timestamp': datetime.datetime.utcnow()})
            except AttributeError:
                pass

            return resp
else:
    authorizer = None
    Resource = piston.resource.Resource

Emitter.register('json', BillyJSONEmitter, 'application/json; charset=utf-8')

Emitter.register('ics', ICalendarEmitter, 'text/calendar')

Emitter.unregister('yaml')
Emitter.unregister('xml')
Emitter.unregister('django')
Emitter.unregister('pickle')

all_metadata_handler = Resource(handlers.AllMetadataHandler,
                                authentication=authorizer)
metadata_handler = Resource(handlers.MetadataHandler,
                            authentication=authorizer)
bill_handler = Resource(handlers.BillHandler,
                        authentication=authorizer)
bill_search_handler = Resource(handlers.BillSearchHandler,
开发者ID:JT5D,项目名称:billy,代码行数:33,代码来源:urls.py

示例6: super

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
            resp = super(Resource, self).__call__(request, *args, **kwargs)

            try:
                db.logs.insert({'key': request.apikey['_id'],
                                'method': self.handler.__class__.__name__,
                                'query_string': request.META['QUERY_STRING'],
                                'timestamp': datetime.datetime.utcnow()})
            except AttributeError:
                pass

            return resp
else:
    authorizer = None
    Resource = piston.resource.Resource

Emitter.register('json', BillyJSONEmitter, 'application/json; charset=utf-8')
Emitter.register('xml', BillyXMLEmitter, 'application/xml; charset=utf-8')

Emitter.register('rss', FeedEmitter, 'application/rss+xml')
Emitter.register('ics', ICalendarEmitter, 'text/calendar')

Emitter.unregister('yaml')
Emitter.unregister('django')
Emitter.unregister('pickle')

all_metadata_handler = Resource(handlers.AllMetadataHandler,
                                authentication=authorizer)
metadata_handler = Resource(handlers.MetadataHandler,
                            authentication=authorizer)
bill_handler = Resource(handlers.BillHandler,
                        authentication=authorizer)
开发者ID:donaldsmith2060,项目名称:openstates,代码行数:33,代码来源:urls.py

示例7: render

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
    def render(self, request):
        cb = request.GET.get("callback", None)
        try:
            per_page = int(request.GET.get("per_page", 10))
        except ValueError:
            per_page = 10
        try:
            page_number = int(request.GET.get("page_number", 1))
        except ValueError:
            page_number = 1

        pages = Paginator(self.construct(), per_page)

        try:
            page = pages.page(page_number)
        except EmptyPage:
            page = pages.page(1)

        data = {"num_pages": pages.num_pages, "page_number": page_number, "data": page.object_list}

        serial = json.dumps(data, cls=DateTimeAwareJSONEncoder, ensure_ascii=False, indent=4)

        # Callback
        if cb and is_valid_jsonp_callback_value(cb):
            return "%s(%s)" % (cb, serial)

        return serial


Emitter.register("page_json", PageJSONEmitter, "application/json; charset=utf-8")
开发者ID:wufulab,项目名称:Kavalan_Management_System,代码行数:32,代码来源:emitters.py

示例8: RSSEmitter

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
class RSSEmitter(Emitter):


	def render(self, request):
		
		data = self.construct()
		rss_items = []
		for item in data:
			rss_items.append(PyRSS2Gen.RSSItem(
					title = item['title'],
					description = item['synopsis'],
					link = item['url'],
					pubDate = item['date_created'],
				))
			
	
		rss = PyRSS2Gen.RSS2(
			title = "RSS for Something",
			link = "http://news.something.com",
			description = "Test",
			lastBuildDate = datetime.datetime.utcnow(),
			items = rss_items			
		)
		
		
		return rss.to_xml(encoding="utf-8")
		#return data
	
# Register Emitter
Emitter.register('rss', RSSEmitter, 'charset=utf-8')
开发者ID:kstateome,项目名称:django-piston-rss-emitter,代码行数:32,代码来源:emitters.py

示例9: render

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
    JSON emitter, understands timestamps, wraps result set in object literal
    for jqGrid JS compatibility
    """

    def render(self, request):
        callback = request.GET.get('callback')

        row_data = self.construct()
        fields = list(self.fields)
        fields.remove('id')
        rows = [{
            'id': row['id'],
            'cell': [row[field] for field in fields]} for row in row_data]

        # todo: Is there a better way to determine this?
        if fields[1] == 'image':
            total = int(math.ceil(len(Image.objects.all())/50.0))
        else:
            total = int(math.ceil(len(File.objects.all())/50.0))

        jqgrid_dict = {'page': int(request.GET['page']), 'total': total, 'records': len(rows), 'rows': rows}
        json = simplejson.dumps(jqgrid_dict, cls=DateTimeAwareJSONEncoder, ensure_ascii=False, indent=4)

        # callback
        if callback:
            return '%s(%s)' % (callback, json)

        return json

Emitter.register('jqgrid-json', jqGridJSONEmitter, 'application/json; charset=utf-8')
开发者ID:CulturePlex,项目名称:website,代码行数:32,代码来源:emitters.py

示例10: patterns

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
from django.conf.urls.defaults import url, patterns, include
from dcapi.common.emitters import StreamingCSVEmitter, StreamingJSONEmitter, ExcelEmitter
from piston.emitters import Emitter

Emitter.register("json", StreamingJSONEmitter, "application/json; charset=utf-8")
Emitter.register("csv", StreamingCSVEmitter, "text/csv; charset=utf-8")
Emitter.register("xls", ExcelEmitter, "application/vnd.ms-excel; charset=utf-8")
Emitter.unregister("django")
Emitter.unregister("pickle")
Emitter.unregister("xml")
Emitter.unregister("yaml")

urlpatterns = patterns(
    "",
    # each data set has its own area of the API and has its own
    # namespace. 'entities' is a core/common element to all APIs, and
    # aggregates has also been de-coupled from the contributions API.
    url(r"^entities", include("dcapi.aggregates.entities.urls")),
    url(r"^contracts", include("dcapi.contracts.urls")),
    # url(r'^contributions/bundled/', include('dcapi.contributions.bundling.urls')),
    url(r"^contributions", include("dcapi.contributions.urls")),
    url(r"^grants", include("dcapi.grants.urls")),
    url(r"^lobbying", include("dcapi.lobbying.urls")),
    url(r"^earmarks", include("dcapi.earmarks.urls")),
    url(r"^misconduct", include("dcapi.contractor_misconduct.urls")),
    url(r"^epa", include("dcapi.epa.urls")),
    url(r"^faca", include("dcapi.faca.urls")),
    url(r"^fara", include("dcapi.fara.urls")),
    url(r"^aggregates/", include("dcapi.aggregates.urls")),
    url(r"^refine/", include("dcapi.reconcile.urls")),
    url(r"^", include("dcapi.rapportive.urls")),
开发者ID:dmc2015,项目名称:datacommons,代码行数:33,代码来源:urls.py

示例11: len

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
    if len(construct) > 0:
        for key, value in construct[0].items():
            header_row.append(key)
    
        for row in construct:
            this_row = []
            for header in header_row:
                this_row.append(row[header])
            data.append(this_row)
    return { 'header_row':header_row, 'data':data }
    
class HTMLEmitter(Emitter):
    def render(self, request):
        page_info = _get_page_info(request)
        data = _construct_to_list(self.construct())
        return render_to_string("api/data_html_view.html", { 'page_info':page_info, 'data':data })
        
class CSVEmitter(Emitter):
    def render(self, request):
        response = HttpResponse(mimetype='text/csv')
        writer = csv.writer(response)
        data = _construct_to_list(self.construct())
        
        writer.writerow(data['header_row'])
        for row in data['data']:
            writer.writerow(row)
        return(response)

Emitter.register('html', HTMLEmitter, 'text/html')
Emitter.register('csv', CSVEmitter, 'text/csv')
开发者ID:jroo,项目名称:npp_api,代码行数:32,代码来源:emitters.py

示例12: get_values

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
                keys.append(item[0])
        return keys
    

    def get_values(self, input_dict):
        for item in input_dict.items():
            if isinstance(item[1], dict):
                input_dict.update(self.get_values(input_dict.pop(item[0])))
            else:
                input_dict[item[0]] = smart_str(item[1])
        return input_dict

    
    def render(self, request):
        response = HttpResponse(mimetype='text/csv')
        content = self.construct()
        keys = self.get_keys(content[0])
        
        writer = csv.DictWriter(response, keys, dialect='excel')
        headers = dict((n,n) for n in keys)
        writer.writerow(headers)
        for row in content:
            writer.writerow(self.get_values(row))
        
        return response

    
Emitter.register('json', JSONEmitter, 'application/json; charset=utf-8')
Emitter.register('csv', CSVEmitter, 'text/csv; charset=utf-8')
Emitter.register('geojson', GeoJSONEmitter, 'application/json; charset=utf-8')
开发者ID:arthur-e,项目名称:gass,代码行数:32,代码来源:emitters.py

示例13: SsiEmitterMixin

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
class SsiEmitterMixin(object):
    def construct(self):
        if isinstance(self.data, QuerySet) and self.data.model in (Book,
                Fragment, Tag):
            return SsiQS(self.data)
        else:
            return super(SsiEmitterMixin, self).construct()


class SsiJsonEmitter(SsiEmitterMixin, JSONEmitter):
    def render(self, request):
        try:
            return super(SsiJsonEmitter, self).render(request)
        except TypeError:
            return '[%s]' % ",".join(self.construct().get_ssis('json'))

Emitter.register('json', SsiJsonEmitter, 'application/json; charset=utf-8')


class SsiXmlEmitter(SsiEmitterMixin, XMLEmitter):
    def render(self, request):
        try:
            return super(SsiXmlEmitter, self).render(request)
        except TypeError:
            return '<?xml version="1.0" encoding="utf-8"?>\n' \
                '<response><resource>%s</resource></response>' % \
                '</resource><resource>'.join(self.construct().get_ssis('xml'))

Emitter.register('xml', SsiXmlEmitter, 'text/xml; charset=utf-8')

开发者ID:jumasheff,项目名称:wolnelektury,代码行数:31,代码来源:emitters.py

示例14: Resource

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
            try:
                LogEntry.objects.create(
                    caller_key=request.apikey.key,
                    method=self.handler.__class__.__name__,
                    query_string=request.META['QUERY_STRING'],
                )
            except AttributeError:
                pass

            return resp
else:
    authorizer = None
    Resource = piston.resource.Resource

Emitter.register('json', OpenStateJSONEmitter,
                 'application/json; charset=utf-8')

Emitter.register('rss', FeedEmitter, 'application/rss+xml')
Emitter.register('ics', ICalendarEmitter, 'text/calendar')

Emitter.unregister('xml')
Emitter.unregister('yaml')
Emitter.unregister('django')
Emitter.unregister('pickle')

metadata_handler = Resource(handlers.MetadataHandler,
                            authentication=authorizer)
bill_handler = Resource(handlers.BillHandler,
                        authentication=authorizer)
bill_search_handler = Resource(handlers.BillSearchHandler,
                               authentication=authorizer)
开发者ID:bstinsonmhk,项目名称:openstates,代码行数:33,代码来源:urls.py

示例15: getattr

# 需要导入模块: from piston.emitters import Emitter [as 别名]
# 或者: from piston.emitters.Emitter import register [as 别名]
from django.conf import settings
from django.conf.urls.defaults import *

from piston.resource import Resource
from piston.emitters import Emitter

from fiftystates.site.api.handlers import *
from fiftystates.site.api.emitters import LoggingJSONEmitter, LoggingXMLEmitter
from fiftystates.site.api.views import document

if getattr(settings, 'USE_LOCKSMITH', False):
    from locksmith.auth.authentication import PistonKeyAuthentication
    authorizer = PistonKeyAuthentication()
    Emitter.register('json', LoggingJSONEmitter,
                     'application/json; charset=utf-8')
    # disable XML output
    Emitter.unregister('xml')
else:
    authorizer = None

metadata_handler = Resource(MetadataHandler, authentication=authorizer)
bill_handler = Resource(BillHandler, authentication=authorizer)
bill_search_handler = Resource(BillSearchHandler, authentication=authorizer)
legislator_handler = Resource(LegislatorHandler, authentication=authorizer)
legsearch_handler = Resource(LegislatorSearchHandler,
                             authentication=authorizer)
legislator_geo_handler = Resource(LegislatorGeoHandler,
                                  authentication=authorizer)
committee_handler = Resource(CommitteeHandler, authentication=authorizer)
committee_search_handler = Resource(CommitteeSearchHandler,
                                    authentication=authorizer)
开发者ID:jsoma,项目名称:openstates,代码行数:33,代码来源:urls.py


注:本文中的piston.emitters.Emitter.register方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。