コード例 #1
0
ファイル: emitters.py プロジェクト: MechanisM/mirosubs
# Universal Subtitles, universalsubtitles.org
# 
# Copyright (C) 2010 Participatory Culture Foundation
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see 
# http://www.gnu.org/licenses/agpl-3.0.html.

from piston.emitters import Emitter
from piston.utils import Mimer

class PlainEmitter(Emitter):
    
    def render(self, request):
        return self.construct()

Emitter.register('plain', PlainEmitter, 'text/plain; charset=utf-8')
Mimer.register(lambda *a: None, ('text/plain',))
コード例 #2
0
                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:
            return False
コード例 #3
0
ファイル: handlers.py プロジェクト: dmaclay/vumi
import yaml
import logging
from piston.handler import BaseHandler
from piston.utils import rc, throttle, require_mime
from piston.utils import Mimer, FormValidationError

from vumi.webapp.api.models import URLCallback
from vumi.webapp.api.forms import URLCallbackForm
from vumi.webapp.api.utils import specify_fields

# Complete reset, clear defaults - they're hard to debug
Mimer.TYPES = {}
# Specify the default Mime loader for YAML, Piston's YAML loader by default
# tries to wrap the loaded YAML data in a dict, which for our conversation
# YAML documents doesn't work.
Mimer.register(yaml.safe_load, ('application/x-yaml',))
# Do nothing with incoming XML, leave the parsing for the handler
Mimer.register(lambda *a: None, ('text/xml', 'application/xml'))
# Do nothing with plain text, leave the parsing for the handler
Mimer.register(lambda *a: None, ('text/plain; charset=utf-8',))


class ConversationHandler(BaseHandler):
    allowed_methods = ('POST',)

    @throttle(5, 10 * 60)  # allow 5 times in 10 minutes
    @require_mime('yaml')
    def create(self, request):
        # menu = load_from_string(request.raw_post_data)
        # dump = dump_menu(menu)  # debug
        logging.debug("Received a new conversation script "
コード例 #4
0
ファイル: emitters.py プロジェクト: SheepDogInc/django-piston
    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('xml', XMLEmitter, 'text/xml; charset=utf-8')
Mimer.register(lambda *a: None, ('text/xml',))

class JSONEmitter(Emitter):
    """
    JSON emitter, understands timestamps.
    """
    def render(self, request):
        cb = request.GET.get('callback', None)
        seria = simplejson.dumps(self.construct(), cls=DateTimeAwareJSONEncoder, ensure_ascii=False, indent=4)

        # Callback
        if cb and is_valid_jsonp_callback_value(cb):
            return '%s(%s)' % (cb, seria)

        return seria
コード例 #5
0
from django.conf.urls.defaults import *
from django.http import HttpResponse
from piston.resource import Resource
from piston.authentication import HttpBasicAuthentication
from piston.utils import Mimer
from txtalert.apps.api.handlers import (SMSHandler, PCMHandler,
                                        SMSReceiptHandler, PatientHandler,
                                        ChangeRequestHandler, CallRequestHandler)

# make sure Piston also accepts text/xml with charset=utf-8
Mimer.register(lambda *a: None, ('text/xml; charset=utf-8',))

http_basic_authentication = HttpBasicAuthentication()

sms_receipt_handler = Resource(SMSReceiptHandler, http_basic_authentication)
sms_handler = Resource(SMSHandler, http_basic_authentication)
pcm_handler = Resource(PCMHandler, http_basic_authentication)
patient_handler = Resource(PatientHandler)
change_request_handler = Resource(ChangeRequestHandler, http_basic_authentication)
call_request_handler = Resource(CallRequestHandler, http_basic_authentication)

# SMS api
urlpatterns = patterns('',
    url(r'^sms/receipt\.(?P<emitter_format>.+)$', sms_receipt_handler, {}, 'api-sms-receipt'),
    url(r'^sms/(?P<identifier>.+)/(?P<msisdn>[0-9]+)\.(?P<emitter_format>.+)$', sms_handler, {}, 'api-sms'),
    url(r'^sms\.(?P<emitter_format>.+)$', sms_handler, {}, 'api-sms'),
    url(r'^patient\.(?P<emitter_format>.+)$', patient_handler, {}, 'api-patient'),
    url(r'^request/change\.(?P<emitter_format>.+)$', change_request_handler, {}, 'api-req-change'),
    url(r'^request/call\.(?P<emitter_format>.+)$', call_request_handler, {}, 'api-req-call'),
)
コード例 #6
0
ファイル: urls.py プロジェクト: tfleish/caesar-web
from api.handlers import CommentHandler

from django.utils import simplejson
from django.conf.urls.defaults import *
from piston.resource import Resource
from piston.authentication import HttpBasicAuthentication
from piston.utils import Mimer

auth = HttpBasicAuthentication(realm="Caesar")
ad = { 'authentication': auth }

# Workaround for django-piston bug in charset handling
Mimer.register(simplejson.loads, 
        ('application/json', 'application/json; charset=UTF-8',))

class CsrfExemptResource(Resource):
    def __init__(self, handler, authentication=None):
        super(CsrfExemptResource, self).__init__(handler, authentication)
        self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)

