add oxdjango to ox package
This commit is contained in:
parent
0eeecabbd2
commit
0262ae50ca
11 changed files with 355 additions and 4 deletions
0
ox/django/__init__.py
Normal file
0
ox/django/__init__.py
Normal file
21
ox/django/decorators.py
Normal file
21
ox/django/decorators.py
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# vi:si:et:sw=4:sts=4:ts=4
|
||||||
|
|
||||||
|
try:
|
||||||
|
from django.contrib.auth.decorators import wraps
|
||||||
|
except:
|
||||||
|
from django.utils.functional import wraps
|
||||||
|
from shortcuts import render_to_json_response
|
||||||
|
|
||||||
|
def login_required_json(function=None):
|
||||||
|
"""
|
||||||
|
Decorator for views that checks that the user is logged in
|
||||||
|
return json error if not logged in.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def _wrapped_view(request, *args, **kwargs):
|
||||||
|
if request.user.is_authenticated():
|
||||||
|
return function(request, *args, **kwargs)
|
||||||
|
return render_to_json_response({'status': {'code': 401, 'text': 'login required'}})
|
||||||
|
return wraps(function)(_wrapped_view)
|
||||||
|
|
76
ox/django/fields.py
Normal file
76
ox/django/fields.py
Normal file
|
@ -0,0 +1,76 @@
|
||||||
|
import time
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from django.utils import simplejson as json
|
||||||
|
|
||||||
|
|
||||||
|
def to_json(python_object):
|
||||||
|
if isinstance(python_object, time.struct_time):
|
||||||
|
return {'__class__': 'time.asctime',
|
||||||
|
'__value__': time.asctime(python_object)}
|
||||||
|
if isinstance(python_object, bytes):
|
||||||
|
return {'__class__': 'bytes',
|
||||||
|
'__value__': list(python_object)}
|
||||||
|
raise TypeError(repr(python_object) + ' is not JSON serializable')
|
||||||
|
|
||||||
|
def from_json(json_object):
|
||||||
|
if '__class__' in json_object:
|
||||||
|
if json_object['__class__'] == 'time.asctime':
|
||||||
|
return time.strptime(json_object['__value__'])
|
||||||
|
if json_object['__class__'] == 'bytes':
|
||||||
|
return bytes(json_object['__value__'])
|
||||||
|
return json_object
|
||||||
|
|
||||||
|
class DictField(models.TextField):
|
||||||
|
"""DictField is a textfield that contains JSON-serialized dictionaries."""
|
||||||
|
|
||||||
|
# Used so to_python() is called
|
||||||
|
__metaclass__ = models.SubfieldBase
|
||||||
|
|
||||||
|
def to_python(self, value):
|
||||||
|
"""Convert our string value to python after we load it from the DB"""
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
value = json.loads(value, object_hook=from_json)
|
||||||
|
except: #this is required to load fixtures
|
||||||
|
value = eval(value)
|
||||||
|
assert isinstance(value, dict)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def get_db_prep_save(self, value):
|
||||||
|
"""Convert our JSON object to a string before we save"""
|
||||||
|
assert isinstance(value, dict)
|
||||||
|
value = json.dumps(value, default=to_json)
|
||||||
|
return super(DictField, self).get_db_prep_save(value)
|
||||||
|
|
||||||
|
class TupleField(models.TextField):
|
||||||
|
"""TupleField is a textfield that contains JSON-serialized tuples."""
|
||||||
|
|
||||||
|
# Used so to_python() is called
|
||||||
|
__metaclass__ = models.SubfieldBase
|
||||||
|
|
||||||
|
def to_python(self, value):
|
||||||
|
"""Convert our string value to JSON after we load it from the DB"""
|
||||||
|
if isinstance(value, tuple):
|
||||||
|
return value
|
||||||
|
|
||||||
|
try:
|
||||||
|
value = json.loads(value, object_hook=from_json)
|
||||||
|
except: #this is required to load fixtures
|
||||||
|
value = eval(value)
|
||||||
|
assert isinstance(value, list)
|
||||||
|
return tuple(value)
|
||||||
|
|
||||||
|
def get_db_prep_save(self, value):
|
||||||
|
"""Convert our JSON object to a string before we save"""
|
||||||
|
assert isinstance(value, tuple)
|
||||||
|
value = json.dumps(value, default=to_json)
|
||||||
|
return super(TupleField, self).get_db_prep_save(value)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from south.modelsinspector import add_introspection_rules
|
||||||
|
add_introspection_rules([], ["^oxdjango\.fields\.DictField"])
|
||||||
|
add_introspection_rules([], ["^oxdjango\.fields\.TupleField"])
|
||||||
|
except:
|
||||||
|
pass
|
34
ox/django/http.py
Normal file
34
ox/django/http.py
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# vi:si:et:sw=4:sts=4:ts=4
|
||||||
|
import os
|
||||||
|
import mimetypes
|
||||||
|
|
||||||
|
from django.http import HttpResponse, Http404
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
|
||||||
|
def HttpFileResponse(path, content_type=None, filename=None):
|
||||||
|
if not os.path.exists(path):
|
||||||
|
raise Http404
|
||||||
|
if not content_type:
|
||||||
|
content_type = mimetypes.guess_type(path)[0]
|
||||||
|
if settings.XACCELREDIRECT:
|
||||||
|
response = HttpResponse()
|
||||||
|
response['Content-Length'] = os.stat(path).st_size
|
||||||
|
if path.startswith(settings.STATIC_ROOT):
|
||||||
|
path = settings.STATIC_URL + path[len(settings.STATIC_ROOT)+1:]
|
||||||
|
if path.startswith(settings.MEDIA_ROOT):
|
||||||
|
path = settings.MEDIA_URL + path[len(settings.MEDIA_ROOT)+1:]
|
||||||
|
response['X-Accel-Redirect'] = path
|
||||||
|
response['Content-Type'] = content_type
|
||||||
|
elif settings.XSENDFILE:
|
||||||
|
response = HttpResponse()
|
||||||
|
response['X-Sendfile'] = path
|
||||||
|
response['Content-Type'] = content_type
|
||||||
|
response['Content-Length'] = os.stat(path).st_size
|
||||||
|
else:
|
||||||
|
response = HttpResponse(open(path), content_type=content_type)
|
||||||
|
if filename:
|
||||||
|
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
|
||||||
|
return response
|
||||||
|
|
15
ox/django/middleware.py
Normal file
15
ox/django/middleware.py
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# vi:si:et:sw=4:sts=4:ts=4
|
||||||
|
|
||||||
|
from shortcuts import HttpErrorJson, render_to_json_response
|
||||||
|
|
||||||
|
class ExceptionMiddleware(object):
|
||||||
|
def process_exception(self, request, exception):
|
||||||
|
if isinstance(exception, HttpErrorJson):
|
||||||
|
return render_to_json_response(exception.response)
|
||||||
|
return None
|
||||||
|
|
||||||
|
class ChromeFrameMiddleware(object):
|
||||||
|
def process_response(self, request, response):
|
||||||
|
response['X-UA-Compatible'] = 'chrome=1'
|
||||||
|
return response
|
113
ox/django/monitor.py
Normal file
113
ox/django/monitor.py
Normal file
|
@ -0,0 +1,113 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# vi:si:et:sw=4:sts=4:ts=4
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
import atexit
|
||||||
|
import Queue
|
||||||
|
|
||||||
|
_interval = 1.0
|
||||||
|
_times = {}
|
||||||
|
_files = []
|
||||||
|
|
||||||
|
_running = False
|
||||||
|
_queue = Queue.Queue()
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
def _restart(path):
|
||||||
|
_queue.put(True)
|
||||||
|
prefix = 'monitor (pid=%d):' % os.getpid()
|
||||||
|
print >> sys.stderr, '%s Change detected to \'%s\'.' % (prefix, path)
|
||||||
|
print >> sys.stderr, '%s Triggering process restart.' % prefix
|
||||||
|
os.kill(os.getpid(), signal.SIGINT)
|
||||||
|
|
||||||
|
def _modified(path):
|
||||||
|
try:
|
||||||
|
# If path doesn't denote a file and were previously
|
||||||
|
# tracking it, then it has been removed or the file type
|
||||||
|
# has changed so force a restart. If not previously
|
||||||
|
# tracking the file then we can ignore it as probably
|
||||||
|
# pseudo reference such as when file extracted from a
|
||||||
|
# collection of modules contained in a zip file.
|
||||||
|
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
return path in _times
|
||||||
|
|
||||||
|
# Check for when file last modified.
|
||||||
|
|
||||||
|
mtime = os.stat(path).st_mtime
|
||||||
|
if path not in _times:
|
||||||
|
_times[path] = mtime
|
||||||
|
|
||||||
|
# Force restart when modification time has changed, even
|
||||||
|
# if time now older, as that could indicate older file
|
||||||
|
# has been restored.
|
||||||
|
|
||||||
|
if mtime != _times[path]:
|
||||||
|
return True
|
||||||
|
except:
|
||||||
|
# If any exception occured, likely that file has been
|
||||||
|
# been removed just before stat(), so force a restart.
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _monitor():
|
||||||
|
while 1:
|
||||||
|
# Check modification times on all files in sys.modules.
|
||||||
|
|
||||||
|
for module in sys.modules.values():
|
||||||
|
if not hasattr(module, '__file__'):
|
||||||
|
continue
|
||||||
|
path = getattr(module, '__file__')
|
||||||
|
if not path:
|
||||||
|
continue
|
||||||
|
if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
|
||||||
|
path = path[:-1]
|
||||||
|
if _modified(path):
|
||||||
|
return _restart(path)
|
||||||
|
|
||||||
|
# Check modification times on files which have
|
||||||
|
# specifically been registered for monitoring.
|
||||||
|
|
||||||
|
for path in _files:
|
||||||
|
if _modified(path):
|
||||||
|
return _restart(path)
|
||||||
|
|
||||||
|
# Go to sleep for specified interval.
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _queue.get(timeout=_interval)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
_thread = threading.Thread(target=_monitor)
|
||||||
|
_thread.setDaemon(True)
|
||||||
|
|
||||||
|
def _exiting():
|
||||||
|
try:
|
||||||
|
_queue.put(True)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
_thread.join()
|
||||||
|
|
||||||
|
atexit.register(_exiting)
|
||||||
|
|
||||||
|
def track(path):
|
||||||
|
if not path in _files:
|
||||||
|
_files.append(path)
|
||||||
|
|
||||||
|
def start(interval=1.0):
|
||||||
|
global _interval
|
||||||
|
if interval < _interval:
|
||||||
|
_interval = interval
|
||||||
|
|
||||||
|
global _running
|
||||||
|
_lock.acquire()
|
||||||
|
if not _running:
|
||||||
|
_running = True
|
||||||
|
_thread.start()
|
||||||
|
_lock.release()
|
38
ox/django/shortcuts.py
Normal file
38
ox/django/shortcuts.py
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# vi:si:et:sw=4:sts=4:ts=4
|
||||||
|
from django.http import HttpResponse, Http404
|
||||||
|
try:
|
||||||
|
import simplejson as json
|
||||||
|
except ImportError:
|
||||||
|
from django.utils import simplejson as json
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
class HttpErrorJson(Http404):
|
||||||
|
def __init__(self, response):
|
||||||
|
self.response = response
|
||||||
|
|
||||||
|
def json_response(data={}, status=200, text='ok'):
|
||||||
|
return {'status': {'code': status, 'text': text}, 'data': data}
|
||||||
|
|
||||||
|
def render_to_json_response(dictionary, content_type="text/json", status=200):
|
||||||
|
indent=None
|
||||||
|
if settings.DEBUG:
|
||||||
|
content_type = "text/javascript"
|
||||||
|
indent = 2
|
||||||
|
if settings.JSON_DEBUG:
|
||||||
|
print json.dumps(dictionary, indent=2)
|
||||||
|
if 'status' in dictionary and 'code' in dictionary['status']:
|
||||||
|
status = dictionary['status']['code']
|
||||||
|
return HttpResponse(json.dumps(dictionary, indent=indent),
|
||||||
|
content_type=content_type, status=status)
|
||||||
|
|
||||||
|
def get_object_or_404_json(klass, *args, **kwargs):
|
||||||
|
from django.shortcuts import _get_queryset
|
||||||
|
queryset = _get_queryset(klass)
|
||||||
|
try:
|
||||||
|
return queryset.get(*args, **kwargs)
|
||||||
|
except queryset.model.DoesNotExist:
|
||||||
|
response = {'status': {'code': 404,
|
||||||
|
'text': '%s not found' % queryset.model._meta.object_name}}
|
||||||
|
raise HttpErrorJson(response)
|
||||||
|
|
41
ox/django/utils.py
Normal file
41
ox/django/utils.py
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
from django.http import HttpResponse,Http404
|
||||||
|
from django.core.servers.basehttp import FileWrapper
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
import mimetypes
|
||||||
|
import os
|
||||||
|
|
||||||
|
def basic_sendfile(fname,download_name=None):
|
||||||
|
if not os.path.exists(fname):
|
||||||
|
raise Http404
|
||||||
|
|
||||||
|
wrapper = FileWrapper(open(fname,"r"))
|
||||||
|
|
||||||
|
content_type = mimetypes.guess_type(fname)[0]
|
||||||
|
response = HttpResponse(wrapper, content_type=content_type)
|
||||||
|
response['Content-Length'] = os.path.getsize(fname)
|
||||||
|
|
||||||
|
if download_name:
|
||||||
|
response['Content-Disposition'] = "attachment; filename=%s"%download_name
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
def x_sendfile(fname,download_name=None):
|
||||||
|
if not os.path.exists(fname):
|
||||||
|
raise Http404
|
||||||
|
|
||||||
|
content_type = mimetypes.guess_type(fname)[0]
|
||||||
|
response = HttpResponse('', content_type=content_type)
|
||||||
|
response['Content-Length'] = os.path.getsize(fname)
|
||||||
|
response['X-Sendfile'] = fname
|
||||||
|
|
||||||
|
if download_name:
|
||||||
|
response['Content-Disposition'] = "attachment; filename=%s"%download_name
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
if getattr(settings,'SENDFILE',False) == 'x_sendfile':
|
||||||
|
sendfile = x_sendfile
|
||||||
|
else:
|
||||||
|
sendfile = basic_sendfile
|
||||||
|
|
9
ox/django/widgets.py
Normal file
9
ox/django/widgets.py
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
import django.newforms as forms
|
||||||
|
from string import Template
|
||||||
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
|
class FirefoggWidget(forms.FileInput):
|
||||||
|
def render(self, name, value, attrs=None):
|
||||||
|
tpl = Template(u"""<h1>This should be a Firefogg widget for $name, current value: $value</h1>""")
|
||||||
|
return mark_safe(tpl.substitute(name=name, value=value))
|
||||||
|
|
10
ox/utils.py
10
ox/utils.py
|
@ -2,11 +2,15 @@
|
||||||
# vi:si:et:sw=4:sts=4:ts=4
|
# vi:si:et:sw=4:sts=4:ts=4
|
||||||
try:
|
try:
|
||||||
from django.utils.datetime_safe import datetime
|
from django.utils.datetime_safe import datetime
|
||||||
except:
|
except ImportError:
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import simplejson as json
|
import simplejson as json
|
||||||
except:
|
except ImportError:
|
||||||
import json
|
try:
|
||||||
|
import json
|
||||||
|
except ImportError:
|
||||||
|
from django.utils import simplejson as json
|
||||||
|
|
||||||
|
|
||||||
|
|
2
setup.py
2
setup.py
|
@ -22,7 +22,7 @@ setup(
|
||||||
url="http://code.0x2620.org/python-ox",
|
url="http://code.0x2620.org/python-ox",
|
||||||
download_url="http://code.0x2620.org/python-ox/download",
|
download_url="http://code.0x2620.org/python-ox/download",
|
||||||
license="GPLv3",
|
license="GPLv3",
|
||||||
packages=['ox', 'ox.torrent', 'ox.web'],
|
packages=['ox', 'ox.django'. 'ox.torrent', 'ox.web'],
|
||||||
install_requires=['chardet', 'feedparser'],
|
install_requires=['chardet', 'feedparser'],
|
||||||
keywords = [
|
keywords = [
|
||||||
],
|
],
|
||||||
|
|
Loading…
Add table
Reference in a new issue