Skip to content

Commit

Permalink
merge with whats on server
Browse files Browse the repository at this point in the history
  • Loading branch information
serg0987 committed Sep 19, 2011
2 parents be2dbf9 + 88f9f78 commit e2e21b1
Show file tree
Hide file tree
Showing 26 changed files with 320 additions and 226 deletions.
2 changes: 1 addition & 1 deletion __init__.py
Expand Up @@ -5,4 +5,4 @@

# Redefine modules names for backword capatibility
sys.modules['noodles.maputils'] = maputils
sys.modules['noodles.session'] = session
sys.modules['noodles.session'] = session
14 changes: 7 additions & 7 deletions app.py
Expand Up @@ -25,7 +25,7 @@

# Create an dispatcher instance
dispatcher = Dispatcher(mapper=resolver.get_map(),
controllers = CONTROLLERS
controllers=CONTROLLERS
)

# Load all midllewares for application
Expand All @@ -44,7 +44,7 @@ def noodlesapp(env, start_response):
# Callable function must return Respone object
for middleware in app_middlewares:
callable_obj = middleware(callable_obj) # Hardcoded use of HTTP Session middleware

try:
response = callable_obj()
return response(env, start_response)
Expand All @@ -58,19 +58,19 @@ def noodlesapp(env, start_response):
response = DebugError500(e, traceback)
return response(env, start_response)
#TODO: write production Error500 response