comment_handler = CsrfExemptResource(CommentHandler, **ad)

urlpatterns = patterns('',
   (r'^comments/', comment_handler),
   (r'^comment/(?P<comment_id>\d+)/', comment_handler)
)
コード例 #7
0
ファイル: settings.py プロジェクト: deccanhosts/log_analytics
from piston.utils import Mimer
from src.utils import pbutils
Mimer.register(pbutils.loadPb, ('application/octet-stream'))
from src.utils import customLogger
apiLogger = customLogger.getApiLogger('api_trace.log')

コード例 #8
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:
            return False
コード例 #9
0
ファイル: __init__.py プロジェクト: miing/mci_migo
# Bit of surgery on piston internals, this fixes
# https://github.com/simplejson/simplejson/issues/37

import json
import simplejson

from piston.utils import Mimer
from piston import emitters

emitters.simplejson = json

Mimer.unregister(simplejson.loads)
Mimer.register(json.loads, ('application/json',))


# Another bit to please django-piston
from django.http import HttpResponse

HttpResponse._get_content = HttpResponse.content.fget
コード例 #10
0
ファイル: handlers.py プロジェクト: opendream/openkala
from quarter.models import *
from stockphoto.models import *
from utility.dmp import diff_match_patch
import utility

def urlencoded(raw):
    first = [urllib.unquote_plus(part) for part in raw.split('&')]
    second = []
    for part in first:
        sp = part.split('=')
        second.append([sp[0], '='.join(sp[1:])])
           
    return dict(second)

Mimer.register(urlencoded, ('application/x-www-form-urlencoded; charset=UTF-8',))

def insertProjectHistory(project, cell, new_value, model, id, field, user): 
    current_value = getattr(model.objects.get(id=id), field)

    if current_value == None:
        current_value = ''
    elif type(current_value) == int:
        current_value = str(current_value)

    if new_value == None:
        new_value = ''
    elif type(new_value) == int:
        new_value = str(new_value)

    if new_value != current_value:
コード例 #11
0
ファイル: __init__.py プロジェクト: sourcery/xperiences
from django.utils.functional import update_wrapper
from piston.decorator import decorator
from piston.emitters import Emitter
from piston.utils import Mimer, rc

__author__ = 'ishai'

class EmpeericJSONEncoder(simplejson.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.datetime):
            d = time.mktime(o.utctimetuple())
            return r"/Date(%u000)/" % d
        else:
            return super(EmpeericJSONEncoder, self).default(o)

Mimer.register(lambda *a: None, ('application/x-www-form-urlencoded; charset=UTF-8',))

