Commit 4ecf20e7 authored by Jacek Furmankiewicz's avatar Jacek Furmankiewicz

Merge branch 'master' of https://github.com/kaosat-dev/corepost

parents b2b41a31 4204008e
...@@ -7,27 +7,41 @@ for JSON/XML/YAML output ...@@ -7,27 +7,41 @@ for JSON/XML/YAML output
''' '''
import collections import collections
import logging
import json
from UserDict import DictMixin from UserDict import DictMixin
from twisted.python import log
advanced_json = False
try:
import jsonpickle
advanced_json = True
except ImportError: pass
primitives = (int, long, float, bool, str,unicode) primitives = (int, long, float, bool, str,unicode)
def convertForSerialization(obj): def convertForSerialization(obj):
"""Converts anything (clas,tuples,list) to the safe serializable equivalent""" """Converts anything (clas,tuples,list) to the safe serializable equivalent"""
if type(obj) in primitives: try:
if type(obj) in primitives:
# no conversion # no conversion
return obj return obj
elif isinstance(obj, dict) or isinstance(obj,DictMixin): elif isinstance(obj, dict) or isinstance(obj,DictMixin):
return traverseDict(obj) return traverseDict(obj)
elif isClassInstance(obj): elif isClassInstance(obj):
return convertClassToDict(obj) return convertClassToDict(obj)
elif isinstance(obj,collections.Iterable) and not isinstance(obj,str): elif isinstance(obj,collections.Iterable) and not isinstance(obj,str):
# iterable # iterable
values = [] values = []
for val in obj: for val in obj:
values.append(convertForSerialization(val)) values.append(convertForSerialization(val))
return values return values
else: else:
# return as-is # return as-is
return obj
except AttributeError as ex:
log.msg(ex,logLevel=logging.WARN)
return obj return obj
def convertClassToDict(clazz): def convertClassToDict(clazz):
...@@ -48,6 +62,19 @@ def traverseDict(dictObject): ...@@ -48,6 +62,19 @@ def traverseDict(dictObject):
newDict[prop] = convertForSerialization(val) newDict[prop] = convertForSerialization(val)
return newDict return newDict
def convertToJson(obj):
"""Converts to JSON, including Python classes that are not JSON serializable by default"""
if advanced_json:
try:
return jsonpickle.encode(obj, unpicklable=False)
except Exception as ex:
raise RuntimeError(str(ex))
try:
return json.dumps(obj)
except Exception as ex:
raise RuntimeError(str(ex))
def generateXml(obj): def generateXml(obj):
"""Generates basic XML from an object that has already been converted for serialization""" """Generates basic XML from an object that has already been converted for serialization"""
......
...@@ -4,20 +4,26 @@ Common enums ...@@ -4,20 +4,26 @@ Common enums
@author: jacekf @author: jacekf
''' '''
class Http: class Http:
"""Enumerates HTTP methods""" """Enumerates HTTP methods"""
GET = "GET" GET = "GET"
POST = "POST" POST = "POST"
PUT = "PUT" PUT = "PUT"
DELETE = "DELETE" DELETE = "DELETE"
OPTIONS = "OPTIONS"
HEAD = "HEAD"
PATCH = "PATCH"
class HttpHeader: class HttpHeader:
"""Enumerates common HTTP headers""" """Enumerates common HTTP headers"""
CONTENT_TYPE = "content-type" CONTENT_TYPE = "content-type"
ACCEPT = "accept" ACCEPT = "accept"
class MediaType: class MediaType:
"""Enumerates media types""" """Enumerates media types"""
WILDCARD = "*/*" WILDCARD = "*/*"
APPLICATION_XML = "application/xml" APPLICATION_XML = "application/xml"
APPLICATION_ATOM_XML = "application/atom+xml" APPLICATION_ATOM_XML = "application/atom+xml"
......
This diff is collapsed.
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
Various CorePost utilities Various CorePost utilities
''' '''
from inspect import getargspec from inspect import getargspec
import json
def getMandatoryArgumentNames(f): def getMandatoryArgumentNames(f):
'''Returns a tuple of the mandatory arguments required in a function''' '''Returns a tuple of the mandatory arguments required in a function'''
...@@ -11,17 +11,12 @@ def getMandatoryArgumentNames(f): ...@@ -11,17 +11,12 @@ def getMandatoryArgumentNames(f):
return args return args
else: else:
return args[0:len(args) - len(defaults)] return args[0:len(args) - len(defaults)]
def getRouterKey(method,url): def getRouterKey(method,url):
'''Returns the common key used to represent a function that a request can be routed to''' '''Returns the common key used to represent a function that a request can be routed to'''
return "%s %s" % (method,url) return "%s %s" % (method,url)
def convertToJson(obj):
"""Converts to JSON, including Python classes that are not JSON serializable by default"""
try:
return json.dumps(obj)
except Exception as ex:
raise RuntimeError(str(ex))
def checkExpectedInterfaces(objects,expectedInterface): def checkExpectedInterfaces(objects,expectedInterface):
"""Verifies that all the objects implement the expected interface""" """Verifies that all the objects implement the expected interface"""
...@@ -33,4 +28,3 @@ def safeDictUpdate(dictObject,key,value): ...@@ -33,4 +28,3 @@ def safeDictUpdate(dictObject,key,value):
"""Only adds a key to a dictionary. If key exists, it leaves it untouched""" """Only adds a key to a dictionary. If key exists, it leaves it untouched"""
if key not in dictObject: if key not in dictObject:
dictObject[key] = value dictObject[key] = value
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment