Source

gevent_cometd / gevent_cometd / util.py

Full commit
import datetime
import json
import urllib
import urllib2
import logging
import gevent_cometd.channel as channel
import gevent_cometd.user as user
from webob import Request, Response, exc
from gevent_cometd import config

log = logging.getLogger(__name__)

def process_request(request, require_authed_request=True):
    """ parse request and check if its authorized if needed """
    res = None
    request_data = None
    if (require_authed_request
        and (request.GET.get('secret') != config['secret'])):
        res = Response(json.dumps({'error':"Bad secret"}),
                       request=request)
        res.status = 403
    if (require_authed_request and
        request.environ['REMOTE_ADDR'] not in config['allow_posting_from']):
        res = Response(json.dumps({'error':"Unauthorized ip:%s" % request.environ['REMOTE_ADDR']}),
                       request=request)
        res.status = 403
    try:
        if request.body:
            request_data = json.loads(request.body)
    except ValueError:
        res = Response(json.dumps({'error':"Malformed json"}),
                       request=request)
        res.status = 400
    return (request_data, res)


class DateTimeEncoder(json.JSONEncoder):
    """ Simple datetime to ISO encoder for json serialization"""
    def default(self, obj):
        if isinstance(obj, datetime.date):
            return obj.isoformat()
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return json.JSONEncoder.default(self, obj)


def cometd_request(endpoint, payload, throw_exceptions=False, servers=None):
    responses = []
    if not servers:
        servers = []
    for server in servers:
        response = {}
        url = '%s%s?%s' % (server['server'], endpoint,
                            urllib.urlencode({"secret":server['secret']}))
        try:
            conn = None
            req = urllib2.Request(url,
                                  json.dumps(payload, cls=DateTimeEncoder),
                                  headers={'Content-Type': 'application/json'},
                                  )
            conn = urllib2.urlopen(req, timeout=3)
            response = json.loads(conn.read())
            conn.close()
        except (urllib2.HTTPError, urllib2.URLError, ValueError), e:
            if hasattr(e, 'read'):
                msg = 'Cometd problem: %s, %s' % (e, e.read())
            else:
                msg = 'Cometd problem: %s' % e
            log.error(msg)
            if throw_exceptions:
                raise Exception(msg)
        responses.append(response)
    return responses

def add_cors_headers(response):
    # allow CORS
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('XDomainRequestAllowed', '1')
    response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
#    response.headers.add('Access-Control-Allow-Credentials', 'true')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Pragma, Origin, Connection, Referer, Cookie')
    response.headers.add('Access-Control-Max-Age', '86400')