def parse_file_field(thing):
    if not thing:
        return None
    if isinstance(thing.field, XPImageField):
        c = Context({'photo' : thing })
        html_template = loader.get_template('photo.json')
        if html_template == None:
            return None
        content = html_template.render(c)
        if content == u'':
            return None
        print content
        try:
            return simplejson.loads(content)
コード例 #12
0
        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('xml', XMLEmitter, 'text/xml; charset=utf-8')
Mimer.register(lambda *a: None, ('text/xml', ))


class JSONEmitter(Emitter):
    """
    JSON emitter, understands timestamps.
    """
    def render(self, request):
        cb = request.GET.get('callback', None)
        seria = simplejson.dumps(self.construct(),
                                 cls=DateTimeAwareJSONEncoder,
                                 ensure_ascii=False,
                                 indent=4)

        # Callback
        if cb and is_valid_jsonp_callback_value(cb):
コード例 #13
0
ファイル: __init__.py プロジェクト: tleekkul/eidos_restful
from piston.utils import Mimer
from piston.emitters import Emitter
from piston.doc import generate_doc

from restful.emitters import HTMLEmitter

#from story.api.handlers import StoryHandler 
#from project.api.handlers import ProjectHandler, ReleaseHandler 

#register emitter
Emitter.register('html', HTMLEmitter, 'text/html; charset=utf-8')

#register content-type 
Mimer.register(lambda *a: None, ('text/plain',))

#register document
#docs = [generate_doc(StoryHandler), generate_doc(ReleaseHandler), generate_doc(ProjectHandler)]
コード例 #14
0
ファイル: emitters.py プロジェクト: edufrick/django-piston
        stream = io.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("xml", XMLEmitter, "text/xml; charset=utf-8")
Mimer.register(lambda *a: None, ("text/xml", ))


class JSONEmitter(Emitter):
    """
    JSON emitter, understands timestamps.
    """
    def render(self, request):
        cb = request.GET.get("callback", None)
        indent = None
        if settings.DEBUG:
            indent = 4
        seria = json.dumps(
            self.construct(),
            cls=DateTimeAwareJSONEncoder,
            ensure_ascii=False,
コード例 #15
0
ファイル: handler.py プロジェクト: leocarv/Roadmap
import django.db.models
from django.db.models.query import QuerySet
from rest.resource import ExtResource
from piston.emitters import Emitter, JSONEmitter
from piston.utils import Mimer
import json
from actstream import action
from rest.decorators import permissions_required


def jquery_json_loads(*args, **kwargs):
    return json.loads(*args, **kwargs)


Emitter.register('json_upload', JSONEmitter, 'text/html; charset=utf-8')
Mimer.register(jquery_json_loads,
                ('application/json', 'application/json; charset=UTF-8',))


class RequestError(Exception):
    """
    A class to control the execution flow exception of a request
    """
    def __init__(self, msg, return_code):
        self.msg = msg
        self.return_code = return_code


class BaseHandler(BaseHandler):

    update_fields = None
    permissions = None
コード例 #16
0
ファイル: handlers.py プロジェクト: opendream/openkala
from stockphoto.models import *
from utility.dmp import diff_match_patch
import utility


def urlencoded(raw):
    first = [urllib.unquote_plus(part) for part in raw.split('&')]
    second = []
    for part in first:
        sp = part.split('=')
        second.append([sp[0], '='.join(sp[1:])])

    return dict(second)


Mimer.register(urlencoded,
               ('application/x-www-form-urlencoded; charset=UTF-8', ))


def insertProjectHistory(project, cell, new_value, model, id, field, user):
    current_value = getattr(model.objects.get(id=id), field)

    if current_value == None:
        current_value = ''
    elif type(current_value) == int:
        current_value = str(current_value)

    if new_value == None:
        new_value = ''
    elif type(new_value) == int:
        new_value = str(new_value)