本文整理汇总了Python中piston.emitters.Emitter类的典型用法代码示例。如果您正苦于以下问题:Python Emitter类的具体用法?Python Emitter怎么用?Python Emitter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Emitter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read
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()
示例2: error_resp
def error_resp(message, error_type=None, resp=rc.BAD_REQUEST, status_code=None):
logging.warn("Status Code " + str(resp.status_code) + ", error_type: " + repr(error_type) + ", message: " + repr(message))
error_json = {}
if message and error_type:
(error_type_resp, error_type) = error_type
resp = error_type_resp
error = {}
error['type'] = error_type
error['message'] = message
error_json['error'] = error
elif message:
error = {}
error['type'] = ''
error['message'] = message
error_json['error'] = error
if message or error_type:
emitter, ct = Emitter.get('json') #TODO: Make this work for other emitter formats
srl = emitter(error_json, None, None, None, None)
rendered_resp = srl.render(HttpRequest())
final_resp = HttpResponse(rendered_resp, mimetype=ct)
if status_code:
final_resp.status_code = status_code
else:
final_resp.status_code = resp.status_code
return final_resp
else:
return resp
示例3: apply_json_emitter
def apply_json_emitter(value_to_emit, handler=None):
emitter, ct = Emitter.get('json') #TODO: Make this work for other emitter formats
handler_fields = None
if handler:
handler_fields = handler.fields
srl = emitter(value_to_emit, typemapper, handler, handler_fields, None)
json = srl.construct()
return json
示例4: render_created
def render_created(self, request, new_obj, new_url):
"""Quick hack to return a 201 Created along with a JSON rendering of
what was created"""
resp = rc.CREATED
emitter, ct = Emitter.get('json')
resp['Content-Type'] = ct
resp['Location'] = new_url
srl = emitter(new_obj, typemapper, self, self.fields, False)
resp.content = srl.render(request)
return resp
示例5: form_validation_response
def form_validation_response(self, e, request,em_format):
print 'in form_validation_response 1'
try:
emitter, ct = Emitter.get(em_format)
fields = self.handler.fields
except ValueError:
result = piston.utils.rc.BAD_REQUEST
result.content = "Invalid output format specified '%s'." % em_format
return result
serialized_errors = dict((key, [unicode(v) for v in values])
for key,values in e.form.errors.items())
srl = emitter(serialized_errors, piston.handler.typemapper, self.handler, fields, False)
stream = srl.render(request)
resp = HttpResponse(stream, mimetype=ct, status=400)
return resp
示例6: render
def render(self, request, *args, **kwargs):
f = StringIO.StringIO()
out = csv.writer(f,dialect='excel')
c = self.construct()
if not bool(request.REQUEST.get('headerless', False)):
out.writerow(self.fields)
def mapper(row):
return [row[key] for key in self.fields]
out.writerows(map(mapper, c))
# In this case we'll hanlde the HttpResponse wrapping.
_, ct = Emitter.get('csv')
response = HttpResponse(f.getvalue(), ct)
response['Content-Disposition'] = 'attachment; filename=irack.csv'
return response
示例7: __call__
def __call__(self, request, result, handler):
if isinstance(result, ErrorDict):
result = dictFromErrorDict(result)
resource = handler.resource
em_format = resource.determine_emitter(request)
emitter, ct = Emitter.get(em_format)
srl = emitter(result, typemapper, handler, handler.fields, anonymous=True)
try:
if resource.stream:
stream = srl.stream_render(request)
else:
stream = srl.render(request)
self.__init__(stream, mimetype=ct)
self.streaming = resource.stream
except HttpStatusCode, e:
return e.response
示例8: UncachedEmitter
class UncachedEmitter(JSONEmitter):
""" In websites running under varnish or another cache
caching the api can mess the results and return the wrong data
this emmitter injects No-Cache headers in response"""
def render(self, request):
content = super(UncachedEmitter, self).render(request)
response = HttpResponse(content)
response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response['Content-Type'] = 'application/json; charset=utf-8'
response['Pragma'] = 'no-cache'
response['Expires'] = 0
return response
Emitter.register('json', UncachedEmitter, 'application/json; charset=utf-8')
class BaseHandler(Handler):
limit = 20
limit_arg = 'paginate_limit'
meta = {}
def include_meta(self, d):
obj = {'meta': self.meta, 'objects': d}
return obj
def paginate_queryset(self, queryset, request):
limit = request.GET.get(self.limit_arg, self.meta.get(self.limit_arg))
paginator = Paginator(queryset, limit or self.limit)
示例9: render
self._to_xml(xml, value)
xml.endElement(key.split()[0])
else:
xml.characters(smart_unicode(data))
def render(self, request):
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, "utf-8")
xml.startDocument()
xml.startElement("Response", {})
self._to_xml(xml, self.construct())
xml.endElement("Response")
xml.endDocument()
return stream.getvalue()
Emitter.register('custom_xml', CustomXmlEmitter, 'text/xml; charset=utf-8')
Mimer.register(lambda *a: None, ('text/xml',))
class IpAuthentication(object):
"""IP Authentication handler
"""
def __init__(self, auth_func=authenticate, realm='API'):
self.auth_func = auth_func
self.realm = realm
def is_authenticated(self, request):
try:
settings.API_ALLOWED_IP.index(request.META['REMOTE_ADDR'])
return True
except:
示例10: AnonymousArtInstallationHandler
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):
示例11: getattr
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)
示例12: super
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,
示例13: SsiEmitterMixin
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')
示例14: PistonKeyAuthentication
RegulationsDocketSubmitterHandler
from dcapi.aggregates.fec.handlers import CandidateSummaryHandler, CommitteeSummaryHandler, CandidateStateHandler, \
CandidateTimelineHandler, CandidateItemizedDownloadHandler, CommitteeItemizedDownloadHandler, \
CommitteeTopContribsHandler
from dcapi.aggregates.independentexpenditures.handlers import CandidateIndExpHandler, CommitteeIndExpHandler, \
CandidateIndExpDownloadHandler, CommitteeIndExpDownloadHandler
from django.conf.urls.defaults import patterns, url
from locksmith.auth.authentication import PistonKeyAuthentication
from piston.emitters import Emitter
from piston.resource import Resource
from dcapi.aggregates.faca.handlers import FACAAgenciesHandler,\
FACACommitteeMembersHandler
# We are using the default JSONEmitter so no need to explicitly
# register it. However, unregister those we don't need.
Emitter.unregister('django')
Emitter.unregister('pickle')
Emitter.unregister('xml')
Emitter.unregister('yaml')
ad = { 'authentication': PistonKeyAuthentication() }
urlpatterns = patterns('',
# amount contributed by one entity to another
url(r'^recipient/(?P<recipient_entity>[a-f0-9]{32})/contributor/(?P<contributor_entity>[a-f0-9]{32})/amount.(?P<emitter_format>.+)$',
Resource(ContributionAmountHandler, **ad)),
# contributors to a single politician
url(r'^pol/(?P<entity_id>[a-f0-9]{32})/contributors\.(?P<emitter_format>.+)$',
示例15: render
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")