# Start server function, you may specify port number here
def startapp():
try:
from config import PORT,SERVER_LOGTYPE
from config import PORT, SERVER_LOGTYPE
except ImportError:
PORT = 8088 # By defaultl 8088 debug port
print 'Start server on %i...' % PORT
if SERVER_LOGTYPE=='supress':
if SERVER_LOGTYPE == 'supress':
import StringIO
s = StringIO.StringIO()
else:
s = SERVER_LOGTYPE
server.WebSocketServer(('', PORT), noodlesapp,log=s).serve_forever()
server.WebSocketServer(('', PORT), noodlesapp, log=s).serve_forever()
#WSGIServer(('', PORT), noodlesapp).serve_forever()
28 changes: 14 additions & 14 deletions controllers/static.py
Expand Up @@ -12,7 +12,7 @@
MIME_TYPES = {
# Application types
'.swf': 'application/x-shockwave-flash',

# Text types
'.gz':'application/x-tar',
'.js': 'text/javascript',
Expand All @@ -25,13 +25,13 @@
'.gif': 'image/gif',
'.png': 'image/png',
'.tiff': 'image/tiff',

# Sound files

'.wav': 'audio/x-wav',
'.mp3': 'audio/mpeg',
'.ogg': 'audio/ogg',

# And much more...
# Add mime types from this source http://en.wikipedia.org/wiki/Internet_media_type
# Thank you Jimmy
Expand All @@ -49,16 +49,16 @@ def index(request, path_info):
# define a file extansion
base, ext = os.path.splitext(path_info) # Get the file extansion
mime_type = MIME_TYPES.get(ext)
if not mime_type: raise Exception("unknown doc, or something like that :-P: %s" % ext )
if not mime_type: raise Exception("unknown doc, or something like that :-P: %s" % ext)
static_file_path = os.path.join(STATIC_ROOT, path_info)
# Check if this path exists
if not os.path.exists(static_file_path):
if not os.path.exists(static_file_path):
error_msg = "<h1>Error 404</h1> No such file STATIC_ROOT/%s" % path_info
return Error404(error_msg)
# configure response
static_file = open(static_file_path, 'rb') # Open file
# Here we try to handle Range parameter

content_offset = 0
content_end = 0
request_range = request.headers.get('Range')
Expand All @@ -69,20 +69,20 @@ def index(request, path_info):
content_offset = toInt(range_bytes[0])
content_end = toInt(range_bytes[1])
parital_response = True
static_content = static_file.read()


static_content = static_file.read()
if content_end <= 0 or content_end >= len(static_content): content_end = len(static_content) - 1
response.body = static_content[content_offset: content_end + 1]


response.charset = 'utf-8'

if parital_response:
response.status = 206
response.headerlist = [('Content-type', mime_type),
response.headerlist = [('Content-type', mime_type),
('Content-Range', 'bytes %i-%i/%i' % (content_offset, content_end, len(static_content)))]

else:
response.headerlist = [('Content-type', mime_type)]

Expand Down
58 changes: 29 additions & 29 deletions datastore.py
Expand Up @@ -24,30 +24,30 @@ class DoesNotExist(Exception):

class Value(object):
"Single value in our data storage"

__isvalue__ = True
def __init__(self, type_of_value = None):

def __init__(self, type_of_value=None):
if type_of_value: self.type = type_of_value
else: self.type = str

def set_key(self, key):
self.key = key

def typing(self, value):
" If value is None it returns None, else value value in proper type"
if value != None: return self.type(value)
else: return None

def get_default(self):
return None

def __get__(self, instance, owner):
valuedict = instance.__instdict__
if valuedict:
return self.typing(valuedict[self.key])
else: return self
else: return self

def __set__(self, instance, value):
valuedict = instance.__instdict__
try:
Expand All @@ -73,9 +73,9 @@ def __init__(self, valuedict=None, embedded=False, **kwargs):
if 'salt' in kwargs: self.__salt__ = kwargs['salt']
classname = self.__class__.__name__
self.__init_structure__(classname, valuedict, **kwargs)
self.collection_name = self.__collection__[classname]
self.collection_name = self.__collection__[classname]
self.embedded = embedded

def __init_structure__(self, classname, valuedict=None, **kwargs):
# create dictionary for model instance
self.__instdict__ = {}
Expand All @@ -97,7 +97,7 @@ def __init_structure__(self, classname, valuedict=None, **kwargs):
self.__instdict__ = valuedict
else:
self.__instdict__ = copy.deepcopy(self.__structure__[classname])

for k in kwargs:
if k=='salt': continue
elif k in self.__instdict__:
Expand All @@ -107,8 +107,8 @@ def __init_structure__(self, classname, valuedict=None, **kwargs):
self.__instdict__[k] = kwargs[k]
else:
raise Exception('There is no such value \'%s\' in %s model.' % (k, classname))
def save(self, storage = None):

def save(self, storage=None):
" Save object to redis storage"
if self.embedded:
logging.warning('You should save embedded objects with high level object')
Expand All @@ -123,7 +123,7 @@ def save(self, storage = None):
RedisConn.set(':'.join([REDIS_NAMESPACE, self.collection_name, str(self.id)]), json.dumps(self.__instdict__))
#self.save_redis_recursive(':'.join([self.collection_name, str(self.id)]), self.__instdict__)


@classmethod
def get_structure(cls):
structure = cls.__structure__.get(cls.__name__)
Expand All @@ -132,7 +132,7 @@ def get_structure(cls):
cls_inst = cls()
return cls.__structure__.get(cls.__name__)
return structure

@classmethod
def get_collection_name(cls):
classname = cls.__name__
Expand All @@ -141,10 +141,10 @@ def get_collection_name(cls):
cls.__collection__[classname] = classname.lower() + 's'
return cls.__collection__[classname]
return collection_name

def get_values(self):
return copy.deepcopy(self.__instdict__)

@classmethod
def get(cls, id, storage = None,salt=None): # storage=None for backword capability
"Get object from Redis storage by ID"
Expand All @@ -160,32 +160,32 @@ def get(cls, id, storage = None,salt=None): # storage=None for backword capabili
else:
# Copy structure of Class to new dictionary
instance_dict = json.loads(inst_data.__str__())
return cls(valuedict = instance_dict)
return cls(valuedict=instance_dict)

@classmethod
def delete(cls, id, storage = None): # storage=None for backword capability
def delete(cls, id, storage=None): # storage=None for backword capability
"Delete key specified by ``id``"
result = RedisConn.delete(':'.join([REDIS_NAMESPACE, cls.get_collection_name(), str(id)]))
logging.debug('delete::______________ %s'%result)
return result
logging.debug('delete::______________ %s' % result)
return result

class Node(Value):
" Use it for embedd objects to model "

def __init__(self, model_class):
self.model = model_class

def __get__(self, instance, owner):
valuedict = instance.__instdict__
if valuedict:
# TODO: Optimiize this!
model_inst = self.model(valuedict = valuedict[self.key])
model_inst = self.model(valuedict=valuedict[self.key])
return model_inst
else: return self

def __set__(self, instance, value):
pass

def get_default(self):
model_inst = self.model()
return model_inst.get_structure()
Expand Down
22 changes: 11 additions & 11 deletions dispatcher.py
Expand Up @@ -2,11 +2,11 @@
filedesc: request dispatch logic
'''
from noodles.http import Error404
from noodles.templates import Templater
import sys, os,urllib
from noodles.templates import Templater
import sys, os, urllib

# Add standard controllers dir to PYTHON_PATH directory
sys.path.append( os.path.join(os.path.dirname(__file__), 'controllers') )
sys.path.append(os.path.join(os.path.dirname(__file__), 'controllers'))

class CallWrapper(object):
def __init__(self, controller, action, extra_args):
Expand All @@ -15,8 +15,8 @@ def __init__(self, controller, action, extra_args):
try:
self.action = getattr(controller, action)
except AttributeError:
raise Exception('No such action %s in controller %s' % (action,controller.__name__))
raise Exception('No such action %s in controller %s' % (action, controller.__name__))

def __call__(self):
return self.action(**self.extra_args)

Expand Down Expand Up @@ -47,14 +47,14 @@ def get_callable(self, request):
# Get controller name and action from routes
controller_name = route_res.get('controller')
action = route_res.get('action')

controller = self.controllers.get(controller_name)
if not controller: raise Exception('No such controller \'%s\'' % controller_name)

# Prepare extra args for callable

extra_args = route_res.copy() # copying all data from routes dictionary
for k,v in extra_args.items():
for k, v in extra_args.items():
extra_args[k] = urllib.unquote(v).decode('utf8')
# Delete controller and action items
del extra_args['controller']; del extra_args['action']
Expand All @@ -65,14 +65,14 @@ def get_callable(self, request):
return callable_obj

def not_found(self, request):
" Returns pair if url does'nt match any choice in mapper "
" Returns pair if url does'nt match any choice in mapper "
class NotFoundCallable():

def __init__(self, request):
self.request = request

def __call__(self):
" Genereate 404 server response here "
return Error404('<h1>Error 404. Can\'t find page</h1>')

return NotFoundCallable(request)
1 change: 0 additions & 1 deletion events/__init__.py
Expand Up @@ -6,4 +6,3 @@
"""
from events import Event


18 changes: 9 additions & 9 deletions events/events.py
Expand Up @@ -21,31 +21,31 @@ class NoodlesEventError(Exception):

class Event(object):
"I'm event object"

_events_id_key = ['__noodles_events_index']

# Hack for saving memory
@property
def events_id_key(self):
return self._events_id_key[0]

def __init__(self):
self.id = RedisConn.incr(self.events_id_key)
self.callback = None

def register(self, callback):
"Register event in system "
NOODLES_EVENTS_LIST[self.id] = self
self.callback = callback
def firing(self, event_data = {}):

def firing(self, event_data={}):
event_msg = {'event_id': self.id, 'event_data': event_data}
RedisConn.publish(NOODLES_EVENTS_CHANNEL, json.dumps(event_msg))
print 'Event is firing'

def unregister(self):
NOODLES_EVENTS_LIST.pop(self.id)

def event_listener():
print "event_listener:: i'm event listener"
rc = redis.Redis()
Expand All @@ -64,5 +64,5 @@ def event_listener():
else: event.callback(event_data)
else:
logging.warning('Noodles events engine: Event#%i is unregistered' % event_id)

gevent.spawn(event_listener)

0 comments on commit e2e21b1

Please sign in to comment.