code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
{% extends "base.html" %} {% block title %}Matrix{% endblock %} {% block content %} <h1>Matrix</h1> <table> <thead> <tr> <th scope="col"> username </th> <th scope="col"> date </th> <th scope="col"> pnum </th> <th scope="col"> light </th> <th scope="col"> temp </th> <th scope="col"> watt </th> <th scope="col"> timestamp </th> </tr> </thead> <tbody> <tr> {% for haco in object_list %} <td> {{ haco.username }} </td> <td> {{ haco.date }} </td> <td> {{ haco.pnum }} </td> <td> {{ haco.light }} </td> <td> {{ haco.temp }} </td> <td> {{ haco.watt }} </td> <td> {{ haco.timestamp }} </td> </tr> {% if not forloop.last %} {% endif %} {% endfor %} </tbody> </table> </div> </ul> {% endblock content %}
100uhaco
trunk/GAE/haco/templates/haco_list.html
HTML
asf20
821
{% extends "base.html" %} {% block title %}Login{% endblock %} {% block content %} <h1>Login</h1> <form action="{{ request.get_full_path }}" method="post"> <table>{{ form }}</table> <input type="submit" value="Login" /> </form> {% endblock content %}
100uhaco
trunk/GAE/haco/templates/login.html
HTML
asf20
256
{% extends "base.html" %} {% block title %}Report{% endblock %} {% block content %} <h1>Report</h1> <a href={{ prev_url }}>PREV</a> {% if delta %} <a href={{ next_url }}>NEXT</a> {% endif %} <br> <strong>{{ day }}</strong> <div class="chart"> <img class = "chart" src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chco=00b379&chxt=y&chxr=0,0,40&chds=0,40&chd=t: {{ t_list }} &chtt=temperature&chg=4.17,25,1,4&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'> <img class = "chart" src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chxt=y&chxr=0,0,700&chds=0,700&chd=t: {{ l_list }} &cht=lc&chtt=light&chg=4.17,14.3,1,2&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'> <img class = "chart" src='http://chart.apis.google.com/chart?chs=750x185&cht=lc&chco=009CD1&chxt=y&chxr=0,0,{{ w_scale }}&chds=0,{{ w_scale }}&chd=t: {{ w_list }} &cht=lc&chtt=watt&chg=4.17,{{ w_line}},1,2&chl=0|||||1|||||2|||||3|||||4|||||5|||||6|||||7|||||8|||||9|||||10|||||11|||||12|||||13|||||14|||||15|||||16|||||17|||||18|||||19|||||20|||||21|||||22|||||23|||||'> </div> </ul> {% endblock content %}
100uhaco
trunk/GAE/haco/templates/report.html
HTML
asf20
1,378
<html> <head> <title>100uhaco</title> </head> <body> <div id="haco_logo"> <img src={{MEDIA_URL}}"haco_logo.png" alt="haco_logo" /> </div> </body> </html>
100uhaco
trunk/GAE/haco/templates/index.html
HTML
asf20
188
{% extends "base.html" %} {% block doctype %}{% endblock %} {% block title %}Map{% endblock %} {% block js %} <script type="text/javascript" src="{{ MEDIA_URL }}combined-{{ LANGUAGE_CODE }}.js"></script> <script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script> <script type='text/javascript' src='/media/1/haco/label.js'></script> <script type='text/javascript'> {% endblock %} {% block extra-head %} function initialize() { var latlng = new google.maps.LatLng(36.054148,140.140033); var myOptions = { zoom: 10, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions) var marker1 = new google.maps.Marker({ position: new google.maps.LatLng({{ ido }},{{ kdo }}), map: map, icon:'/media/1/haco/arduino_mini.jpeg' , title: '1' }); var label1 = new Label({ map: map }); label1.bindTo('position', marker1, 'position'); label1.set('text', '消費電力:90.0W 照度:684.0lux 温度:24.3℃'); } </script> {% endblock %} {% block body %} <body onload='initialize()'> {% endblock %} {% block content %} <h1>Map</h1> <div id='map_canvas' style='width:80%; height:80%'></div> {% endblock %}
100uhaco
trunk/GAE/haco/templates/map.html
HTML
asf20
1,416
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from ragendja.template import render_to_response from django.template import Context, RequestContext, loader from django.views.generic.list_detail import object_list from django.views.generic.simple import direct_to_template from django.forms.formsets import formset_factory from haco.models import * from httpauth import * from haco.jsTime import * from haco.convert import * import logging import time import csv @http_login_required() def record( request): logging.info(request.user.username + ":" + request.GET['pnum']) mes ="<html><body>" haco =Haco(key_name= now().strftime("%Y-%m-%d") + ":" + str(request.GET['pnum']) + ":" + request.user.username) haco.user =request.user haco.username =request.user.username haco.date = today() if request.GET['pnum'] == "0": if now().strftime("%H") == "23": haco.date = tomorrow() haco.timestamp = now() mes +=request.user.username+"<br/>" if request.GET.has_key( 'pnum'): haco.pnum =int( request.GET['pnum']) mes +="pnum:"+str(haco.pnum)+"<br/>" if request.GET.has_key( 'temp'): haco.temp =float( v2T(request.GET['temp'])) mes +="temp:"+str(haco.temp)+"<br/>" if request.GET.has_key( 'light'): haco.light =float( v2L(request.GET['light'])) mes +="light:"+str(haco.light)+"<br/>" if request.GET.has_key( 'watt'): haco.watt =float( v2W(request.GET['watt'])) mes +="watt:"+str(haco.watt)+"<br/>" mes +="</body></html>" haco.put() return HttpResponse( mes) @login_required() def report( request): delta = 0 if request.GET.has_key( 'delta'): delta = int(request.GET['delta']) day = someday(delta) else: day = today() t_list = [-1.0] * 144 l_list = [-1.0] * 144 w_list = [-1.0] * 144 q =Haco.all() q =q.filter( 'user', request.user) q =q.filter( 'date', day) q =q.order( 'pnum') for h in q: t_list[h.pnum] = h.temp l_list[h.pnum] = h.light w_list[h.pnum] = h.watt if max(w_list) < 200: w_scale = 200 w_line = 25 else: w_scale = 1000 w_line = 20 return direct_to_template(request, 'report.html', { 'day' : day.strftime("%m/%d"), 'delta' : delta, 'prev_url' : "./?delta="+str(delta -1 ), 'next_url' : "./?delta="+str(delta +1 ), 't_list': chartmake(t_list), 'l_list': chartmake(l_list), 'w_list': chartmake(w_list), 'w_scale': w_scale, 'w_line': w_line, }) def chartmake( a_list): chart ="" for data in a_list: chart += str(data) +"," chart = chart[0:len(chart)-1] return chart @login_required() def matrix( request): if request.GET.has_key( 'delta'): day = someday(int(request.GET['delta'])) else: day = today() q =Haco.all() q =q.filter( 'user', request.user) q =q.filter( 'date', day) q =q.order( 'pnum') return object_list( request, q) @login_required def map( request): return direct_to_template(request, 'map.html', { 'ido': str(36.054148), 'kdo': str(140.140033), }) @login_required def feed( request): delta = 0 if request.GET.has_key( 'delta'): delta = int(request.GET['delta']) day = someday(delta) else: day = today() q =Haco.all() q =q.filter( 'user', request.user) q =q.filter( 'date', day) q =q.order( 'pnum') return object_list( request, queryset=q ,template_name="feed.xml" ,extra_context = {'date':day.strftime("%Y-%m-%d"), 'username':request.user.username} ,mimetype="application/xml") @login_required def csv( request): delta = 0 if request.GET.has_key( 'delta'): delta = int(request.GET['delta']) day = someday(delta) else: day = today() mes ="" q =Haco.all() q =q.filter( 'user', request.user) q =q.filter( 'date', day) q =q.order( 'pnum') mes = "" for h in q: mes += str(h.username)+"," mes += str(h.date)+"," mes += str(h.pnum)+"," mes += str(h.light)+"," mes += str(h.temp)+"," mes += str(h.watt)+"," mes += str(h.timestamp) mes +="\n" return HttpResponse(mes,mimetype = "text/plain" ) @login_required def test( request): if request.GET.has_key( 'delta'): day = someday(int(request.GET['delta'])) else: day = today() q =Haco.all() q =q.filter( 'user', request.user) q =q.filter( 'date', day) q =q.order( 'pnum') return object_list( request, q, template_name = "test.html", extra_context ={ 'count': len(q), } )
100uhaco
trunk/GAE/haco/views.py
Python
asf20
5,258
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from ragendja.template import render_to_response from django.template import Context, loader from django.views.generic.list_detail import object_list from haco.models import * from httpauth import * from haco.jsTime import *
100uhaco
trunk/GAE/haco/cron.py
Python
asf20
455
from django.contrib import admin from haco.models import HacoUser, Haco class HacoUserAdmin( admin.ModelAdmin): list_display =( 'user', 'prefecture', 'city') class HacoAdmin( admin.ModelAdmin): list_display =( 'temp', 'light', 'watt', 'date') admin.site.register( HacoUser) admin.site.register( Haco)
100uhaco
trunk/GAE/haco/admin.py
Python
asf20
312
# -*- coding: utf-8 -*- from datetime import * def now(): return datetime.now() + timedelta(hours=9) def today(): return now().replace(hour=0,minute=0,second=0,microsecond=0) def tomorrow(): return (now() + timedelta(days=1)).replace(hour=0,minute=0,second=0,microsecond=0) def someday(delta): return (now() + timedelta(days=delta)).replace(hour=0,minute=0,second=0,microsecond=0)
100uhaco
trunk/GAE/haco/jsTime.py
Python
asf20
413
from ragendja.settings_post import settings settings.add_app_media('combined-%(LANGUAGE_DIR)s.css', 'blueprintcss/reset.css', 'blueprintcss/typography.css', 'blueprintcss/forms.css', 'blueprintcss/grid.css', 'blueprintcss/lang-%(LANGUAGE_DIR)s.css', ) settings.add_app_media('combined-print-%(LANGUAGE_DIR)s.css', 'blueprintcss/print.css', ) settings.add_app_media('ie.css', 'blueprintcss/ie.css', )
100uhaco
trunk/GAE/blueprintcss/settings.py
Python
asf20
428
/* -------------------------------------------------------------- typography.css * Sets up some sensible default typography. -------------------------------------------------------------- */ /* Default font settings. The font-size percentage is of 16px. (0.75 * 16px = 12px) */ body { font-size: 75%; color: #222; background: #fff; font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; } /* Headings -------------------------------------------------------------- */ h1,h2,h3,h4,h5,h6 { font-weight: normal; color: #111; } h1 { font-size: 3em; line-height: 1; margin-bottom: 0.5em; } h2 { font-size: 2em; margin-bottom: 0.75em; } h3 { font-size: 1.5em; line-height: 1; margin-bottom: 1em; } h4 { font-size: 1.2em; line-height: 1.25; margin-bottom: 1.25em; } h5 { font-size: 1em; font-weight: bold; margin-bottom: 1.5em; } h6 { font-size: 1em; font-weight: bold; } h1 img, h2 img, h3 img, h4 img, h5 img, h6 img { margin: 0; } /* Text elements -------------------------------------------------------------- */ p { margin: 0 0 1.5em; } p img.left { float: left; margin: 1.5em 1.5em 1.5em 0; padding: 0; } p img.right { float: right; margin: 1.5em 0 1.5em 1.5em; } a:focus, a:hover { color: #000; } a { color: #009; text-decoration: underline; } blockquote { margin: 1.5em; color: #666; font-style: italic; } strong { font-weight: bold; } em,dfn { font-style: italic; } dfn { font-weight: bold; } sup, sub { line-height: 0; } abbr, acronym { border-bottom: 1px dotted #666; } address { margin: 0 0 1.5em; font-style: italic; } del { color:#666; } pre { margin: 1.5em 0; white-space: pre; } pre,code,tt { font: 1em 'andale mono', 'lucida console', monospace; line-height: 1.5; } /* Lists -------------------------------------------------------------- */ li ul, li ol { margin:0 1.5em; } ul, ol { margin: 0 1.5em 1.5em 1.5em; } ul { list-style-type: disc; } ol { list-style-type: decimal; } dl { margin: 0 0 1.5em 0; } dl dt { font-weight: bold; } dd { margin-left: 1.5em;} /* Tables -------------------------------------------------------------- */ table { margin-bottom: 1.4em; width:100%; } th { font-weight: bold; } thead th { background: #c3d9ff; } th,td,caption { padding: 4px 10px 4px 5px; } tr.even td { background: #e5ecf9; } tfoot { font-style: italic; } caption { background: #eee; } /* Misc classes -------------------------------------------------------------- */ .small { font-size: .8em; margin-bottom: 1.875em; line-height: 1.875em; } .large { font-size: 1.2em; line-height: 2.5em; margin-bottom: 1.25em; } .hide { display: none; } .quiet { color: #666; } .loud { color: #000; } .highlight { background:#ff0; } .added { background:#060; color: #fff; } .removed { background:#900; color: #fff; } .first { margin-left:0; padding-left:0; } .last { margin-right:0; padding-right:0; } .top { margin-top:0; padding-top:0; } .bottom { margin-bottom:0; padding-bottom:0; }
100uhaco
trunk/GAE/blueprintcss/media/typography.css
CSS
asf20
3,149
/* -------------------------------------------------------------- rtl.css * Mirrors Blueprint for left-to-right languages By Ran Yaniv Hartstein [ranh.co.il] -------------------------------------------------------------- */ body .container { direction: rtl; } body .column { float: right; margin-right: 0; margin-left: 10px; } body div.last { margin-left: 0; } body table .last { padding-left: 0; } body .append-1 { padding-right: 0; padding-left: 40px; } body .append-2 { padding-right: 0; padding-left: 80px; } body .append-3 { padding-right: 0; padding-left: 120px; } body .append-4 { padding-right: 0; padding-left: 160px; } body .append-5 { padding-right: 0; padding-left: 200px; } body .append-6 { padding-right: 0; padding-left: 240px; } body .append-7 { padding-right: 0; padding-left: 280px; } body .append-8 { padding-right: 0; padding-left: 320px; } body .append-9 { padding-right: 0; padding-left: 360px; } body .append-10 { padding-right: 0; padding-left: 400px; } body .append-11 { padding-right: 0; padding-left: 440px; } body .append-12 { padding-right: 0; padding-left: 480px; } body .append-13 { padding-right: 0; padding-left: 520px; } body .append-14 { padding-right: 0; padding-left: 560px; } body .append-15 { padding-right: 0; padding-left: 600px; } body .append-16 { padding-right: 0; padding-left: 640px; } body .append-17 { padding-right: 0; padding-left: 680px; } body .append-18 { padding-right: 0; padding-left: 720px; } body .append-19 { padding-right: 0; padding-left: 760px; } body .append-20 { padding-right: 0; padding-left: 800px; } body .append-21 { padding-right: 0; padding-left: 840px; } body .append-22 { padding-right: 0; padding-left: 880px; } body .append-23 { padding-right: 0; padding-left: 920px; } body .prepend-1 { padding-left: 0; padding-right: 40px; } body .prepend-2 { padding-left: 0; padding-right: 80px; } body .prepend-3 { padding-left: 0; padding-right: 120px; } body .prepend-4 { padding-left: 0; padding-right: 160px; } body .prepend-5 { padding-left: 0; padding-right: 200px; } body .prepend-6 { padding-left: 0; padding-right: 240px; } body .prepend-7 { padding-left: 0; padding-right: 280px; } body .prepend-8 { padding-left: 0; padding-right: 320px; } body .prepend-9 { padding-left: 0; padding-right: 360px; } body .prepend-10 { padding-left: 0; padding-right: 400px; } body .prepend-11 { padding-left: 0; padding-right: 440px; } body .prepend-12 { padding-left: 0; padding-right: 480px; } body .prepend-13 { padding-left: 0; padding-right: 520px; } body .prepend-14 { padding-left: 0; padding-right: 560px; } body .prepend-15 { padding-left: 0; padding-right: 600px; } body .prepend-16 { padding-left: 0; padding-right: 640px; } body .prepend-17 { padding-left: 0; padding-right: 680px; } body .prepend-18 { padding-left: 0; padding-right: 720px; } body .prepend-19 { padding-left: 0; padding-right: 760px; } body .prepend-20 { padding-left: 0; padding-right: 800px; } body .prepend-21 { padding-left: 0; padding-right: 840px; } body .prepend-22 { padding-left: 0; padding-right: 880px; } body .prepend-23 { padding-left: 0; padding-right: 920px; } body .border { padding-right: 0; padding-left: 4px; margin-right: 0; margin-left: 5px; border-right: none; border-left: 1px solid #eee; } body .colborder { padding-right: 0; padding-left: 24px; margin-right: 0; margin-left: 25px; border-right: none; border-left: 1px solid #eee; } body .pull-1 { margin-left: 0; margin-right: -40px; } body .pull-2 { margin-left: 0; margin-right: -80px; } body .pull-3 { margin-left: 0; margin-right: -120px; } body .pull-4 { margin-left: 0; margin-right: -160px; } body .push-0 { margin: 0 18px 0 0; } body .push-1 { margin: 0 18px 0 -40px; } body .push-2 { margin: 0 18px 0 -80px; } body .push-3 { margin: 0 18px 0 -120px; } body .push-4 { margin: 0 18px 0 -160px; } body .push-0, body .push-1, body .push-2, body .push-3, body .push-4 { float: left; } /* Typography with RTL support */ body h1,body h2,body h3, body h4,body h5,body h6 { font-family: Arial, sans-serif; } html body { font-family: Arial, sans-serif; } body pre,body code,body tt { font-family: monospace; } /* Mirror floats and margins on typographic elements */ body p img { float: right; margin: 1.5em 0 1.5em 1.5em; } body dd, body ul, body ol { margin-left: 0; margin-right: 1.5em;} body td, body th { text-align:right; }
100uhaco
trunk/GAE/blueprintcss/media/lang-rtl.css
CSS
asf20
4,477
/* -------------------------------------------------------------- forms.css * Sets up some default styling for forms * Gives you classes to enhance your forms Usage: * For text fields, use class .title or .text -------------------------------------------------------------- */ label { font-weight: bold; } fieldset { padding:1.4em; margin: 0 0 1.5em 0; border: 1px solid #ccc; } legend { font-weight: bold; font-size:1.2em; } /* Form fields -------------------------------------------------------------- */ input.text, input.title, textarea, select { margin:0.5em 0; border:1px solid #bbb; } input.text:focus, input.title:focus, textarea:focus, select:focus { border:1px solid #666; } input.text, input.title { width: 300px; padding:5px; } input.title { font-size:1.5em; } textarea { width: 390px; height: 250px; padding:5px; } /* Success, notice and error boxes -------------------------------------------------------------- */ .error, .notice, .success { padding: .8em; margin-bottom: 1em; border: 2px solid #ddd; } .error { background: #FBE3E4; color: #8a1f11; border-color: #FBC2C4; } .notice { background: #FFF6BF; color: #514721; border-color: #FFD324; } .success { background: #E6EFC2; color: #264409; border-color: #C6D880; } .error a { color: #8a1f11; } .notice a { color: #514721; } .success a { color: #264409; }
100uhaco
trunk/GAE/blueprintcss/media/forms.css
CSS
asf20
1,414
/* -------------------------------------------------------------- print.css * Gives you some sensible styles for printing pages. * See Readme file in this directory for further instructions. Some additions you'll want to make, customized to your markup: #header, #footer, #navigation { display:none; } -------------------------------------------------------------- */ body { line-height: 1.5; font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; color:#000; background: none; font-size: 10pt; } /* Layout -------------------------------------------------------------- */ .container { background: none; } hr { background:#ccc; color:#ccc; width:100%; height:2px; margin:2em 0; padding:0; border:none; } hr.space { background: #fff; color: #fff; } /* Text -------------------------------------------------------------- */ h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; } code { font:.9em "Courier New", Monaco, Courier, monospace; } img { float:left; margin:1.5em 1.5em 1.5em 0; } a img { border:none; } p img.top { margin-top: 0; } blockquote { margin:1.5em; padding:1em; font-style:italic; font-size:.9em; } .small { font-size: .9em; } .large { font-size: 1.1em; } .quiet { color: #999; } .hide { display:none; } /* Links -------------------------------------------------------------- */ a:link, a:visited { background: transparent; font-weight:700; text-decoration: underline; } a:link:after, a:visited:after { content: " (" attr(href) ")"; font-size: 90%; } /* If you're having trouble printing relative links, uncomment and customize this: (note: This is valid CSS3, but it still won't go through the W3C CSS Validator) */ /* a[href^="/"]:after { content: " (http://www.yourdomain.com" attr(href) ") "; } */
100uhaco
trunk/GAE/blueprintcss/media/print.css
CSS
asf20
1,867
/* -------------------------------------------------------------- reset.css * Resets default browser CSS. -------------------------------------------------------------- */ html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; } body { line-height: 1.5; } /* Tables still need 'cellspacing="0"' in the markup. */ table { border-collapse: separate; border-spacing: 0; } caption, th, td { text-align: left; font-weight: normal; } table, td, th { vertical-align: middle; } /* Remove possible quote marks (") from <q>, <blockquote>. */ blockquote:before, blockquote:after, q:before, q:after { content: ""; } blockquote, q { quotes: "" ""; } /* Remove annoying border on linked images. */ a img { border: none; }
100uhaco
trunk/GAE/blueprintcss/media/reset.css
CSS
asf20
1,077
/* -------------------------------------------------------------- ie.css Contains every hack for Internet Explorer, so that our core files stay sweet and nimble. -------------------------------------------------------------- */ /* Fixes IE margin bugs */ * html .column, * html div.span-1, * html div.span-2, * html div.span-3, * html div.span-4, * html div.span-5, * html div.span-6, * html div.span-7, * html div.span-8, * html div.span-9, * html div.span-10, * html div.span-11, * html div.span-12, * html div.span-13, * html div.span-14, * html div.span-15, * html div.span-16, * html div.span-17, * html div.span-18, * html div.span-19, * html div.span-20, * html div.span-21, * html div.span-22, * html div.span-23, * html div.span-24 { overflow-x: hidden; } /* Elements -------------------------------------------------------------- */ /* Fixes incorrect styling of legend in IE6. */ * html legend { margin:0px -8px 16px 0; padding:0; } /* Fixes incorrect placement of ol numbers in IE6/7. */ ol { margin-left:2em; } /* Fixes wrong line-height on sup/sub in IE. */ sup { vertical-align: text-top; } sub { vertical-align: text-bottom; } /* Fixes IE7 missing wrapping of code elements. */ html>body p code { *white-space: normal; } /* IE 6&7 has problems with setting proper <hr> margins. */ hr { margin: -8px auto 11px; } /* Explicitly set interpolation, allowing dynamically resized images to not look horrible */ img { -ms-interpolation-mode: bicubic; } /* Clearing -------------------------------------------------------------- */ /* Makes clearfix actually work in IE */ .clearfix, .container {display: inline-block;} * html .clearfix, * html .container {height: 1%;} /* Forms -------------------------------------------------------------- */ /* Fixes padding on fieldset */ fieldset {padding-top: 0;}
100uhaco
trunk/GAE/blueprintcss/media/ie.css
CSS
asf20
1,861
/* -------------------------------------------------------------- grid.css - mirror version of src/grid.css -------------------------------------------------------------- */ /* A container should group all your columns. */ .container { width: 950px; margin: 0 auto; } /* Use this class on any div.span / container to see the grid. */ .showgrid { background: url(grid.png); } /* Columns -------------------------------------------------------------- */ /* Sets up basic grid floating and margin. */ .column, div.span-1, div.span-2, div.span-3, div.span-4, div.span-5, div.span-6, div.span-7, div.span-8, div.span-9, div.span-10, div.span-11, div.span-12, div.span-13, div.span-14, div.span-15, div.span-16, div.span-17, div.span-18, div.span-19, div.span-20, div.span-21, div.span-22, div.span-23, div.span-24 { float: left; margin-right: 10px; } /* The last column in a row needs this class. */ .last, div.last { margin-right: 0; } /* Use these classes to set the width of a column. */ .span-1 {width: 30px;} .span-2 {width: 70px;} .span-3 {width: 110px;} .span-4 {width: 150px;} .span-5 {width: 190px;} .span-6 {width: 230px;} .span-7 {width: 270px;} .span-8 {width: 310px;} .span-9 {width: 350px;} .span-10 {width: 390px;} .span-11 {width: 430px;} .span-12 {width: 470px;} .span-13 {width: 510px;} .span-14 {width: 550px;} .span-15 {width: 590px;} .span-16 {width: 630px;} .span-17 {width: 670px;} .span-18 {width: 710px;} .span-19 {width: 750px;} .span-20 {width: 790px;} .span-21 {width: 830px;} .span-22 {width: 870px;} .span-23 {width: 910px;} .span-24, div.span-24 { width:950px; margin:0; } /* Use these classes to set the width of an input. */ input.span-1, textarea.span-1, input.span-2, textarea.span-2, input.span-3, textarea.span-3, input.span-4, textarea.span-4, input.span-5, textarea.span-5, input.span-6, textarea.span-6, input.span-7, textarea.span-7, input.span-8, textarea.span-8, input.span-9, textarea.span-9, input.span-10, textarea.span-10, input.span-11, textarea.span-11, input.span-12, textarea.span-12, input.span-13, textarea.span-13, input.span-14, textarea.span-14, input.span-15, textarea.span-15, input.span-16, textarea.span-16, input.span-17, textarea.span-17, input.span-18, textarea.span-18, input.span-19, textarea.span-19, input.span-20, textarea.span-20, input.span-21, textarea.span-21, input.span-22, textarea.span-22, input.span-23, textarea.span-23, input.span-24, textarea.span-24 { border-left-width: 1px!important; border-right-width: 1px!important; padding-left: 5px!important; padding-right: 5px!important; } input.span-1, textarea.span-1 { width: 18px!important; } input.span-2, textarea.span-2 { width: 58px!important; } input.span-3, textarea.span-3 { width: 98px!important; } input.span-4, textarea.span-4 { width: 138px!important; } input.span-5, textarea.span-5 { width: 178px!important; } input.span-6, textarea.span-6 { width: 218px!important; } input.span-7, textarea.span-7 { width: 258px!important; } input.span-8, textarea.span-8 { width: 298px!important; } input.span-9, textarea.span-9 { width: 338px!important; } input.span-10, textarea.span-10 { width: 378px!important; } input.span-11, textarea.span-11 { width: 418px!important; } input.span-12, textarea.span-12 { width: 458px!important; } input.span-13, textarea.span-13 { width: 498px!important; } input.span-14, textarea.span-14 { width: 538px!important; } input.span-15, textarea.span-15 { width: 578px!important; } input.span-16, textarea.span-16 { width: 618px!important; } input.span-17, textarea.span-17 { width: 658px!important; } input.span-18, textarea.span-18 { width: 698px!important; } input.span-19, textarea.span-19 { width: 738px!important; } input.span-20, textarea.span-20 { width: 778px!important; } input.span-21, textarea.span-21 { width: 818px!important; } input.span-22, textarea.span-22 { width: 858px!important; } input.span-23, textarea.span-23 { width: 898px!important; } input.span-24, textarea.span-24 { width: 938px!important; } /* Add these to a column to append empty cols. */ .append-1 { padding-right: 40px;} .append-2 { padding-right: 80px;} .append-3 { padding-right: 120px;} .append-4 { padding-right: 160px;} .append-5 { padding-right: 200px;} .append-6 { padding-right: 240px;} .append-7 { padding-right: 280px;} .append-8 { padding-right: 320px;} .append-9 { padding-right: 360px;} .append-10 { padding-right: 400px;} .append-11 { padding-right: 440px;} .append-12 { padding-right: 480px;} .append-13 { padding-right: 520px;} .append-14 { padding-right: 560px;} .append-15 { padding-right: 600px;} .append-16 { padding-right: 640px;} .append-17 { padding-right: 680px;} .append-18 { padding-right: 720px;} .append-19 { padding-right: 760px;} .append-20 { padding-right: 800px;} .append-21 { padding-right: 840px;} .append-22 { padding-right: 880px;} .append-23 { padding-right: 920px;} /* Add these to a column to prepend empty cols. */ .prepend-1 { padding-left: 40px;} .prepend-2 { padding-left: 80px;} .prepend-3 { padding-left: 120px;} .prepend-4 { padding-left: 160px;} .prepend-5 { padding-left: 200px;} .prepend-6 { padding-left: 240px;} .prepend-7 { padding-left: 280px;} .prepend-8 { padding-left: 320px;} .prepend-9 { padding-left: 360px;} .prepend-10 { padding-left: 400px;} .prepend-11 { padding-left: 440px;} .prepend-12 { padding-left: 480px;} .prepend-13 { padding-left: 520px;} .prepend-14 { padding-left: 560px;} .prepend-15 { padding-left: 600px;} .prepend-16 { padding-left: 640px;} .prepend-17 { padding-left: 680px;} .prepend-18 { padding-left: 720px;} .prepend-19 { padding-left: 760px;} .prepend-20 { padding-left: 800px;} .prepend-21 { padding-left: 840px;} .prepend-22 { padding-left: 880px;} .prepend-23 { padding-left: 920px;} /* Border on right hand side of a column. */ div.border { padding-right: 4px; margin-right: 5px; border-right: 1px solid #eee; } /* Border with more whitespace, spans one column. */ div.colborder { padding-right: 24px; margin-right: 25px; border-right: 1px solid #eee; } /* Use these classes on an element to push it into the next column, or to pull it into the previous column. */ .pull-1 { margin-left: -40px; } .pull-2 { margin-left: -80px; } .pull-3 { margin-left: -120px; } .pull-4 { margin-left: -160px; } .pull-5 { margin-left: -200px; } .pull-6 { margin-left: -240px; } .pull-7 { margin-left: -280px; } .pull-8 { margin-left: -320px; } .pull-9 { margin-left: -360px; } .pull-10 { margin-left: -400px; } .pull-11 { margin-left: -440px; } .pull-12 { margin-left: -480px; } .pull-13 { margin-left: -520px; } .pull-14 { margin-left: -560px; } .pull-15 { margin-left: -600px; } .pull-16 { margin-left: -640px; } .pull-17 { margin-left: -680px; } .pull-18 { margin-left: -720px; } .pull-19 { margin-left: -760px; } .pull-20 { margin-left: -800px; } .pull-21 { margin-left: -840px; } .pull-22 { margin-left: -880px; } .pull-23 { margin-left: -920px; } .pull-24 { margin-left: -960px; } .pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float: left; position:relative;} .push-1 { margin: 0 -40px 1.5em 40px; } .push-2 { margin: 0 -80px 1.5em 80px; } .push-3 { margin: 0 -120px 1.5em 120px; } .push-4 { margin: 0 -160px 1.5em 160px; } .push-5 { margin: 0 -200px 1.5em 200px; } .push-6 { margin: 0 -240px 1.5em 240px; } .push-7 { margin: 0 -280px 1.5em 280px; } .push-8 { margin: 0 -320px 1.5em 320px; } .push-9 { margin: 0 -360px 1.5em 360px; } .push-10 { margin: 0 -400px 1.5em 400px; } .push-11 { margin: 0 -440px 1.5em 440px; } .push-12 { margin: 0 -480px 1.5em 480px; } .push-13 { margin: 0 -520px 1.5em 520px; } .push-14 { margin: 0 -560px 1.5em 560px; } .push-15 { margin: 0 -600px 1.5em 600px; } .push-16 { margin: 0 -640px 1.5em 640px; } .push-17 { margin: 0 -680px 1.5em 680px; } .push-18 { margin: 0 -720px 1.5em 720px; } .push-19 { margin: 0 -760px 1.5em 760px; } .push-20 { margin: 0 -800px 1.5em 800px; } .push-21 { margin: 0 -840px 1.5em 840px; } .push-22 { margin: 0 -880px 1.5em 880px; } .push-23 { margin: 0 -920px 1.5em 920px; } .push-24 { margin: 0 -960px 1.5em 960px; } .push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float: right; position:relative;} /* Misc classes and elements -------------------------------------------------------------- */ /* In case you need to add a gutter above/below an element */ .prepend-top { margin-top:1.5em; } .append-bottom { margin-bottom:1.5em; } /* Use a .box to create a padded box inside a column. */ .box { padding: 1.5em; margin-bottom: 1.5em; background: #E5ECF9; } /* Use this to create a horizontal ruler across a column. */ hr { background: #ddd; color: #ddd; clear: both; float: none; width: 100%; height: .1em; margin: 0 0 1.45em; border: none; } hr.space { background: #fff; color: #fff; } /* Clearing floats without extra markup Based on How To Clear Floats Without Structural Markup by PiE [http://www.positioniseverything.net/easyclearing.html] */ .clearfix:after, .container:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; overflow:hidden; } .clearfix, .container {display: block;} /* Regular clearing apply to column that should drop below previous ones. */ .clear { clear:both; }
100uhaco
trunk/GAE/blueprintcss/media/grid.css
CSS
asf20
9,611
# -*- coding: utf-8 -*- from django.conf.urls.defaults import * from ragendja.urlsauto import urlpatterns from ragendja.auth.urls import urlpatterns as auth_patterns #from myapp.forms import UserRegistrationForm from django.contrib import admin from django.contrib.auth import views as auth_views from haco import views as haco_views from haco.forms import UserRegistrationForm admin.autodiscover() handler500 = 'ragendja.views.server_error' urlpatterns = auth_patterns + patterns( '', ('^admin/(.*)', admin.site.root), #(r'^$', 'django.views.generic.simple.direct_to_template', # {'template': 'main.html'}), # Override the default registration form url(r'^account/register/$', 'registration.views.register', kwargs={'form_class': UserRegistrationForm}, name='registration_register'), #url(r'^$', 'haco.views.login'), url( r'^$', auth_views.login, {'template_name': 'registration/login.html'}, name='auth_login'), (r'^accounts/change-password/$', 'django.contrib.auth.views.password_change', {'post_change_redirect': '/'}), (r'^haco/', include( 'haco.urls')), ) + urlpatterns
100uhaco
trunk/GAE/urls.py
Python
asf20
1,190
/* Add your global CSS (i.e., code that is project-specific and not part of any app) here. */ body { padding: 15px 20px; } #clickme { background-color: #eeeeee; border: 1px solid black; padding: 3px; } #footer { clear: both; }
100uhaco
trunk/GAE/media/look.css
CSS
asf20
240
*{ margin:0; padding:0; } li{ list-style-type:none;} body{ line-height:1.8; font-size:80%; }
100uhaco
trunk/GAE/media/iPhone.css
CSS
asf20
102
from ragendja.settings_post import settings if not hasattr(settings, 'ACCOUNT_ACTIVATION_DAYS'): settings.ACCOUNT_ACTIVATION_DAYS = 30
100uhaco
trunk/GAE/registration/settings.py
Python
asf20
140
from django.conf.urls.defaults import * rootpatterns = patterns('', (r'^account/', include('registration.urls')), )
100uhaco
trunk/GAE/registration/urlsauto.py
Python
asf20
121
import datetime import random import re import sha from google.appengine.ext import db from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.db import models from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ SHA1_RE = re.compile('^[a-f0-9]{40}$') class RegistrationManager(models.Manager): """ Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. """ def activate_user(self, activation_key): """ Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To prevent reactivation of an account which has been deactivated by site administrators, the activation key is reset to the string constant ``RegistrationProfile.ACTIVATED`` after successful activation. To execute customized logic when a ``User`` is activated, connect a function to the signal ``registration.signals.user_activated``; this signal will be sent (with the ``User`` as the value of the keyword argument ``user``) after a successful activation. """ from registration.signals import user_activated # Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(activation_key): profile = RegistrationProfile.get_by_key_name("key_"+activation_key) if not profile: return False if not profile.activation_key_expired(): user = profile.user user.is_active = True user.put() profile.activation_key = RegistrationProfile.ACTIVATED profile.put() user_activated.send(sender=self.model, user=user) return user return False def create_inactive_user(self, username, password, email, domain_override="", send_email=True): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. To disable the email, call with ``send_email=False``. The activation email will make use of two templates: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. It receives one context variable, ``site``, which is the currently-active ``django.contrib.sites.models.Site`` instance. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/activation_email.txt`` This template will be used for the body of the email. It will receive three context variables: ``activation_key`` will be the user's activation key (for use in constructing a URL to activate the account), ``expiration_days`` will be the number of days for which the key will be valid and ``site`` will be the currently-active ``django.contrib.sites.models.Site`` instance. To execute customized logic once the new ``User`` has been created, connect a function to the signal ``registration.signals.user_registered``; this signal will be sent (with the new ``User`` as the value of the keyword argument ``user``) after the ``User`` and ``RegistrationProfile`` have been created, and the email (if any) has been sent.. """ from registration.signals import user_registered # prepend "key_" to the key_name, because key_names can't start with numbers new_user = User(username=username, key_name="key_"+username.lower(), email=email, is_active=False) new_user.set_password(password) new_user.put() registration_profile = self.create_profile(new_user) if send_email: # from django.core.mail import send_mail # from google.appengine.api.mail import send_mail current_site = domain_override # current_site = Site.objects.get_current() subject = render_to_string('registration/activation_email_subject.txt', { 'site': current_site }) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string('registration/activation_email.txt', { 'activation_key': registration_profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': current_site }) #send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email]) # send_mail( sender =settings.DEFAULT_FROM_EMAIL, # to =[new_user.email], # subject =subject, # body =message) user_registered.send(sender=self.model, user=new_user) return new_user def create_profile(self, user): """ Create a ``RegistrationProfile`` for a given ``User``, and return the ``RegistrationProfile``. The activation key for the ``RegistrationProfile`` will be a SHA1 hash, generated from a combination of the ``User``'s username and a random salt. """ salt = sha.new(str(random.random())).hexdigest()[:5] activation_key = sha.new(salt+user.username).hexdigest() # prepend "key_" to the key_name, because key_names can't start with numbers registrationprofile = RegistrationProfile(user=user, activation_key=activation_key, key_name="key_"+activation_key) registrationprofile.put() return registrationprofile def delete_expired_users(self): """ Remove expired instances of ``RegistrationProfile`` and their associated ``User``s. Accounts to be deleted are identified by searching for instances of ``RegistrationProfile`` with expired activation keys, and then checking to see if their associated ``User`` instances have the field ``is_active`` set to ``False``; any ``User`` who is both inactive and has an expired activation key will be deleted. It is recommended that this method be executed regularly as part of your routine site maintenance; this application provides a custom management command which will call this method, accessible as ``manage.py cleanupregistration``. Regularly clearing out accounts which have never been activated serves two useful purposes: 1. It alleviates the ocasional need to reset a ``RegistrationProfile`` and/or re-send an activation email when a user does not receive or does not act upon the initial activation email; since the account will be deleted, the user will be able to simply re-register and receive a new activation key. 2. It prevents the possibility of a malicious user registering one or more accounts and never activating them (thus denying the use of those usernames to anyone else); since those accounts will be deleted, the usernames will become available for use again. If you have a troublesome ``User`` and wish to disable their account while keeping it in the database, simply delete the associated ``RegistrationProfile``; an inactive ``User`` which does not have an associated ``RegistrationProfile`` will not be deleted. """ for profile in RegistrationProfile.all(): if profile.activation_key_expired(): user = profile.user if not user.is_active: user.delete() profile.delete() class RegistrationProfile(db.Model): """ A simple profile which stores an activation key for use during user account registration. Generally, you will not want to interact directly with instances of this model; the provided manager includes methods for creating and activating new accounts, as well as for cleaning out accounts which have never been activated. While it is possible to use this model as the value of the ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do so. This model's sole purpose is to store data temporarily during account registration and activation. """ ACTIVATED = u"ALREADY_ACTIVATED" user = db.ReferenceProperty(User, verbose_name=_('user')) activation_key = db.StringProperty(_('activation key')) objects = RegistrationManager() class Meta: verbose_name = _('registration profile') verbose_name_plural = _('registration profiles') def __unicode__(self): return u"Registration information for %s" % self.user def activation_key_expired(self): """ Determine whether this ``RegistrationProfile``'s activation key has expired, returning a boolean -- ``True`` if the key has expired. Key expiration is determined by a two-step process: 1. If the user has already activated, the key will have been reset to the string constant ``ACTIVATED``. Re-activating is not permitted, and so this method returns ``True`` in this case. 2. Otherwise, the date the user signed up is incremented by the number of days specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of days after signup during which a user is allowed to activate their account); if the result is less than or equal to the current date, the key has expired and this method returns ``True``. """ expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) return self.activation_key == RegistrationProfile.ACTIVATED or \ (self.user.date_joined + expiration_date <= datetime.datetime.now()) activation_key_expired.boolean = True
100uhaco
trunk/GAE/registration/models.py
Python
asf20
11,287
""" Forms and validation code for user registration. """ from django.contrib.auth.models import User from django import forms from django.utils.translation import ugettext_lazy as _ from registration.models import RegistrationProfile # I put this on all required fields, because it's easier to pick up # on them with CSS or JavaScript if they have a class of "required" # in the HTML. Your mileage may vary. If/when Django ticket #3515 # lands in trunk, this will no longer be necessary. attrs_dict = { 'class': 'required' } class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should either preserve the base ``save()`` or implement a ``save()`` method which returns a ``User``. """ username = forms.RegexField(regex=r'^\w+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_(u'username')) email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'email address')) password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password')) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password (again)')) def clean_username(self): """ Validate that the username is alphanumeric and is not already in use. """ user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower()) if user: raise forms.ValidationError(_(u'This username is already taken. Please choose another.')) return self.cleaned_data['username'] def clean(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(_(u'You must type the same password each time')) return self.cleaned_data def save(self, domain_override=""): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User`` (by calling ``RegistrationProfile.objects.create_inactive_user()``). """ new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], domain_override=domain_override, ) return new_user class RegistrationFormTermsOfService(RegistrationForm): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict), label=_(u'I have read and agree to the Terms of Service'), error_messages={ 'required': u"You must agree to the terms to register" }) class RegistrationFormUniqueEmail(RegistrationForm): """ Subclass of ``RegistrationForm`` which enforces uniqueness of email addresses. """ def clean_email(self): """ Validate that the supplied email address is unique for the site. """ email = self.cleaned_data['email'].lower() if User.all().filter('email =', email).count(1): raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.')) return email class RegistrationFormNoFreeEmail(RegistrationForm): """ Subclass of ``RegistrationForm`` which disallows registration with email addresses from popular free webmail services; moderately useful for preventing automated spam registrations. To change the list of banned domains, subclass this form and override the attribute ``bad_domains``. """ bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com', 'googlemail.com', 'hotmail.com', 'hushmail.com', 'msn.com', 'mail.ru', 'mailinator.com', 'live.com'] def clean_email(self): """ Check the supplied email address against a list of known free webmail domains. """ email_domain = self.cleaned_data['email'].split('@')[1] if email_domain in self.bad_domains: raise forms.ValidationError(_(u'Registration using free email addresses is prohibited. Please supply a different email address.')) return self.cleaned_data['email']
100uhaco
trunk/GAE/registration/forms.py
Python
asf20
5,496
""" Unit tests for django-registration. These tests assume that you've completed all the prerequisites for getting django-registration running in the default setup, to wit: 1. You have ``registration`` in your ``INSTALLED_APPS`` setting. 2. You have created all of the templates mentioned in this application's documentation. 3. You have added the setting ``ACCOUNT_ACTIVATION_DAYS`` to your settings file. 4. You have URL patterns pointing to the registration and activation views, with the names ``registration_register`` and ``registration_activate``, respectively, and a URL pattern named 'registration_complete'. """ import datetime import sha from django.conf import settings from django.contrib.auth.models import User from django.core import mail from django.core import management from django.core.urlresolvers import reverse from django.test import TestCase from google.appengine.ext import db from registration import forms from registration.models import RegistrationProfile from registration import signals class RegistrationTestCase(TestCase): """ Base class for the test cases; this sets up two users -- one expired, one not -- which are used to exercise various parts of the application. """ def setUp(self): self.sample_user = RegistrationProfile.objects.create_inactive_user(username='alice', password='secret', email='alice@example.com') self.expired_user = RegistrationProfile.objects.create_inactive_user(username='bob', password='swordfish', email='bob@example.com') self.expired_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1) self.expired_user.save() class RegistrationModelTests(RegistrationTestCase): """ Tests for the model-oriented functionality of django-registration, including ``RegistrationProfile`` and its custom manager. """ def test_new_user_is_inactive(self): """ Test that a newly-created user is inactive. """ self.failIf(self.sample_user.is_active) def test_registration_profile_created(self): """ Test that a ``RegistrationProfile`` is created for a new user. """ self.assertEqual(RegistrationProfile.all().count(), 2) def test_activation_email(self): """ Test that user signup sends an activation email. """ self.assertEqual(len(mail.outbox), 2) def test_activation_email_disable(self): """ Test that activation email can be disabled. """ RegistrationProfile.objects.create_inactive_user(username='noemail', password='foo', email='nobody@example.com', send_email=False) self.assertEqual(len(mail.outbox), 2) def test_activation(self): """ Test that user activation actually activates the user and properly resets the activation key, and fails for an already-active or expired user, or an invalid key. """ # Activating a valid user returns the user. self.failUnlessEqual(RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key).key(), self.sample_user.key()) # The activated user must now be active. self.failUnless(User.get(self.sample_user.key()).is_active) # The activation key must now be reset to the "already activated" constant. self.failUnlessEqual(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key, RegistrationProfile.ACTIVATED) # Activating an expired user returns False. self.failIf(RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', self.expired_user).get().activation_key)) # Activating from a key that isn't a SHA1 hash returns False. self.failIf(RegistrationProfile.objects.activate_user('foo')) # Activating from a key that doesn't exist returns False. self.failIf(RegistrationProfile.objects.activate_user(sha.new('foo').hexdigest())) def test_account_expiration_condition(self): """ Test that ``RegistrationProfile.activation_key_expired()`` returns ``True`` for expired users and for active users, and ``False`` otherwise. """ # Unexpired user returns False. self.failIf(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key_expired()) # Expired user returns True. self.failUnless(RegistrationProfile.all().filter('user =', self.expired_user).get().activation_key_expired()) # Activated user returns True. RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key) self.failUnless(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key_expired()) def test_expired_user_deletion(self): """ Test that ``RegistrationProfile.objects.delete_expired_users()`` deletes only inactive users whose activation window has expired. """ RegistrationProfile.objects.delete_expired_users() self.assertEqual(RegistrationProfile.all().count(), 1) def test_management_command(self): """ Test that ``manage.py cleanupregistration`` functions correctly. """ management.call_command('cleanupregistration') self.assertEqual(RegistrationProfile.all().count(), 1) def test_signals(self): """ Test that the ``user_registered`` and ``user_activated`` signals are sent, and that they send the ``User`` as an argument. """ def receiver(sender, **kwargs): self.assert_('user' in kwargs) self.assertEqual(kwargs['user'].username, u'signal_test') received_signals.append(kwargs.get('signal')) received_signals = [] expected_signals = [signals.user_registered, signals.user_activated] for signal in expected_signals: signal.connect(receiver) RegistrationProfile.objects.create_inactive_user(username='signal_test', password='foo', email='nobody@example.com', send_email=False) RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', db.Key.from_path(User.kind(), 'key_signal_test')).get().activation_key) self.assertEqual(received_signals, expected_signals) class RegistrationFormTests(RegistrationTestCase): """ Tests for the forms and custom validation logic included in django-registration. """ def test_registration_form(self): """ Test that ``RegistrationForm`` enforces username constraints and matching passwords. """ invalid_data_dicts = [ # Non-alphanumeric username. { 'data': { 'username': 'foo/bar', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }, 'error': ('username', [u"Enter a valid value."]) }, # Already-existing username. { 'data': { 'username': 'alice', 'email': 'alice@example.com', 'password1': 'secret', 'password2': 'secret' }, 'error': ('username', [u"This username is already taken. Please choose another."]) }, # Mismatched passwords. { 'data': { 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'bar' }, 'error': ('__all__', [u"You must type the same password each time"]) }, ] for invalid_dict in invalid_data_dicts: form = forms.RegistrationForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) form = forms.RegistrationForm(data={ 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.failUnless(form.is_valid()) def test_registration_form_tos(self): """ Test that ``RegistrationFormTermsOfService`` requires agreement to the terms of service. """ form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.failIf(form.is_valid()) self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"]) form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo', 'tos': 'on' }) self.failUnless(form.is_valid()) def test_registration_form_unique_email(self): """ Test that ``RegistrationFormUniqueEmail`` validates uniqueness of email addresses. """ form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo', 'email': 'alice@example.com', 'password1': 'foo', 'password2': 'foo' }) self.failIf(form.is_valid()) self.assertEqual(form.errors['email'], [u"This email address is already in use. Please supply a different email address."]) form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.failUnless(form.is_valid()) def test_registration_form_no_free_email(self): """ Test that ``RegistrationFormNoFreeEmail`` disallows registration with free email addresses. """ base_data = { 'username': 'foo', 'password1': 'foo', 'password2': 'foo' } for domain in ('aim.com', 'aol.com', 'email.com', 'gmail.com', 'googlemail.com', 'hotmail.com', 'hushmail.com', 'msn.com', 'mail.ru', 'mailinator.com', 'live.com'): invalid_data = base_data.copy() invalid_data['email'] = u"foo@%s" % domain form = forms.RegistrationFormNoFreeEmail(data=invalid_data) self.failIf(form.is_valid()) self.assertEqual(form.errors['email'], [u"Registration using free email addresses is prohibited. Please supply a different email address."]) base_data['email'] = 'foo@example.com' form = forms.RegistrationFormNoFreeEmail(data=base_data) self.failUnless(form.is_valid()) class RegistrationViewTests(RegistrationTestCase): """ Tests for the views included in django-registration. """ def test_registration_view(self): """ Test that the registration view rejects invalid submissions, and creates a new user and redirects after a valid submission. """ # Invalid data fails. alice = User.all().filter('username =', 'alice').get() alice.is_active = True alice.put() response = self.client.post(reverse('registration_register'), data={ 'username': 'alice', # Will fail on username uniqueness. 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.assertEqual(response.status_code, 200) self.failUnless(response.context[0]['form']) self.failUnless(response.context[0]['form'].errors) response = self.client.post(reverse('registration_register'), data={ 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_complete')) self.assertEqual(RegistrationProfile.all().count(), 3) def test_activation_view(self): """ Test that the activation view activates the user from a valid key and fails if the key is invalid or has expired. """ # Valid user puts the user account into the context. response = self.client.get(reverse('registration_activate', kwargs={ 'activation_key': RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key })) self.assertEqual(response.status_code, 200) self.assertEqual(response.context[0]['account'].key(), self.sample_user.key()) # Expired user sets the account to False. response = self.client.get(reverse('registration_activate', kwargs={ 'activation_key': RegistrationProfile.all().filter('user =', self.expired_user).get().activation_key })) self.failIf(response.context[0]['account']) # Invalid key gets to the view, but sets account to False. response = self.client.get(reverse('registration_activate', kwargs={ 'activation_key': 'foo' })) self.failIf(response.context[0]['account']) # Nonexistent key sets the account to False. response = self.client.get(reverse('registration_activate', kwargs={ 'activation_key': sha.new('foo').hexdigest() })) self.failIf(response.context[0]['account'])
100uhaco
trunk/GAE/registration/tests.py
Python
asf20
15,474
""" URLConf for Django user registration and authentication. If the default behavior of the registration views is acceptable to you, simply use a line like this in your root URLConf to set up the default URLs for registration:: (r'^accounts/', include('registration.urls')), This will also automatically set up the views in ``django.contrib.auth`` at sensible default locations. But if you'd like to customize the behavior (e.g., by passing extra arguments to the various views) or split up the URLs, feel free to set up your own URL patterns for these views instead. If you do, it's a good idea to use the names ``registration_activate``, ``registration_complete`` and ``registration_register`` for the various steps of the user-signup process. """ from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from django.contrib.auth import views as auth_views from registration.views import * urlpatterns = patterns('', # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to the view; # that way it can return a sensible "invalid key" message instead of a # confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', activate, name='registration_activate'), url(r'^login/$', auth_views.login, {'template_name': 'registration/login.html'}, name='auth_login'), url(r'^logout/$', auth_views.logout, name='auth_logout'), url(r'^password/change/$', auth_views.password_change, name='auth_password_change'), url(r'^password/change/done/$', auth_views.password_change_done, name='auth_password_change_done'), url(r'^password/reset/$', auth_views.password_reset, name='auth_password_reset'), url(r'^password/reset/confirm/(?P<uidb36>.+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='auth_password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='auth_password_reset_complete'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='auth_password_reset_done'), url(r'^register/$', register, name='registration_register'), url(r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}, name='registration_complete'), url(r'^config/$', config, name='config'), url(r'^config/complete/$', direct_to_template, {'template': 'registration/config_complete.html'}, name='config_complete'), )
100uhaco
trunk/GAE/registration/urls.py
Python
asf20
3,620
{% extends "base.html" %} {% block title %}Reset password{% endblock %} {% block content %} <h1>Reset password</h1> <form action="{{ request.path }}" method="post"> <table>{{ form }}</table> <input type="submit" value="Reset" /> </form> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/password_reset_form.html
HTML
asf20
265
{% extends "base.html" %} {% block title %}Password reset complete{% endblock %} {% block content %} <h1>Password reset complete</h1> <p>You've successfully reset your password!</p> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/password_reset_complete.html
HTML
asf20
206
{% extends "base.html" %} {% block title %}Config{% endblock %} {% block content %} <h1>Config</h1> <p>configuration complete</p> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/config_complete.html
HTML
asf20
156
Hi! In order to reset your password please visit the following link: {{ protocol }}://{{ domain }}{% url auth_password_reset_confirm uidb36=uid,token=token %} Thanks, Your {{ site_name }} team
100uhaco
trunk/GAE/registration/templates/password_reset_email.html
HTML
asf20
195
{% extends "base.html" %} {% block title %}{% if account %}Activation successful{% else %}Activation failed :({% endif %}{% endblock %} {% block content %} {% if account %} <h1>Activation successful</h1> <p>Congratulations, {{ account.username }}. Your account has been created successfully.</p> {% else %} <h1>Activation failed :(</h1> <p>Sorry, there were problems with the activation. Please make sure that the activation link was opened correctly in your Browser. Please be also aware that activation links expire automatically.</p> {% endif %} {% endblock content %}
100uhaco
trunk/GAE/registration/templates/activate.html
HTML
asf20
581
{% extends "base.html" %} {% block title %}Reset password{% endblock %} {% block content %} <h1>Reset password</h1> <p>You've received an email with instructions for resetting your password. Please check your inbox.</p> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/password_reset_done.html
HTML
asf20
244
{% extends "base.html" %} {% block title %}Activation required{% endblock %} {% block content %} <h1>Activation required</h1> <p>In order to activate your account please check your email and click on the activation link.</p> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/registration_complete.html
HTML
asf20
251
{% extends "base.html" %} {% block title %}Register{% endblock %} {% block content %} <h1>Register</h1> <form action="{{ request.path }}" method="post"> <table>{{ form }}</table> <input type="submit" value="Register" /> </form> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/registration_form.html
HTML
asf20
256
{% extends "base.html" %} {% block title %}Login{% endblock %} {% block content %} <h1>Login</h1> <form action="{{ request.get_full_path }}" method="post"> <table>{{ form }}</table> <input type="submit" value="Login" /> </form> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/login.html
HTML
asf20
256
{% extends "base.html" %} {% block title %}Password Change{% endblock %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="."> <table> <tr> <td>{{ form.old_password.label_tag }}</td> <td>{{ form.old_password }}</td> </tr> <tr> <td>{{ form.new_password1.label_tag }}</td> <td>{{ form.new_password1 }}</td> </tr> <tr> <td>{{ form.new_password2.label_tag }}</td> <td>{{ form.new_password2 }}</td> </tr> </table> <input type="submit" value="Change" /> <input type="button" value="Cancel" onclick="javascript:window.location='/';"/> <input type="hidden" name="next" value="/" /> </form> {% endblock %}
100uhaco
trunk/GAE/registration/templates/password_change_form.html
HTML
asf20
728
{% extends "base.html" %} {% block title %}Logged out{% endblock %} {% block content %} <h1>Logged out</h1> <p>You've successfully logged out.</p> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/logged_out.html
HTML
asf20
171
{% extends "base.html" %} {% block title %}Config{% endblock %} {% block content %} <h1>Config</h1> <form action="." method="POST"> <table>{{ form }}</table> <input type="submit" value="Submit"> </form> <br><br> <strong>Caution!</strong><br> If you use Arduino Device without RTC, you should edit program and reboot Arduino Device.<br><br> <table> <tr> <div class = passwd> <td><strong>Password</strong></td> <td> <a href="{% url django.contrib.auth.views.password_change %}">Change Password</a></td> </div> </tr> </table> <br><br> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/config.html
HTML
asf20
572
{% extends "base.html" %} {% block title %}Confirm password reset{% endblock %} {% block content %} <h1>Confirm password reset</h1> <form action="{{ request.path }}" method="post"> <table>{{ form }}</table> <input type="submit" value="Reset" /> </form> {% endblock content %}
100uhaco
trunk/GAE/registration/templates/password_reset_confirm.html
HTML
asf20
281
""" A management command which deletes expired accounts (e.g., accounts which signed up but never activated) from the database. Calls ``RegistrationProfile.objects.delete_expired_users()``, which contains the actual logic for determining which accounts are deleted. """ from django.core.management.base import NoArgsCommand from registration.models import RegistrationProfile class Command(NoArgsCommand): help = "Delete expired user registrations from the database" def handle_noargs(self, **options): RegistrationProfile.objects.delete_expired_users()
100uhaco
trunk/GAE/registration/management/commands/cleanupregistration.py
Python
asf20
577
""" Views which allow users to create and activate accounts. """ from django.contrib.auth.decorators import login_required from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic.simple import direct_to_template from registration.forms import RegistrationForm from haco.models import * from haco.forms import * from registration.models import RegistrationProfile from django.http import * def activate(request, activation_key, template_name='registration/activate.html', extra_context=None): """ Activate a ``User``'s account from an activation key, if their key is valid and hasn't expired. By default, use the template ``registration/activate.html``; to change this, pass the name of a template as the keyword argument ``template_name``. **Required arguments** ``activation_key`` The activation key to validate and use for activating the ``User``. **Optional arguments** ``extra_context`` A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. ``template_name`` A custom template to use. **Context:** ``account`` The ``User`` object corresponding to the account, if the activation was successful. ``False`` if the activation was not successful. ``expiration_days`` The number of days for which activation keys stay valid after registration. Any extra variables supplied in the ``extra_context`` argument (see above). **Template:** registration/activate.html or ``template_name`` keyword argument. """ activation_key = activation_key.lower() # Normalize before trying anything with it. account = RegistrationProfile.objects.activate_user(activation_key) if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, { 'account': account, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS }, context_instance=context) def register(request, success_url=None, form_class=RegistrationForm, template_name='registration/registration_form.html', extra_context=None): """ Allow a new user to register an account. Following successful registration, issue a redirect; by default, this will be whatever URL corresponds to the named URL pattern ``registration_complete``, which will be ``/accounts/register/complete/`` if using the included URLConf. To change this, point that named pattern at another URL, or pass your preferred URL as the keyword argument ``success_url``. By default, ``registration.forms.RegistrationForm`` will be used as the registration form; to change this, pass a different form class as the ``form_class`` keyword argument. The form class you specify must have a method ``save`` which will create and return the new ``User``. By default, use the template ``registration/registration_form.html``; to change this, pass the name of a template as the keyword argument ``template_name``. **Required arguments** None. **Optional arguments** ``form_class`` The form class to use for registration. ``extra_context`` A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. ``success_url`` The URL to redirect to on successful registration. ``template_name`` A custom template to use. **Context:** ``form`` The registration form. Any extra variables supplied in the ``extra_context`` argument (see above). **Template:** registration/registration_form.html or ``template_name`` keyword argument. """ if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) domain_override = request.get_host() if form.is_valid(): new_user = form.save(domain_override) # success_url needs to be dynamically generated here; setting a # a default value using reverse() will cause circular-import # problems with the default URLConf for this application, which # imports this file. return HttpResponseRedirect(success_url or reverse('registration_complete')) else: form = form_class() if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, { 'form': form }, context_instance=context) @login_required def config( request, success_url=None, form_class=UserConfigForm, template_name='config.html', extra_context=None): u_name = request.user.username u_query =db.GqlQuery("SELECT * FROM auth_user Where username = :1",u_name ) for data in u_query: key =data.key() if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) if form.is_valid(): form.save(key) return HttpResponseRedirect(success_url or reverse('config_complete')) else: form = form_class() if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, { 'form': form }, context_instance=context)
100uhaco
trunk/GAE/registration/views.py
Python
asf20
6,397
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
100uhaco
trunk/GAE/registration/admin.py
Python
asf20
313
from django.dispatch import Signal # A new user has registered. user_registered = Signal(providing_args=["user"]) # A user has activated his or her account. user_activated = Signal(providing_args=["user"])
100uhaco
trunk/GAE/registration/signals.py
Python
asf20
209
{% extends 'base.html' %} {% block title %}Server error{% endblock %} {% block content %} There was an error while handling your request. {% endblock %}
100uhaco
trunk/GAE/templates/500.html
HTML
asf20
154
{% extends "admin/base.html" %} {% load i18n %} {% block title %}{{ title }} | {% trans 'Django site admin' %}{% endblock %} {% block userlinks %} <a href="/">Back to sample project</a> / {% url django-admindocs-docroot as docsroot %}{% if docsroot %}<a href="{{ docsroot }}">{% trans 'Documentation' %}</a> / {% endif %} <a href="{{ root_path }}password_change/">{% trans 'Change password' %}</a> / <a href="{% url django.contrib.auth.views.logout %}">{% trans 'Log out' %}</a> {% endblock %} {% block branding %} <h1 id="site-name">{% trans 'Django administration' %}</h1> {% endblock %} {% block nav-global %}{% endblock %}
100uhaco
trunk/GAE/templates/admin/base_site.html
HTML
asf20
631
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}" xml:lang="{% firstof LANGUAGE_CODE 'en' %}" lang="{% firstof LANGUAGE_CODE 'en' %}"> <head> <title>{% block title %}{% endblock %} - site name</title> {% block css %} <link rel="stylesheet" type="text/css" media="screen, projection" href="{{ MEDIA_URL }}combined-{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}.css" /> <link rel="stylesheet" type="text/css" media="print" href="{{ MEDIA_URL }}combined-print-{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}.css" /> <!--[if IE]> <link rel="stylesheet" type="text/css" media="screen, projection" href="{{ MEDIA_URL }}ie.css"> <![endif]--> {% endblock %} {% block js %} <script type="text/javascript" src="{{ MEDIA_URL }}combined-{{ LANGUAGE_CODE }}.js"></script> {% endblock %} {% block extra-head %}{% endblock %} </head> <body> {% block header %} <div id="header"> <div class="menu"> <a href="/"><img src="{{ MEDIA_URL }}global/haco_logo.png" alt="" /></a> {% if user.is_authenticated %} Welcome, {{ user.username }}! <a href="{% url django.contrib.auth.views.logout %}">Logout</a> {% else %} <a href="{% url django.contrib.auth.views.login %}">Login</a> {% endif %} </div> </div> {% endblock %} <div id="content" class="column container"> {% block content-header %} {% if error %}<div class="error">{{ error }}</div>{% endif %} {% if info %}<div class="info">{{ info }}</div>{% endif %} {% if messages %} {% for message in messages %} <div class="info">{{ message }}</div> {% endfor %} {% endif %} {% endblock %} {% block content %}{% endblock %} </div> <div id="footer"> <a href="http://code.google.com/p/app-engine-patch/"><img src="{{ MEDIA_URL }}global/powered-by-app-engine-patch.png" alt="powered by app-engine-patch" /></a> </div> </body> </html>
100uhaco
trunk/GAE/templates/haco_base.html
HTML
asf20
2,242
{% block doctype %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> {% endblock %} <html xmlns="http://www.w3.org/1999/xhtml" dir="{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}" xml:lang="{% firstof LANGUAGE_CODE 'en' %}" lang="{% firstof LANGUAGE_CODE 'en' %}"> <head> <meta content="width=device-width; maximum-scale=0.6667; user-scalable=yes" id="viewport" name="viewport" /> <title>{% block title %}{% endblock %} - site name</title> {% block css %} <link rel="stylesheet" type="text/css" media="screen, projection" href="{{ MEDIA_URL }}combined-{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}.css" /> <link rel="stylesheet" type="text/css" media="print" href="{{ MEDIA_URL }}combined-print-{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}.css" /> <link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="{{ MEDIA_URL }}iPhone.css"> <!--[if IE]> <link rel="stylesheet" type="text/css" media="screen, projection" href="{{ MEDIA_URL }}ie.css"> <![endif]--> {% endblock %} {% block js %} <script type="text/javascript" src="{{ MEDIA_URL }}combined-{{ LANGUAGE_CODE }}.js"></script> {% endblock %} {% block extra-head %}{% endblock %} </head> {% block body %} <body> {% endblock %} {% block header %} <div id="header"> <div class="menu"> <img class = "top" src="{{ MEDIA_URL }}global/haco_logo.png" alt="" /> {% if user.is_authenticated %} Welcome, {{ user.username }}! <a href="{% url config %}">Config</a> <a href="{% url django.contrib.auth.views.logout %}">Logout</a> {% else %} <a href="{% url django.contrib.auth.views.login %}">Login</a> <a href="{% url registration.views.register %}">New Account</a> {% endif %} </div> </div> {% endblock %} <div id="content" class="column container"> {% block content-header %} {% if error %}<div class="error">{{ error }}</div>{% endif %} {% if info %}<div class="info">{{ info }}</div>{% endif %} {% if messages %} {% for message in messages %} <div class="info">{{ message }}</div> {% endfor %} {% endif %} {% endblock %} {% block content %}{% endblock %} </div> <div id="footer"> <a href="http://code.google.com/p/app-engine-patch/"><img src="{{ MEDIA_URL }}global/powered-by-app-engine-patch.png" alt="powered by app-engine-patch" /></a> </div> </body> </html>
100uhaco
trunk/GAE/templates/base.html
HTML
asf20
2,658
{% extends 'base.html' %} {% block title %}Page not found{% endblock %} {% block content %} The page you requested could not be found. {% endblock %}
100uhaco
trunk/GAE/templates/404.html
HTML
asf20
151
{% extends 'base.html' %} {% block title %}{{ flatpage.title }}{% endblock %} {% block content %} {{ flatpage.content|safe }} {% endblock %}
100uhaco
trunk/GAE/templates/flatpages/default.html
HTML
asf20
142
{% extends 'base.html' %} {% block title %}Welcome!{% endblock %} {% block content %} <h1>Welcome to the app-engine-patch sample project</h1> <p>This site is a demonstration of <a href="http://code.google.com/p/app-engine-patch/">app-engine-patch</a> which is an <a href="http://code.google.com/appengine/">App Engine</a> port of the <a href="http://www.djangoproject.com/">Django</a> web framework.</p> <h2>Examples</h2> <p> You can visit Django's <a href="/admin/">admin interface</a>. If needed, you can <a href="{% url myapp.views.create_admin_user %}">generate an admin user</a> with the username and password "admin". </p> <p> Let's have a look at our <a href="{% url myapp.views.list_people %}">generic views sample</a> (a simple person list with file uploads). </p> <p> The CSS styling is done via <a href="http://www.blueprintcss.org/">Blueprint CSS</a>. We use a modified version which is adapted to the app-engine-patch <a href="http://code.google.com/p/app-engine-patch/wiki/MediaGenerator">media generator</a>. </p> <p> This sample project includes a port of <a href="http://www.bitbucket.org/ubernostrum/django-registration/wiki/Home">django-registration</a>. We maintain a list of other <a href="http://code.google.com/p/app-engine-patch/wiki/OpenSourceProjects">open-source projects</a> to get you started faster with App Engine development. </p> <p> Finally, we've integrated <a href="http://jquery.com/">jQuery</a> into the sample project: </p> <h3>jQuery example</h3> <p> <span id='clickme'>Click me!</span> </p> {% endblock %}
100uhaco
trunk/GAE/templates/main.html
HTML
asf20
1,554
#include "Python.h" #include "structmember.h" #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t PyInt_FromLong #define PyInt_AsSsize_t PyInt_AsLong #endif #ifndef Py_IS_FINITE #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #ifdef __GNUC__ #define UNUSED __attribute__((__unused__)) #else #define UNUSED #endif #define DEFAULT_ENCODING "utf-8" #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType) #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType) #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType) #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType) static PyTypeObject PyScannerType; static PyTypeObject PyEncoderType; typedef struct _PyScannerObject { PyObject_HEAD PyObject *encoding; PyObject *strict; PyObject *object_hook; PyObject *parse_float; PyObject *parse_int; PyObject *parse_constant; } PyScannerObject; static PyMemberDef scanner_members[] = { {"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"}, {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"}, {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"}, {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"}, {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"}, {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"}, {NULL} }; typedef struct _PyEncoderObject { PyObject_HEAD PyObject *markers; PyObject *defaultfn; PyObject *encoder; PyObject *indent; PyObject *key_separator; PyObject *item_separator; PyObject *sort_keys; PyObject *skipkeys; int fast_encode; int allow_nan; } PyEncoderObject; static PyMemberDef encoder_members[] = { {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"}, {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"}, {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"}, {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"}, {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"}, {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"}, {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"}, {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"}, {NULL} }; static Py_ssize_t ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars); static PyObject * ascii_escape_unicode(PyObject *pystr); static PyObject * ascii_escape_str(PyObject *pystr); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr); void init_speedups(void); static PyObject * scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx); static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds); static void scanner_dealloc(PyObject *self); static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds); static void encoder_dealloc(PyObject *self); static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level); static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level); static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level); static PyObject * _encoded_const(PyObject *const); static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end); static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj); static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr); static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr); static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj); #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"') #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r')) #define MIN_EXPANSION 6 #ifdef Py_UNICODE_WIDE #define MAX_EXPANSION (2 * MIN_EXPANSION) #else #define MAX_EXPANSION MIN_EXPANSION #endif static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr) { /* PyObject to Py_ssize_t converter */ *size_ptr = PyInt_AsSsize_t(o); if (*size_ptr == -1 && PyErr_Occurred()); return 1; return 0; } static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr) { /* Py_ssize_t to PyObject converter */ return PyInt_FromSsize_t(*size_ptr); } static Py_ssize_t ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars) { /* Escape unicode code point c to ASCII escape sequences in char *output. output must have at least 12 bytes unused to accommodate an escaped surrogate pair "\uXXXX\uXXXX" */ output[chars++] = '\\'; switch (c) { case '\\': output[chars++] = (char)c; break; case '"': output[chars++] = (char)c; break; case '\b': output[chars++] = 'b'; break; case '\f': output[chars++] = 'f'; break; case '\n': output[chars++] = 'n'; break; case '\r': output[chars++] = 'r'; break; case '\t': output[chars++] = 't'; break; default: #ifdef Py_UNICODE_WIDE if (c >= 0x10000) { /* UTF-16 surrogate pair */ Py_UNICODE v = c - 0x10000; c = 0xd800 | ((v >> 10) & 0x3ff); output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; c = 0xdc00 | (v & 0x3ff); output[chars++] = '\\'; } #endif output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; } return chars; } static PyObject * ascii_escape_unicode(PyObject *pystr) { /* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t max_output_size; Py_ssize_t chars; PyObject *rval; char *output; Py_UNICODE *input_unicode; input_chars = PyUnicode_GET_SIZE(pystr); input_unicode = PyUnicode_AS_UNICODE(pystr); /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; max_output_size = 2 + (input_chars * MAX_EXPANSION); rval = PyString_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyString_AS_STRING(rval); chars = 0; output[chars++] = '"'; for (i = 0; i < input_chars; i++) { Py_UNICODE c = input_unicode[i]; if (S_CHAR(c)) { output[chars++] = (char)c; } else { chars = ascii_escape_char(c, output, chars); } if (output_size - chars < (1 + MAX_EXPANSION)) { /* There's more than four, so let's resize by a lot */ Py_ssize_t new_output_size = output_size * 2; /* This is an upper bound */ if (new_output_size > max_output_size) { new_output_size = max_output_size; } /* Make sure that the output size changed before resizing */ if (new_output_size != output_size) { output_size = new_output_size; if (_PyString_Resize(&rval, output_size) == -1) { return NULL; } output = PyString_AS_STRING(rval); } } } output[chars++] = '"'; if (_PyString_Resize(&rval, chars) == -1) { return NULL; } return rval; } static PyObject * ascii_escape_str(PyObject *pystr) { /* Take a PyString pystr and return a new ASCII-only escaped PyString */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t chars; PyObject *rval; char *output; char *input_str; input_chars = PyString_GET_SIZE(pystr); input_str = PyString_AS_STRING(pystr); /* Fast path for a string that's already ASCII */ for (i = 0; i < input_chars; i++) { Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i]; if (!S_CHAR(c)) { /* If we have to escape something, scan the string for unicode */ Py_ssize_t j; for (j = i; j < input_chars; j++) { c = (Py_UNICODE)(unsigned char)input_str[j]; if (c > 0x7f) { /* We hit a non-ASCII character, bail to unicode mode */ PyObject *uni; uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict"); if (uni == NULL) { return NULL; } rval = ascii_escape_unicode(uni); Py_DECREF(uni); return rval; } } break; } } if (i == input_chars) { /* Input is already ASCII */ output_size = 2 + input_chars; } else { /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; } rval = PyString_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyString_AS_STRING(rval); output[0] = '"'; /* We know that everything up to i is ASCII already */ chars = i + 1; memcpy(&output[1], input_str, i); for (; i < input_chars; i++) { Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i]; if (S_CHAR(c)) { output[chars++] = (char)c; } else { chars = ascii_escape_char(c, output, chars); } /* An ASCII char can't possibly expand to a surrogate! */ if (output_size - chars < (1 + MIN_EXPANSION)) { /* There's more than four, so let's resize by a lot */ output_size *= 2; if (output_size > 2 + (input_chars * MIN_EXPANSION)) { output_size = 2 + (input_chars * MIN_EXPANSION); } if (_PyString_Resize(&rval, output_size) == -1) { return NULL; } output = PyString_AS_STRING(rval); } } output[chars++] = '"'; if (_PyString_Resize(&rval, chars) == -1) { return NULL; } return rval; } static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end) { /* Use the Python function simplejson.decoder.errmsg to raise a nice looking ValueError exception */ static PyObject *errmsg_fn = NULL; PyObject *pymsg; if (errmsg_fn == NULL) { PyObject *decoder = PyImport_ImportModule("simplejson.decoder"); if (decoder == NULL) return; errmsg_fn = PyObject_GetAttrString(decoder, "errmsg"); Py_DECREF(decoder); if (errmsg_fn == NULL) return; } pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end); if (pymsg) { PyErr_SetObject(PyExc_ValueError, pymsg); Py_DECREF(pymsg); } } static PyObject * join_list_unicode(PyObject *lst) { /* return u''.join(lst) */ static PyObject *joinfn = NULL; if (joinfn == NULL) { PyObject *ustr = PyUnicode_FromUnicode(NULL, 0); if (ustr == NULL) return NULL; joinfn = PyObject_GetAttrString(ustr, "join"); Py_DECREF(ustr); if (joinfn == NULL) return NULL; } return PyObject_CallFunctionObjArgs(joinfn, lst, NULL); } static PyObject * join_list_string(PyObject *lst) { /* return ''.join(lst) */ static PyObject *joinfn = NULL; if (joinfn == NULL) { PyObject *ustr = PyString_FromStringAndSize(NULL, 0); if (ustr == NULL) return NULL; joinfn = PyObject_GetAttrString(ustr, "join"); Py_DECREF(ustr); if (joinfn == NULL) return NULL; } return PyObject_CallFunctionObjArgs(joinfn, lst, NULL); } static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) { /* return (rval, idx) tuple, stealing reference to rval */ PyObject *tpl; PyObject *pyidx; /* steal a reference to rval, returns (rval, idx) */ if (rval == NULL) { return NULL; } pyidx = PyInt_FromSsize_t(idx); if (pyidx == NULL) { Py_DECREF(rval); return NULL; } tpl = PyTuple_New(2); if (tpl == NULL) { Py_DECREF(pyidx); Py_DECREF(rval); return NULL; } PyTuple_SET_ITEM(tpl, 0, rval); PyTuple_SET_ITEM(tpl, 1, pyidx); return tpl; } static PyObject * scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyString pystr. end is the index of the first character after the quote. encoding is the encoding of pystr (must be an ASCII superset) if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyString (if ASCII-only) or PyUnicode */ PyObject *rval; Py_ssize_t len = PyString_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next = begin; int has_unicode = 0; char *buf = PyString_AS_STRING(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { goto bail; } if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; PyObject *chunk = NULL; for (next = end; next < len; next++) { c = (unsigned char)buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } else if (c > 0x7f) { has_unicode = 1; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end); if (strchunk == NULL) { goto bail; } if (has_unicode) { chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL); Py_DECREF(strchunk); if (chunk == NULL) { goto bail; } } else { chunk = strchunk; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { c2 <<= 4; Py_UNICODE digit = buf[next]; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } if (c > 0x7f) { has_unicode = 1; } if (has_unicode) { chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } } else { char c_char = Py_CHARMASK(c); chunk = PyString_FromStringAndSize(&c_char, 1); if (chunk == NULL) { goto bail; } } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } rval = join_list_string(chunks); if (rval == NULL) { goto bail; } Py_CLEAR(chunks); *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); return NULL; } static PyObject * scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyUnicode pystr. end is the index of the first character after the quote. encoding is the encoding of pystr (must be an ASCII superset) if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyUnicode */ PyObject *rval; Py_ssize_t len = PyUnicode_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next = begin; const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { goto bail; } if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; PyObject *chunk = NULL; for (next = end; next < len; next++) { c = buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { chunk = PyUnicode_FromUnicode(&buf[end], next - end); if (chunk == NULL) { goto bail; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { c2 <<= 4; Py_UNICODE digit = buf[next]; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } if (PyList_Append(chunks, chunk)) { Py_DECREF(chunk); goto bail; } Py_DECREF(chunk); } rval = join_list_unicode(chunks); if (rval == NULL) { goto bail; } Py_DECREF(chunks); *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); return NULL; } PyDoc_STRVAR(pydoc_scanstring, "scanstring(basestring, end, encoding, strict=True) -> (str, end)\n" "\n" "Scan the string s for a JSON string. End is the index of the\n" "character in s after the quote that started the JSON string.\n" "Unescapes all valid JSON string escape sequences and raises ValueError\n" "on attempt to decode an invalid string. If strict is False then literal\n" "control characters are allowed in the string.\n" "\n" "Returns a tuple of the decoded string and the index of the character in s\n" "after the end quote." ); static PyObject * py_scanstring(PyObject* self UNUSED, PyObject *args) { PyObject *pystr; PyObject *rval; Py_ssize_t end; Py_ssize_t next_end = -1; char *encoding = NULL; int strict = 1; if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) { return NULL; } if (encoding == NULL) { encoding = DEFAULT_ENCODING; } if (PyString_Check(pystr)) { rval = scanstring_str(pystr, end, encoding, strict, &next_end); } else if (PyUnicode_Check(pystr)) { rval = scanstring_unicode(pystr, end, strict, &next_end); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_end); } PyDoc_STRVAR(pydoc_encode_basestring_ascii, "encode_basestring_ascii(basestring) -> str\n" "\n" "Return an ASCII-only JSON representation of a Python string" ); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr) { /* Return an ASCII-only JSON representation of a Python string */ /* METH_O */ if (PyString_Check(pystr)) { return ascii_escape_str(pystr); } else if (PyUnicode_Check(pystr)) { return ascii_escape_unicode(pystr); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } } static void scanner_dealloc(PyObject *self) { /* Deallocate scanner object */ PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_CLEAR(s->encoding); Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); self->ob_type->tp_free(self); } static PyObject * _parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyString pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; PyObject *rval = PyDict_New(); PyObject *key = NULL; PyObject *val = NULL; char *encoding = PyString_AS_STRING(s->encoding); int strict = PyObject_IsTrue(s->strict); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx); if (key == NULL) goto bail; idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON data type */ val = scan_once_str(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyDict_SetItem(rval, key, val) == -1) goto bail; Py_CLEAR(key); Py_CLEAR(val); idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); if (val == NULL) goto bail; Py_DECREF(rval); rval = val; val = NULL; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyUnicode pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyDict_New(); PyObject *key = NULL; int strict = PyObject_IsTrue(s->strict); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_unicode(pystr, idx + 1, strict, &next_idx); if (key == NULL) goto bail; idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyDict_SetItem(rval, key, val) == -1) goto bail; Py_CLEAR(key); Py_CLEAR(val); idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); if (val == NULL) goto bail; Py_DECREF(rval); rval = val; val = NULL; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term and de-tuplefy the (rval, idx) */ val = scan_once_str(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON constant from PyString pystr. constant is the constant string that was found ("NaN", "Infinity", "-Infinity"). idx is the index of the first character of the constant *next_idx_ptr is a return-by-reference index to the first character after the constant. Returns the result of parse_constant */ PyObject *cstr; PyObject *rval; /* constant is "NaN", "Infinity", or "-Infinity" */ cstr = PyString_InternFromString(constant); if (cstr == NULL) return NULL; /* rval = parse_constant(constant) */ rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL); idx += PyString_GET_SIZE(cstr); Py_DECREF(cstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyString pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ char *str = PyString_AS_STRING(pystr); Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { /* save the index of the 'e' or 'E' just in case we need to backtrack */ Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } /* copy the section we determined to be a number */ numstr = PyString_FromStringAndSize(&str[start], idx - start); if (numstr == NULL) return NULL; if (is_float) { /* parse as a float using a fast path if available, otherwise call user defined method */ if (s->parse_float != (PyObject *)&PyFloat_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL); } else { rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr))); } } else { /* parse as an int using a fast path if available, otherwise call user defined method */ if (s->parse_int != (PyObject *)&PyInt_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL); } else { rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10); } } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyUnicode pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx < end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } /* copy the section we determined to be a number */ numstr = PyUnicode_FromUnicode(&str[start], idx - start); if (numstr == NULL) return NULL; if (is_float) { /* parse as a float using a fast path if available, otherwise call user defined method */ if (s->parse_float != (PyObject *)&PyFloat_Type) { rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL); } else { rval = PyFloat_FromString(numstr, NULL); } } else { /* no fast path for unicode -> int, just call */ rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL); } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyString pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ char *str = PyString_AS_STRING(pystr); Py_ssize_t length = PyString_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_str(pystr, idx + 1, PyString_AS_STRING(s->encoding), PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ return _parse_object_str(s, pystr, idx + 1, next_idx_ptr); case '[': /* array */ return _parse_array_str(s, pystr, idx + 1, next_idx_ptr); case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_str(s, pystr, idx, next_idx_ptr); } static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyUnicode pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t length = PyUnicode_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_unicode(pystr, idx + 1, PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr); case '[': /* array */ return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr); case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_unicode(s, pystr, idx, next_idx_ptr); } static PyObject * scanner_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to scan_once_{str,unicode} */ PyObject *pystr; PyObject *rval; Py_ssize_t idx; Py_ssize_t next_idx = -1; static char *kwlist[] = {"string", "idx", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx)) return NULL; if (PyString_Check(pystr)) { rval = scan_once_str(s, pystr, idx, &next_idx); } else if (PyUnicode_Check(pystr)) { rval = scan_once_unicode(s, pystr, idx, &next_idx); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_idx); } static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds) { /* Initialize Scanner object */ PyObject *ctx; static char *kwlist[] = {"context", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx)) return -1; s->encoding = NULL; s->strict = NULL; s->object_hook = NULL; s->parse_float = NULL; s->parse_int = NULL; s->parse_constant = NULL; /* PyString_AS_STRING is used on encoding */ s->encoding = PyObject_GetAttrString(ctx, "encoding"); if (s->encoding == Py_None) { Py_DECREF(Py_None); s->encoding = PyString_InternFromString(DEFAULT_ENCODING); } else if (PyUnicode_Check(s->encoding)) { PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL); Py_DECREF(s->encoding); s->encoding = tmp; } if (s->encoding == NULL || !PyString_Check(s->encoding)) goto bail; /* All of these will fail "gracefully" so we don't need to verify them */ s->strict = PyObject_GetAttrString(ctx, "strict"); if (s->strict == NULL) goto bail; s->object_hook = PyObject_GetAttrString(ctx, "object_hook"); if (s->object_hook == NULL) goto bail; s->parse_float = PyObject_GetAttrString(ctx, "parse_float"); if (s->parse_float == NULL) goto bail; s->parse_int = PyObject_GetAttrString(ctx, "parse_int"); if (s->parse_int == NULL) goto bail; s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant"); if (s->parse_constant == NULL) goto bail; return 0; bail: Py_CLEAR(s->encoding); Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); return -1; } PyDoc_STRVAR(scanner_doc, "JSON scanner object"); static PyTypeObject PyScannerType = { PyObject_HEAD_INIT(0) 0, /* tp_internal */ "Scanner", /* tp_name */ sizeof(PyScannerObject), /* tp_basicsize */ 0, /* tp_itemsize */ scanner_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ scanner_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ scanner_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ scanner_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ scanner_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ 0,/* PyType_GenericNew, */ /* tp_new */ 0,/* _PyObject_Del, */ /* tp_free */ }; static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds) { /* initialize Encoder object */ static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL}; PyEncoderObject *s; PyObject *allow_nan; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; s->markers = NULL; s->defaultfn = NULL; s->encoder = NULL; s->indent = NULL; s->key_separator = NULL; s->item_separator = NULL; s->sort_keys = NULL; s->skipkeys = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist, &s->markers, &s->defaultfn, &s->encoder, &s->indent, &s->key_separator, &s->item_separator, &s->sort_keys, &s->skipkeys, &allow_nan)) return -1; Py_INCREF(s->markers); Py_INCREF(s->defaultfn); Py_INCREF(s->encoder); Py_INCREF(s->indent); Py_INCREF(s->key_separator); Py_INCREF(s->item_separator); Py_INCREF(s->sort_keys); Py_INCREF(s->skipkeys); s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii); s->allow_nan = PyObject_IsTrue(allow_nan); return 0; } static PyObject * encoder_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to encode_listencode_obj */ static char *kwlist[] = {"obj", "_current_indent_level", NULL}; PyObject *obj; PyObject *rval; Py_ssize_t indent_level; PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist, &obj, _convertPyInt_AsSsize_t, &indent_level)) return NULL; rval = PyList_New(0); if (rval == NULL) return NULL; if (encoder_listencode_obj(s, rval, obj, indent_level)) { Py_DECREF(rval); return NULL; } return rval; } static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ if (obj == Py_None) { static PyObject *s_null = NULL; if (s_null == NULL) { s_null = PyString_InternFromString("null"); } Py_INCREF(s_null); return s_null; } else if (obj == Py_True) { static PyObject *s_true = NULL; if (s_true == NULL) { s_true = PyString_InternFromString("true"); } Py_INCREF(s_true); return s_true; } else if (obj == Py_False) { static PyObject *s_false = NULL; if (s_false == NULL) { s_false = PyString_InternFromString("false"); } Py_INCREF(s_false); return s_false; } else { PyErr_SetString(PyExc_ValueError, "not a const"); return NULL; } } static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a PyFloat */ double i = PyFloat_AS_DOUBLE(obj); if (!Py_IS_FINITE(i)) { if (!s->allow_nan) { PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant"); return NULL; } if (i > 0) { return PyString_FromString("Infinity"); } else if (i < 0) { return PyString_FromString("-Infinity"); } else { return PyString_FromString("NaN"); } } /* Use a better float format here? */ return PyObject_Repr(obj); } static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a string */ if (s->fast_encode) return py_encode_basestring_ascii(NULL, obj); else return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL); } static int _steal_list_append(PyObject *lst, PyObject *stolen) { /* Append stolen and then decrement its reference count */ int rval = PyList_Append(lst, stolen); Py_DECREF(stolen); return rval; } static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level) { /* Encode Python object obj to a JSON term, rval is a PyList */ PyObject *newobj; int rv; if (obj == Py_None || obj == Py_True || obj == Py_False) { PyObject *cstr = _encoded_const(obj); if (cstr == NULL) return -1; return _steal_list_append(rval, cstr); } else if (PyString_Check(obj) || PyUnicode_Check(obj)) { PyObject *encoded = encoder_encode_string(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyInt_Check(obj) || PyLong_Check(obj)) { PyObject *encoded = PyObject_Str(obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyFloat_Check(obj)) { PyObject *encoded = encoder_encode_float(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyList_Check(obj) || PyTuple_Check(obj)) { return encoder_listencode_list(s, rval, obj, indent_level); } else if (PyDict_Check(obj)) { return encoder_listencode_dict(s, rval, obj, indent_level); } else { PyObject *ident = NULL; if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(obj); if (ident == NULL) return -1; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); Py_DECREF(ident); return -1; } if (PyDict_SetItem(s->markers, ident, obj)) { Py_DECREF(ident); return -1; } } newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL); if (newobj == NULL) { Py_XDECREF(ident); return -1; } rv = encoder_listencode_obj(s, rval, newobj, indent_level); Py_DECREF(newobj); if (rv) { Py_XDECREF(ident); return -1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) { Py_XDECREF(ident); return -1; } Py_XDECREF(ident); } return rv; } } static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level) { /* Encode Python dict dct a JSON term, rval is a PyList */ static PyObject *open_dict = NULL; static PyObject *close_dict = NULL; static PyObject *empty_dict = NULL; PyObject *kstr = NULL; PyObject *ident = NULL; PyObject *key, *value; Py_ssize_t pos; int skipkeys; Py_ssize_t idx; if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) { open_dict = PyString_InternFromString("{"); close_dict = PyString_InternFromString("}"); empty_dict = PyString_InternFromString("{}"); if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) return -1; } if (PyDict_Size(dct) == 0) return PyList_Append(rval, empty_dict); if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(dct); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, dct)) { goto bail; } } if (PyList_Append(rval, open_dict)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } /* TODO: C speedup not implemented for sort_keys */ pos = 0; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; while (PyDict_Next(dct, &pos, &key, &value)) { PyObject *encoded; if (PyString_Check(key) || PyUnicode_Check(key)) { Py_INCREF(key); kstr = key; } else if (PyFloat_Check(key)) { kstr = encoder_encode_float(s, key); if (kstr == NULL) goto bail; } else if (PyInt_Check(key) || PyLong_Check(key)) { kstr = PyObject_Str(key); if (kstr == NULL) goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { kstr = _encoded_const(key); if (kstr == NULL) goto bail; } else if (skipkeys) { continue; } else { /* TODO: include repr of key */ PyErr_SetString(PyExc_ValueError, "keys must be a string"); goto bail; } if (idx) { if (PyList_Append(rval, s->item_separator)) goto bail; } encoded = encoder_encode_string(s, kstr); Py_CLEAR(kstr); if (encoded == NULL) goto bail; if (PyList_Append(rval, encoded)) { Py_DECREF(encoded); goto bail; } Py_DECREF(encoded); if (PyList_Append(rval, s->key_separator)) goto bail; if (encoder_listencode_obj(s, rval, value, indent_level)) goto bail; idx += 1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level -= 1; /* yield '\n' + (' ' * (_indent * _current_indent_level)) */ } if (PyList_Append(rval, close_dict)) goto bail; return 0; bail: Py_XDECREF(kstr); Py_XDECREF(ident); return -1; } static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level) { /* Encode Python list seq to a JSON term, rval is a PyList */ static PyObject *open_array = NULL; static PyObject *close_array = NULL; static PyObject *empty_array = NULL; PyObject *ident = NULL; PyObject *s_fast = NULL; Py_ssize_t num_items; PyObject **seq_items; Py_ssize_t i; if (open_array == NULL || close_array == NULL || empty_array == NULL) { open_array = PyString_InternFromString("["); close_array = PyString_InternFromString("]"); empty_array = PyString_InternFromString("[]"); if (open_array == NULL || close_array == NULL || empty_array == NULL) return -1; } ident = NULL; s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence"); if (s_fast == NULL) return -1; num_items = PySequence_Fast_GET_SIZE(s_fast); if (num_items == 0) { Py_DECREF(s_fast); return PyList_Append(rval, empty_array); } if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(seq); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, seq)) { goto bail; } } seq_items = PySequence_Fast_ITEMS(s_fast); if (PyList_Append(rval, open_array)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } for (i = 0; i < num_items; i++) { PyObject *obj = seq_items[i]; if (i) { if (PyList_Append(rval, s->item_separator)) goto bail; } if (encoder_listencode_obj(s, rval, obj, indent_level)) goto bail; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level -= 1; /* yield '\n' + (' ' * (_indent * _current_indent_level)) */ } if (PyList_Append(rval, close_array)) goto bail; Py_DECREF(s_fast); return 0; bail: Py_XDECREF(ident); Py_DECREF(s_fast); return -1; } static void encoder_dealloc(PyObject *self) { /* Deallocate Encoder */ PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_CLEAR(s->markers); Py_CLEAR(s->defaultfn); Py_CLEAR(s->encoder); Py_CLEAR(s->indent); Py_CLEAR(s->key_separator); Py_CLEAR(s->item_separator); Py_CLEAR(s->sort_keys); Py_CLEAR(s->skipkeys); self->ob_type->tp_free(self); } PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable"); static PyTypeObject PyEncoderType = { PyObject_HEAD_INIT(0) 0, /* tp_internal */ "Encoder", /* tp_name */ sizeof(PyEncoderObject), /* tp_basicsize */ 0, /* tp_itemsize */ encoder_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ encoder_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ encoder_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ encoder_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ encoder_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ 0,/* PyType_GenericNew, */ /* tp_new */ 0,/* _PyObject_Del, */ /* tp_free */ }; static PyMethodDef speedups_methods[] = { {"encode_basestring_ascii", (PyCFunction)py_encode_basestring_ascii, METH_O, pydoc_encode_basestring_ascii}, {"scanstring", (PyCFunction)py_scanstring, METH_VARARGS, pydoc_scanstring}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(module_doc, "simplejson speedups\n"); void init_speedups(void) { PyObject *m; PyScannerType.tp_getattro = PyObject_GenericGetAttr; PyScannerType.tp_setattro = PyObject_GenericSetAttr; PyScannerType.tp_alloc = PyType_GenericAlloc; PyScannerType.tp_new = PyType_GenericNew; PyScannerType.tp_free = _PyObject_Del; if (PyType_Ready(&PyScannerType) < 0) return; PyEncoderType.tp_getattro = PyObject_GenericGetAttr; PyEncoderType.tp_setattro = PyObject_GenericSetAttr; PyEncoderType.tp_alloc = PyType_GenericAlloc; PyEncoderType.tp_new = PyType_GenericNew; PyEncoderType.tp_free = _PyObject_Del; if (PyType_Ready(&PyEncoderType) < 0) return; m = Py_InitModule3("_speedups", speedups_methods, module_doc); Py_INCREF((PyObject*)&PyScannerType); PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType); Py_INCREF((PyObject*)&PyEncoderType); PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType); }
100uhaco
trunk/GAE/simplejson/_speedups.c
C
asf20
75,169
"""Implementation of JSONDecoder """ import re import sys import struct from simplejson.scanner import make_scanner try: from simplejson._speedups import scanstring as c_scanstring except ImportError: c_scanstring = None __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _speedups lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: msg = "Invalid control character %r at" % (terminator,) raise ValueError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: # Unicode escape sequence esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise ValueError(errmsg(msg, s, end)) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise ValueError(errmsg(msg, s, end)) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise ValueError(errmsg(msg, s, end)) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = unichr(uni) end = next_end # Append the unescaped character _append(char) return u''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR): pairs = {} # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': return pairs, end + 1 elif nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 while True: key, end = scanstring(s, end, encoding, strict) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) try: nextchar = s[end] if nextchar in _ws: end += 1 nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): """``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. """ self.encoding = encoding self.object_hook = object_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.scan_once = make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end
100uhaco
trunk/GAE/simplejson/decoder.py
Python
asf20
12,032
"""JSON token scanner """ import re try: from simplejson._speedups import make_scanner as c_make_scanner except ImportError: c_make_scanner = None __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration return _scan_once make_scanner = c_make_scanner or py_make_scanner
100uhaco
trunk/GAE/simplejson/scanner.py
Python
asf20
2,227
"""Implementation of JSONEncoder """ import re try: from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii except ImportError: c_encode_basestring_ascii = None try: from simplejson._speedups import make_encoder as c_make_encoder except ImportError: c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # Assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is True, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is True, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is True, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError("%r is not JSON serializable" % (o,)) def encode(self, o): """Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) return ''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError("Out of range float values are not JSON compliant: %r" % (o,)) return text if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys: _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif isinstance(key, (int, long)): key = str(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif _skipkeys: continue else: raise TypeError("key %r is not a string" % (key,)) if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
100uhaco
trunk/GAE/simplejson/encoder.py
Python
asf20
15,836
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> import decimal >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError("%r is not JSON serializable" % (o,)) ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.0.7' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder', ] from decoder import JSONDecoder from encoder import JSONEncoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s)
100uhaco
trunk/GAE/simplejson/__init__.py
Python
asf20
12,503
r"""Using simplejson from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ import simplejson def main(): import sys if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],)) try: obj = simplejson.load(infile) except ValueError, e: raise SystemExit(e) simplejson.dump(obj, outfile, sort_keys=True, indent=4) outfile.write('\n') if __name__ == '__main__': main()
100uhaco
trunk/GAE/simplejson/tool.py
Python
asf20
908
// Define the overlay, derived from google.maps.OverlayView function Label(opt_options){ // Initialization this.setValues(opt_options); // Label specific var span = this.span_ = document.createElement('span'); span.style.cssText = 'position: relative; left: 0%; top: -50px; ' + 'white-space: nowrap; border: 1px solid black; ' + 'padding: 5px; background-color: white'; var div = this.div_ = document.createElement('div'); div.appendChild(span); div.style.cssText = 'position: absolute; display: none'; }; Label.prototype = new google.maps.OverlayView; // Implement onAdd Label.prototype.onAdd = function(){ var pane = this.getPanes().overlayLayer; pane.appendChild(this.div_); // Ensures the label is redrawn if the text or position is changed. var me = this; this.listeners_ = [google.maps.event.addListener(this, 'position_changed', function(){ me.draw(); }), google.maps.event.addListener(this, 'text_changed', function(){ me.draw(); })]; }; // Implement onRemove Label.prototype.onRemove = function(){ this.div_.parentNode.removeChild(this.div_); // Label is removed from the map, stop updating its position/text. for (var i = 0, I = this.listeners_.length; i < I; ++i) { maps.google.event.removeListener(this.listeners_[i]); } }; // Implement draw Label.prototype.draw = function(){ var projection = this.getProjection(); var position = projection.fromLatLngToDivPixel(this.get('position')); var div = this.div_; div.style.left = position.x + 'px'; div.style.top = position.y + 'px'; div.style.display = 'block'; this.span_.innerHTML = this.get('text'); };
100uhaco
trunk/GAE/_generated_media/1/haco/label.js
JavaScript
asf20
1,794
*{ margin:0; padding:0; } li{ list-style-type:none;} body{ line-height:1.8; font-size:80%; } IMG.top { width:900px } IMG.chart { width:900px } DIV.bar { text-align: right; } DIV.passwd { width: 900px; } FORM { position: relative; width: 900px; }
100uhaco
trunk/GAE/_generated_media/1/iPhone.css
CSS
asf20
289
# -*- coding: utf-8 -*- import os, sys COMMON_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) PROJECT_DIR = os.path.dirname(COMMON_DIR) ZIP_PACKAGES_DIRS = (os.path.join(PROJECT_DIR, 'zip-packages'), os.path.join(COMMON_DIR, 'zip-packages')) # Overrides for os.environ env_ext = {'DJANGO_SETTINGS_MODULE': 'settings'} def setup_env(manage_py_env=False): """Configures app engine environment for command-line apps.""" # Try to import the appengine code from the system path. try: from google.appengine.api import apiproxy_stub_map except ImportError, e: for k in [k for k in sys.modules if k.startswith('google')]: del sys.modules[k] # Not on the system path. Build a list of alternative paths where it # may be. First look within the project for a local copy, then look for # where the Mac OS SDK installs it. paths = [os.path.join(COMMON_DIR, '.google_appengine'), '/usr/local/google_appengine', '/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine'] for path in os.environ.get('PATH', '').replace(';', ':').split(':'): path = path.rstrip(os.sep) if path.endswith('google_appengine'): paths.append(path) if os.name in ('nt', 'dos'): prefix = '%(PROGRAMFILES)s' % os.environ paths.append(prefix + r'\Google\google_appengine') # Loop through all possible paths and look for the SDK dir. SDK_PATH = None for sdk_path in paths: sdk_path = os.path.realpath(sdk_path) if os.path.exists(sdk_path): SDK_PATH = sdk_path break if SDK_PATH is None: # The SDK could not be found in any known location. sys.stderr.write('The Google App Engine SDK could not be found!\n' 'Visit http://code.google.com/p/app-engine-patch/' ' for installation instructions.\n') sys.exit(1) # Add the SDK and the libraries within it to the system path. EXTRA_PATHS = [SDK_PATH] lib = os.path.join(SDK_PATH, 'lib') # Automatically add all packages in the SDK's lib folder: for dir in os.listdir(lib): path = os.path.join(lib, dir) # Package can be under 'lib/<pkg>/<pkg>/' or 'lib/<pkg>/lib/<pkg>/' detect = (os.path.join(path, dir), os.path.join(path, 'lib', dir)) for path in detect: if os.path.isdir(path): EXTRA_PATHS.append(os.path.dirname(path)) break sys.path = EXTRA_PATHS + sys.path from google.appengine.api import apiproxy_stub_map # Add this folder to sys.path sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path setup_project() from appenginepatcher.patch import patch_all patch_all() if not manage_py_env: return print >> sys.stderr, 'Running on app-engine-patch 1.0.2.2' def setup_project(): from appenginepatcher import on_production_server if on_production_server: # This fixes a pwd import bug for os.path.expanduser() global env_ext env_ext['HOME'] = PROJECT_DIR os.environ.update(env_ext) # Add the two parent folders and appenginepatcher's lib folder to sys.path. # The current folder has to be added in main.py or setup_env(). This # suggests a folder structure where you separate reusable code from project # code: # project -> common -> appenginepatch # You can put a custom Django version into the "common" folder, for example. EXTRA_PATHS = [ PROJECT_DIR, COMMON_DIR, ] this_folder = os.path.abspath(os.path.dirname(__file__)) EXTRA_PATHS.append(os.path.join(this_folder, 'appenginepatcher', 'lib')) # We support zipped packages in the common and project folders. # The files must be in the packages folder. for packages_dir in ZIP_PACKAGES_DIRS: if os.path.isdir(packages_dir): for zip_package in os.listdir(packages_dir): EXTRA_PATHS.append(os.path.join(packages_dir, zip_package)) # App Engine causes main.py to be reloaded if an exception gets raised # on the first request of a main.py instance, so don't call setup_project() # multiple times. We ensure this indirectly by checking if we've already # modified sys.path. if len(sys.path) < len(EXTRA_PATHS) or \ sys.path[:len(EXTRA_PATHS)] != EXTRA_PATHS: # Remove the standard version of Django for k in [k for k in sys.modules if k.startswith('django')]: del sys.modules[k] sys.path = EXTRA_PATHS + sys.path
100uhaco
trunk/GAE/common/appenginepatch/aecmd.py
Python
asf20
4,878
#!/usr/bin/env python if __name__ == '__main__': from common.appenginepatch.aecmd import setup_env setup_env(manage_py_env=True) # Recompile translation files from mediautils.compilemessages import updatemessages updatemessages() # Generate compressed media files for manage.py update import sys from mediautils.generatemedia import updatemedia if len(sys.argv) >= 2 and sys.argv[1] == 'update': updatemedia(True) import settings from django.core.management import execute_manager execute_manager(settings)
100uhaco
trunk/GAE/common/appenginepatch/.svn/text-base/manage.py.svn-base
Python
asf20
566
# -*- coding: utf-8 -*- import os, sys # Add current folder to sys.path, so we can import aecmd. # App Engine causes main.py to be reloaded if an exception gets raised # on the first request of a main.py instance, so don't add current_dir multiple # times. current_dir = os.path.abspath(os.path.dirname(__file__)) if current_dir not in sys.path: sys.path = [current_dir] + sys.path import aecmd aecmd.setup_project() from appenginepatcher.patch import patch_all, setup_logging patch_all() import django.core.handlers.wsgi from google.appengine.ext.webapp import util from django.conf import settings def real_main(): # Reset path and environment variables global path_backup try: sys.path = path_backup[:] except: path_backup = sys.path[:] os.environ.update(aecmd.env_ext) setup_logging() # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() # Run the WSGI CGI handler with that application. util.run_wsgi_app(application) def profile_main(): import logging, cProfile, pstats, random, StringIO only_forced_profile = getattr(settings, 'ONLY_FORCED_PROFILE', False) profile_percentage = getattr(settings, 'PROFILE_PERCENTAGE', None) if (only_forced_profile and 'profile=forced' not in os.environ.get('QUERY_STRING')) or \ (not only_forced_profile and profile_percentage and float(profile_percentage) / 100.0 <= random.random()): return real_main() prof = cProfile.Profile() prof = prof.runctx('real_main()', globals(), locals()) stream = StringIO.StringIO() stats = pstats.Stats(prof, stream=stream) sort_by = getattr(settings, 'SORT_PROFILE_RESULTS_BY', 'time') if not isinstance(sort_by, (list, tuple)): sort_by = (sort_by,) stats.sort_stats(*sort_by) restrictions = [] profile_pattern = getattr(settings, 'PROFILE_PATTERN', None) if profile_pattern: restrictions.append(profile_pattern) max_results = getattr(settings, 'MAX_PROFILE_RESULTS', 80) if max_results and max_results != 'all': restrictions.append(max_results) stats.print_stats(*restrictions) extra_output = getattr(settings, 'EXTRA_PROFILE_OUTPUT', None) or () if not isinstance(sort_by, (list, tuple)): extra_output = (extra_output,) if 'callees' in extra_output: stats.print_callees() if 'callers' in extra_output: stats.print_callers() logging.info('Profile data:\n%s', stream.getvalue()) main = getattr(settings, 'ENABLE_PROFILER', False) and profile_main or real_main if __name__ == '__main__': main()
100uhaco
trunk/GAE/common/appenginepatch/main.py
Python
asf20
2,674
# Empty file neeed to make this a Django app.
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/models.py
Python
asf20
46
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This file acts as a very minimal replacement for the 'imp' module. It contains only what Django expects to use and does not actually implement the same functionality as the real 'imp' module. """ def find_module(name, path=None): """Django needs imp.find_module, but it works fine if nothing is found.""" raise ImportError
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/imp.py
Python
asf20
932
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/conf/app_template/models.py
Python
asf20
118
# -*- coding: utf-8 -*- from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from ragendja.template import render_to_response
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/conf/app_template/views.py
Python
asf20
171
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This file acts as a very minimal replacement for the 'imp' module. It contains only what Django expects to use and does not actually implement the same functionality as the real 'imp' module. """ def find_module(name, path=None): """Django needs imp.find_module, but it works fine if nothing is found.""" raise ImportError
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/.svn/text-base/imp.py.svn-base
Python
asf20
932
# -*- coding: utf-8 -*- from django.db.models import signals from django.test import TestCase from ragendja.dbutils import cleanup_relations from ragendja.testutils import ModelTestCase from google.appengine.ext import db from google.appengine.ext.db.polymodel import PolyModel from datetime import datetime # Test class Meta class TestA(db.Model): class Meta: abstract = True verbose_name = 'aaa' class TestB(TestA): class Meta: verbose_name = 'bbb' class TestC(TestA): pass class TestModelRel(db.Model): modelrel = db.ReferenceProperty(db.Model) class PolyA(PolyModel): class Meta: verbose_name = 'polyb' class PolyB(PolyA): pass class ModelMetaTest(TestCase): def test_class_meta(self): self.assertEqual(TestA._meta.verbose_name_plural, 'aaas') self.assertTrue(TestA._meta.abstract) self.assertEqual(TestB._meta.verbose_name_plural, 'bbbs') self.assertFalse(TestB._meta.abstract) self.assertEqual(TestC._meta.verbose_name_plural, 'test cs') self.assertFalse(TestC._meta.abstract) self.assertFalse(PolyA._meta.abstract) self.assertFalse(PolyB._meta.abstract) # Test signals class SignalTest(TestCase): def test_signals(self): global received_pre_delete global received_post_save received_pre_delete = False received_post_save = False def handle_pre_delete(**kwargs): global received_pre_delete received_pre_delete = True signals.pre_delete.connect(handle_pre_delete, sender=TestC) def handle_post_save(**kwargs): global received_post_save received_post_save = True signals.post_save.connect(handle_post_save, sender=TestC) a = TestC() a.put() a.delete() self.assertTrue(received_pre_delete) self.assertTrue(received_post_save) def test_batch_signals(self): global received_pre_delete global received_post_save received_pre_delete = False received_post_save = False def handle_pre_delete(**kwargs): global received_pre_delete received_pre_delete = True signals.pre_delete.connect(handle_pre_delete, sender=TestC) def handle_post_save(**kwargs): global received_post_save received_post_save = True signals.post_save.connect(handle_post_save, sender=TestC) a = TestC() db.put([a]) db.delete([a]) self.assertTrue(received_pre_delete) self.assertTrue(received_post_save) # Test serialization class SerializeModel(db.Model): name = db.StringProperty() count = db.IntegerProperty() created = db.DateTimeProperty() class SerializerTest(ModelTestCase): model = SerializeModel def test_serializer(self, format='json'): from django.core import serializers created = datetime.now() x = SerializeModel(key_name='blue_key', name='blue', count=4) x.put() SerializeModel(name='green', count=1, created=created).put() data = serializers.serialize(format, SerializeModel.all()) db.delete(SerializeModel.all().fetch(100)) for obj in serializers.deserialize(format, data): obj.save() self.validate_state( ('key.name', 'name', 'count', 'created'), (None, 'green', 1, created), ('blue_key', 'blue', 4, None), ) def test_xml_serializer(self): self.test_serializer(format='xml') def test_python_serializer(self): self.test_serializer(format='python') def test_yaml_serializer(self): self.test_serializer(format='yaml') # Test ragendja cleanup handler class SigChild(db.Model): CLEANUP_REFERENCES = 'rel' owner = db.ReferenceProperty(TestC) rel = db.ReferenceProperty(TestC, collection_name='sigchildrel_set') class RelationsCleanupTest(TestCase): def test_cleanup(self): signals.pre_delete.connect(cleanup_relations, sender=TestC) c1 = TestC() c2 = TestC() db.put((c1, c2)) TestModelRel(modelrel=c1).put() child = SigChild(owner=c1, rel=c2) child.put() self.assertEqual(TestC.all().count(), 2) self.assertEqual(SigChild.all().count(), 1) self.assertEqual(TestModelRel.all().count(), 1) c1.delete() signals.pre_delete.disconnect(cleanup_relations, sender=TestC) self.assertEqual(SigChild.all().count(), 0) self.assertEqual(TestC.all().count(), 0) self.assertEqual(TestModelRel.all().count(), 0) from ragendja.dbutils import FakeModel, FakeModelProperty, \ FakeModelListProperty class FM(db.Model): data = FakeModelProperty(FakeModel, indexed=False) class FML(db.Model): data = FakeModelListProperty(FakeModel, indexed=False) # Test FakeModel, FakeModelProperty, FakeModelListProperty class RelationsCleanupTest(TestCase): def test_fake_model_property(self): value = {'bla': [1, 2, {'blub': 'bla'*1000}]} FM(data=FakeModel(value=value)).put() self.assertEqual(FM.all()[0].data.value, value) def test_fake_model_list_property(self): value = {'bla': [1, 2, {'blub': 'bla'*1000}]} FML(data=[FakeModel(value=value)]).put() self.assertEqual(FML.all()[0].data[0].value, value)
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/tests.py
Python
asf20
5,416
# -*- coding: utf-8 -*- # Unfortunately, we have to fix a few App Engine bugs here because otherwise # not all of our features will work. Still, we should keep the number of bug # fixes to a minimum and report everything to Google, please: # http://code.google.com/p/googleappengine/issues/list from google.appengine.ext import db from google.appengine.ext.db import polymodel import logging, os, re, sys base_path = os.path.abspath(os.path.dirname(__file__)) get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip() DEFAULT_NAMES = ('verbose_name', 'ordering', 'permissions', 'app_label', 'abstract', 'db_table', 'db_tablespace') # Add checkpoints to patching procedure, so we don't apply certain patches # multiple times. This can happen if an exeception gets raised on the first # request of an instance. In that case, main.py gets reloaded and patch_all() # gets executed yet another time. done_patch_all = False def patch_all(): global done_patch_all if done_patch_all: return patch_python() patch_app_engine() # Add signals: post_save_committed, post_delete_committed from appenginepatcher import transactions setup_logging() done_patch_all = True def patch_python(): # Remove modules that we want to override. Don't remove modules that we've # already overridden. for module in ('memcache',): if module in sys.modules and \ not sys.modules[module].__file__.startswith(base_path): del sys.modules[module] # For some reason the imp module can't be replaced via sys.path from appenginepatcher import have_appserver if have_appserver: from appenginepatcher import imp sys.modules['imp'] = imp if have_appserver: def unlink(_): raise NotImplementedError('App Engine does not support FS writes!') os.unlink = unlink def patch_app_engine(): # This allows for using Paginator on a Query object. We limit the number # of results to 301, so there won't be any timeouts (301, so you can say # "more than 300 results"). def __len__(self): return self.count() db.Query.__len__ = __len__ old_count = db.Query.count def count(self, limit=301): return old_count(self, limit) db.Query.count = count # Add "model" property to Query (needed by generic views) class ModelProperty(object): def __get__(self, query, unused): try: return query._Query__model_class except: return query._model_class db.Query.model = ModelProperty() db.GqlQuery.model = ModelProperty() # Add a few Model methods that are needed for serialization and ModelForm def _get_pk_val(self): if self.has_key(): return unicode(self.key()) else: return None db.Model._get_pk_val = _get_pk_val def __eq__(self, other): if not isinstance(other, self.__class__): return False return self._get_pk_val() == other._get_pk_val() db.Model.__eq__ = __eq__ def __ne__(self, other): return not self.__eq__(other) db.Model.__ne__ = __ne__ def pk(self): return self._get_pk_val() db.Model.id = db.Model.pk = property(pk) def serializable_value(self, field_name): """ Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly. Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method. """ from django.db.models.fields import FieldDoesNotExist try: field = self._meta.get_field(field_name) except FieldDoesNotExist: return getattr(self, field_name) return getattr(self, field.attname) db.Model.serializable_value = serializable_value # Make Property more Django-like (needed for serialization and ModelForm) db.Property.serialize = True db.Property.editable = True db.Property.help_text = '' def blank(self): return not self.required db.Property.blank = property(blank) def _get_verbose_name(self): if not getattr(self, '_verbose_name', None): self._verbose_name = self.name.replace('_', ' ') return self._verbose_name def _set_verbose_name(self, verbose_name): self._verbose_name = verbose_name db.Property.verbose_name = property(_get_verbose_name, _set_verbose_name) def attname(self): return self.name db.Property.attname = property(attname) class Rel(object): def __init__(self, property): self.field_name = 'key' self.property = property self.to = property.reference_class self.multiple = True self.parent_link = False self.related_name = getattr(property, 'collection_name', None) self.through = None class RelProperty(object): def __get__(self, property, cls): if property is None: return self if not hasattr(property, 'reference_class'): return None if not hasattr(property, '_rel_cache'): property._rel_cache = Rel(property) return property._rel_cache db.Property.rel = RelProperty() def formfield(self, **kwargs): return self.get_form_field(**kwargs) db.Property.formfield = formfield # Add repr to make debugging a little bit easier def __repr__(self): data = [] if self.has_key(): if self.key().name(): data.append('key_name='+repr(self.key().name())) else: data.append('key_id='+repr(self.key().id())) for field in self._meta.fields: try: data.append(field.name+'='+repr(getattr(self, field.name))) except: data.append(field.name+'='+repr(field.get_value_for_datastore(self))) return u'%s(%s)' % (self.__class__.__name__, ', '.join(data)) db.Model.__repr__ = __repr__ # Add default __str__ and __unicode__ methods def __str__(self): return unicode(self).encode('utf-8') db.Model.__str__ = __str__ def __unicode__(self): return unicode(repr(self)) db.Model.__unicode__ = __unicode__ # Replace save() method with one that calls put(), so a monkey-patched # put() will also work if someone uses save() def save(self): self.put() db.Model.save = save # Add _meta to Model, so porting code becomes easier (generic views, # xheaders, and serialization depend on it). from django.conf import settings from django.utils.encoding import force_unicode, smart_str from django.utils.translation import string_concat, get_language, \ activate, deactivate_all class _meta(object): many_to_many = () class pk: name = 'key' attname = 'pk' def __init__(self, model, bases): try: self.app_label = model.__module__.split('.')[-2] except IndexError: raise ValueError('Django expects models (here: %s.%s) to be defined in their own apps!' % (model.__module__, model.__name__)) self.parents = [b for b in bases if issubclass(b, db.Model)] self.object_name = model.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) self.ordering = () self.abstract = model is db.Model self.model = model self.unique_together = () self.installed = model.__module__.rsplit('.', 1)[0] in \ settings.INSTALLED_APPS self.permissions = [] meta = model.__dict__.get('Meta') if meta: meta_attrs = meta.__dict__.copy() for name in meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(meta, attr_name): setattr(self, attr_name, getattr(meta, attr_name)) # verbose_name_plural is a special case because it uses a 's' # by default. setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's'))) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError, "'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()) else: self.verbose_name_plural = self.verbose_name + 's' if not isinstance(self.permissions, list): self.permissions = list(self.permissions) if not self.abstract: self.permissions.extend([ ('add_%s' % self.object_name.lower(), string_concat('Can add ', self.verbose_name)), ('change_%s' % self.object_name.lower(), string_concat('Can change ', self.verbose_name)), ('delete_%s' % self.object_name.lower(), string_concat('Can delete ', self.verbose_name)), ]) def __repr__(self): return '<Options for %s>' % self.object_name def __str__(self): return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name)) def _set_db_table(self, db_table): self._db_table = db_table def _get_db_table(self): if getattr(settings, 'DJANGO_STYLE_MODEL_KIND', True): if hasattr(self, '_db_table'): return self._db_table return '%s_%s' % (self.app_label, self.module_name) return self.object_name db_table = property(_get_db_table, _set_db_table) def _set_db_tablespace(self, db_tablespace): self._db_tablespace = db_tablespace def _get_db_tablespace(self): if hasattr(self, '_db_tablespace'): return self._db_tablespace return settings.DEFAULT_TABLESPACE db_tablespace = property(_get_db_tablespace, _set_db_tablespace) @property def verbose_name_raw(self): """ There are a few places where the untranslated verbose name is needed (so that we get the same value regardless of currently active locale). """ lang = get_language() deactivate_all() raw = force_unicode(self.verbose_name) activate(lang) return raw @property def local_fields(self): return tuple(sorted([p for p in self.model.properties().values() if not isinstance(p, db.ListProperty)], key=lambda prop: prop.creation_counter)) @property def local_many_to_many(self): return tuple(sorted([p for p in self.model.properties().values() if isinstance(p, db.ListProperty) and not (issubclass(self.model, polymodel.PolyModel) and p.name == 'class')], key=lambda prop: prop.creation_counter)) @property def fields(self): return self.local_fields + self.local_many_to_many def get_field(self, name, many_to_many=True): """ Returns the requested field by name. Raises FieldDoesNotExist on error. """ for f in self.fields: if f.name == name: return f from django.db.models.fields import FieldDoesNotExist raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name) def get_all_related_objects(self, local_only=False): try: self._related_objects_cache except AttributeError: self._fill_related_objects_cache() if local_only: return [k for k, v in self._related_objects_cache.items() if not v] return self._related_objects_cache.keys() def get_all_related_objects_with_model(self): """ Returns a list of (related-object, model) pairs. Similar to get_fields_with_model(). """ try: self._related_objects_cache except AttributeError: self._fill_related_objects_cache() return self._related_objects_cache.items() def _fill_related_objects_cache(self): from django.db.models.loading import get_models from django.db.models.related import RelatedObject from django.utils.datastructures import SortedDict cache = SortedDict() parent_list = self.get_parent_list() for parent in self.parents: for obj, model in parent._meta.get_all_related_objects_with_model(): if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list: continue if not model: cache[obj] = parent else: cache[obj] = model for klass in get_models(): for f in klass._meta.local_fields: if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta: cache[RelatedObject(f.rel.to, klass, f)] = None self._related_objects_cache = cache def get_all_related_many_to_many_objects(self, local_only=False): try: cache = self._related_many_to_many_cache except AttributeError: cache = self._fill_related_many_to_many_cache() if local_only: return [k for k, v in cache.items() if not v] return cache.keys() def get_all_related_m2m_objects_with_model(self): """ Returns a list of (related-m2m-object, model) pairs. Similar to get_fields_with_model(). """ try: cache = self._related_many_to_many_cache except AttributeError: cache = self._fill_related_many_to_many_cache() return cache.items() def _fill_related_many_to_many_cache(self): from django.db.models.loading import get_models, app_cache_ready from django.db.models.related import RelatedObject from django.utils.datastructures import SortedDict cache = SortedDict() parent_list = self.get_parent_list() for parent in self.parents: for obj, model in parent._meta.get_all_related_m2m_objects_with_model(): if obj.field.creation_counter < 0 and obj.model not in parent_list: continue if not model: cache[obj] = parent else: cache[obj] = model for klass in get_models(): for f in klass._meta.local_many_to_many: if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta: cache[RelatedObject(f.rel.to, klass, f)] = None if app_cache_ready(): self._related_many_to_many_cache = cache return cache def get_add_permission(self): return 'add_%s' % self.object_name.lower() def get_change_permission(self): return 'change_%s' % self.object_name.lower() def get_delete_permission(self): return 'delete_%s' % self.object_name.lower() def get_ordered_objects(self): return [] def get_parent_list(self): """ Returns a list of all the ancestor of this model as a list. Useful for determining if something is an ancestor, regardless of lineage. """ result = set() for parent in self.parents: result.add(parent) result.update(parent._meta.get_parent_list()) return result # Required to support reference properties to db.Model db.Model._meta = _meta(db.Model, ()) def _initialize_model(cls, bases): cls._meta = _meta(cls, bases) cls._default_manager = cls if not cls._meta.abstract: from django.db.models.loading import register_models register_models(cls._meta.app_label, cls) # Register models with Django from django.db.models import signals if not hasattr(db.PropertiedClass.__init__, 'patched'): old_propertied_class_init = db.PropertiedClass.__init__ def __init__(cls, name, bases, attrs, map_kind=True): """Creates a combined appengine and Django model. The resulting model will be known to both the appengine libraries and Django. """ _initialize_model(cls, bases) old_propertied_class_init(cls, name, bases, attrs, not cls._meta.abstract) signals.class_prepared.send(sender=cls) __init__.patched = True db.PropertiedClass.__init__ = __init__ if not hasattr(polymodel.PolymorphicClass.__init__, 'patched'): old_poly_init = polymodel.PolymorphicClass.__init__ def __init__(cls, name, bases, attrs): if polymodel.PolyModel not in bases: _initialize_model(cls, bases) old_poly_init(cls, name, bases, attrs) if polymodel.PolyModel not in bases: signals.class_prepared.send(sender=cls) __init__.patched = True polymodel.PolymorphicClass.__init__ = __init__ @classmethod def kind(cls): return cls._meta.db_table db.Model.kind = kind # Add model signals if not hasattr(db.Model.__init__, 'patched'): old_model_init = db.Model.__init__ def __init__(self, *args, **kwargs): signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs) old_model_init(self, *args, **kwargs) signals.post_init.send(sender=self.__class__, instance=self) __init__.patched = True db.Model.__init__ = __init__ if not hasattr(db.Model.put, 'patched'): old_put = db.Model.put def put(self, *args, **kwargs): signals.pre_save.send(sender=self.__class__, instance=self, raw=False) created = not self.is_saved() result = old_put(self, *args, **kwargs) signals.post_save.send(sender=self.__class__, instance=self, created=created, raw=False) return result put.patched = True db.Model.put = put if not hasattr(db.put, 'patched'): old_db_put = db.put def put(models, *args, **kwargs): if not isinstance(models, (list, tuple)): items = (models,) else: items = models items_created = [] for item in items: if not isinstance(item, db.Model): continue signals.pre_save.send(sender=item.__class__, instance=item, raw=False) items_created.append(not item.is_saved()) result = old_db_put(models, *args, **kwargs) for item, created in zip(items, items_created): if not isinstance(item, db.Model): continue signals.post_save.send(sender=item.__class__, instance=item, created=created, raw=False) return result put.patched = True db.put = put if not hasattr(db.Model.delete, 'patched'): old_delete = db.Model.delete def delete(self, *args, **kwargs): signals.pre_delete.send(sender=self.__class__, instance=self) result = old_delete(self, *args, **kwargs) signals.post_delete.send(sender=self.__class__, instance=self) return result delete.patched = True db.Model.delete = delete if not hasattr(db.delete, 'patched'): old_db_delete = db.delete def delete(models, *args, **kwargs): if not isinstance(models, (list, tuple)): items = (models,) else: items = models for item in items: if not isinstance(item, db.Model): continue signals.pre_delete.send(sender=item.__class__, instance=item) result = old_db_delete(models, *args, **kwargs) for item in items: if not isinstance(item, db.Model): continue signals.post_delete.send(sender=item.__class__, instance=item) return result delete.patched = True db.delete = delete # This has to come last because we load Django here from django.db.models.fields import BLANK_CHOICE_DASH def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): first_choice = include_blank and blank_choice or [] if self.choices: return first_choice + list(self.choices) if self.rel: return first_choice + [(obj.pk, unicode(obj)) for obj in self.rel.to.all().fetch(301)] return first_choice db.Property.get_choices = get_choices fix_app_engine_bugs() def fix_app_engine_bugs(): # Fix handling of verbose_name. Google resolves lazy translation objects # immedately which of course breaks translation support. # http://code.google.com/p/googleappengine/issues/detail?id=583 from django import forms from django.utils.text import capfirst # This import is needed, so the djangoforms patch can do its work, first from google.appengine.ext.db import djangoforms def get_form_field(self, form_class=forms.CharField, **kwargs): defaults = {'required': self.required} defaults['label'] = capfirst(self.verbose_name) if self.choices: choices = [] if not self.required or (self.default is None and 'initial' not in kwargs): choices.append(('', '---------')) for choice in self.choices: choices.append((unicode(choice), unicode(choice))) defaults['widget'] = forms.Select(choices=choices) if self.default is not None: defaults['initial'] = self.default defaults.update(kwargs) return form_class(**defaults) db.Property.get_form_field = get_form_field # Extend ModelForm with support for EmailProperty # http://code.google.com/p/googleappengine/issues/detail?id=880 def get_form_field(self, **kwargs): """Return a Django form field appropriate for an email property.""" defaults = {'form_class': forms.EmailField} defaults.update(kwargs) return super(db.EmailProperty, self).get_form_field(**defaults) db.EmailProperty.get_form_field = get_form_field # Fix DateTimeProperty, so it returns a property even for auto_now and # auto_now_add. # http://code.google.com/p/googleappengine/issues/detail?id=994 def get_form_field(self, **kwargs): defaults = {'form_class': forms.DateTimeField} defaults.update(kwargs) return super(db.DateTimeProperty, self).get_form_field(**defaults) db.DateTimeProperty.get_form_field = get_form_field def get_form_field(self, **kwargs): defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(db.DateProperty, self).get_form_field(**defaults) db.DateProperty.get_form_field = get_form_field def get_form_field(self, **kwargs): defaults = {'form_class': forms.TimeField} defaults.update(kwargs) return super(db.TimeProperty, self).get_form_field(**defaults) db.TimeProperty.get_form_field = get_form_field # Improve handing of StringListProperty def get_form_field(self, **kwargs): defaults = {'widget': forms.Textarea, 'initial': ''} defaults.update(kwargs) defaults['required'] = False return super(db.StringListProperty, self).get_form_field(**defaults) db.StringListProperty.get_form_field = get_form_field # Fix file uploads via BlobProperty def get_form_field(self, **kwargs): defaults = {'form_class': forms.FileField} defaults.update(kwargs) return super(db.BlobProperty, self).get_form_field(**defaults) db.BlobProperty.get_form_field = get_form_field def get_value_for_form(self, instance): return getattr(instance, self.name) db.BlobProperty.get_value_for_form = get_value_for_form from django.core.files.uploadedfile import UploadedFile def make_value_from_form(self, value): if isinstance(value, UploadedFile): return db.Blob(value.read()) return super(db.BlobProperty, self).make_value_from_form(value) db.BlobProperty.make_value_from_form = make_value_from_form # Optimize ReferenceProperty, so it returns the key directly # http://code.google.com/p/googleappengine/issues/detail?id=993 def get_value_for_form(self, instance): return self.get_value_for_datastore(instance) db.ReferenceProperty.get_value_for_form = get_value_for_form # Use our ModelChoiceField instead of Google's def get_form_field(self, **kwargs): defaults = {'form_class': forms.ModelChoiceField, 'queryset': self.reference_class.all()} defaults.update(kwargs) return super(db.ReferenceProperty, self).get_form_field(**defaults) db.ReferenceProperty.get_form_field = get_form_field def setup_logging(): from django.conf import settings if settings.DEBUG: logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().setLevel(logging.INFO)
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/patch.py
Python
asf20
27,320
from google.appengine.api import apiproxy_stub_map from google.appengine.ext import db from django.dispatch import Signal from django.db.models import signals from django.utils._threading_local import local from functools import wraps # Add signals which can be run after a transaction has been committed signals.post_save_committed = Signal() signals.post_delete_committed = Signal() local = local() # Patch transaction handlers, so we can support post_xxx_committed signals run_in_transaction = db.run_in_transaction if not hasattr(run_in_transaction, 'patched'): @wraps(run_in_transaction) def handle_signals(*args, **kwargs): try: if not getattr(local, 'in_transaction', False): local.in_transaction = True local.notify = [] result = run_in_transaction(*args, **kwargs) except: local.in_transaction = False local.notify = [] raise else: commit() return result handle_signals.patched = True db.run_in_transaction = handle_signals run_in_transaction_custom_retries = db.run_in_transaction_custom_retries if not hasattr(run_in_transaction_custom_retries, 'patched'): @wraps(run_in_transaction_custom_retries) def handle_signals(*args, **kwargs): try: result = run_in_transaction_custom_retries(*args, **kwargs) except: local.in_transaction = False local.notify = [] raise else: commit() return result handle_signals.patched = True db.run_in_transaction_custom_retries = handle_signals def hook(service, call, request, response): if call == 'Rollback': # This stores a list of tuples (action, sender, kwargs) # Possible actions: 'delete', 'save' local.in_transaction = True local.notify = [] apiproxy_stub_map.apiproxy.GetPostCallHooks().Append('tx_signals', hook) def commit(): local.in_transaction = False for action, sender, kwds in local.notify: signal = getattr(signals, 'post_%s_committed' % action) signal.send(sender=sender, **kwds) def entity_saved(sender, **kwargs): if 'signal' in kwargs: del kwargs['signal'] if getattr(local, 'in_transaction', False): local.notify.append(('save', sender, kwargs)) else: signals.post_save_committed.send(sender=sender, **kwargs) signals.post_save.connect(entity_saved) def entity_deleted(sender, **kwargs): if 'signal' in kwargs: del kwargs['signal'] if getattr(local, 'in_transaction', False): local.notify.append(('delete', sender, kwargs)) else: signals.post_delete_committed.send(sender=sender, **kwargs) signals.post_delete.connect(entity_deleted)
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/transactions.py
Python
asf20
2,808
from google.appengine.api import apiproxy_stub_map import os, sys have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3')) if have_appserver: appid = os.environ.get('APPLICATION_ID') else: try: from google.appengine.tools import dev_appserver from aecmd import PROJECT_DIR appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {}) appid = appconfig.application except ImportError: appid = None on_production_server = have_appserver and \ not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/__init__.py
Python
asf20
591
from google.appengine.api.memcache import *
100uhaco
trunk/GAE/common/appenginepatch/appenginepatcher/lib/memcache.py
Python
asf20
44
from ragendja.settings_post import settings from appenginepatcher import have_appserver, on_production_server if have_appserver and not on_production_server and \ settings.MEDIA_URL.startswith('/'): if settings.ADMIN_MEDIA_PREFIX.startswith(settings.MEDIA_URL): settings.ADMIN_MEDIA_PREFIX = '/generated_media' + \ settings.ADMIN_MEDIA_PREFIX settings.MEDIA_URL = '/generated_media' + settings.MEDIA_URL settings.MIDDLEWARE_CLASSES = ( 'mediautils.middleware.MediaMiddleware', ) + settings.MIDDLEWARE_CLASSES
100uhaco
trunk/GAE/common/appenginepatch/mediautils/settings.py
Python
asf20
587
# -*- coding: utf-8 -*- from django.conf import settings from django.utils.simplejson import dumps from os.path import getmtime import os, codecs, shutil, logging, re path_re = re.compile(r'/[^/]+/\.\./') MEDIA_VERSION = unicode(settings.MEDIA_VERSION) COMPRESSOR = os.path.join(os.path.dirname(__file__), '.yuicompressor.jar') PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname( os.path.dirname(__file__))))) GENERATED_MEDIA = os.path.join(PROJECT_ROOT, '_generated_media') MEDIA_ROOT = os.path.join(GENERATED_MEDIA, MEDIA_VERSION) DYNAMIC_MEDIA = os.path.join(PROJECT_ROOT, '.dynamic_media') # A list of file types that have to be combined MUST_COMBINE = ['.js', '.css'] # Detect language codes if not settings.USE_I18N: LANGUAGES = (settings.LANGUAGE_CODE,) else: LANGUAGES = [code for code, _ in settings.LANGUAGES] # Dynamic source handlers def site_data(**kwargs): """Provide site_data variable with settings (currently only MEDIA_URL).""" content = 'window.site_data = {};' content += 'window.site_data.settings = %s;' % dumps({ 'MEDIA_URL': settings.MEDIA_URL }) return content def lang_data(LANGUAGE_CODE, **kwargs): # These are needed for i18n from django.http import HttpRequest from django.views.i18n import javascript_catalog LANGUAGE_BIDI = LANGUAGE_CODE.split('-')[0] in \ settings.LANGUAGES_BIDI request = HttpRequest() request.GET['language'] = LANGUAGE_CODE # Add some JavaScript data content = 'var LANGUAGE_CODE = "%s";\n' % LANGUAGE_CODE content += 'var LANGUAGE_BIDI = ' + \ (LANGUAGE_BIDI and 'true' or 'false') + ';\n' content += javascript_catalog(request, packages=settings.INSTALLED_APPS).content # The hgettext() function just calls gettext() internally, but # it won't get indexed by makemessages. content += '\nwindow.hgettext = function(text) { return gettext(text); };\n' # Add a similar hngettext() function content += 'window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };\n' return content lang_data.name = 'lang-%(LANGUAGE_CODE)s.js' def generatemedia(compressed): if os.path.exists(MEDIA_ROOT): shutil.rmtree(MEDIA_ROOT) updatemedia(compressed) def copy_file(path, generated): dirpath = os.path.dirname(generated) if not os.path.exists(dirpath): os.makedirs(dirpath) shutil.copyfile(path, generated) def compress_file(path): if not path.endswith(('.css', '.js')): return from subprocess import Popen print ' Running yuicompressor...', try: cmd = Popen(['java', '-jar', COMPRESSOR, '--charset', 'UTF-8', path, '-o', path]) if cmd.wait() == 0: print '%d bytes' % os.path.getsize(path) else: print 'Failed!' except: raise Exception("Failed to execute Java VM. " "Please make sure that you have installed Java " "and that it's in your PATH.") def get_file_path(handler, target, media_dirs, **kwargs): if isinstance(handler, basestring): path = handler % dict(kwargs, target=target) app, filepath = path.replace('/', os.sep).split(os.sep, 1) return os.path.abspath(os.path.join(media_dirs[app], filepath)) ext = os.path.splitext(target)[1] owner = '' for app in settings.INSTALLED_APPS: if handler.__module__.startswith(app + '.') and len(app) > len(owner): owner = app owner = owner or handler.__module__ name = getattr(handler, 'name', handler.__name__ + ext) % dict(kwargs, target=target) assert '/' not in name return os.path.join(DYNAMIC_MEDIA, '%s-%s' % (owner, name)) def get_css_content(handler, content, **kwargs): # Add $MEDIA_URL variable to CSS files content = content.replace('$MEDIA_URL/', settings.MEDIA_URL) # Remove @charset rules content = re.sub(r'@charset(.*?);', '', content) if not isinstance(handler, basestring): return content def fixurls(path): # Resolve ../ paths path = '%s%s/%s' % (settings.MEDIA_URL, os.path.dirname(handler % dict(kwargs)), path.group(1)) while path_re.search(path): path = path_re.sub('/', path, 1) return 'url("%s")' % path # Make relative paths work with MEDIA_URL content = re.sub(r'url\s*\(["\']?([\w\.][^:]*?)["\']?\)', fixurls, content) return content def get_file_content(handler, cache, **kwargs): path = get_file_path(handler, **kwargs) if path not in cache: if isinstance(handler, basestring): try: file = codecs.open(path, 'r', 'utf-8') cache[path] = file.read().lstrip(codecs.BOM_UTF8.decode('utf-8') ).replace('\r\n', '\n').replace('\r', '\n') except: logging.error('Error in %s' % path) raise file.close() elif callable(handler): cache[path] = handler(**kwargs) else: raise ValueError('Media generator source "%r" not valid!' % handler) # Rewrite url() paths in CSS files ext = os.path.splitext(path)[1] if ext == '.css': cache[path] = get_css_content(handler, cache[path], **kwargs) return cache[path] def update_dynamic_file(handler, cache, **kwargs): assert callable(handler) path = get_file_path(handler, **kwargs) content = get_file_content(handler, cache, **kwargs) needs_update = not os.path.exists(path) if not needs_update: file = codecs.open(path, 'r', 'utf-8') if content != file.read(): needs_update = True file.close() if needs_update: file = codecs.open(path, 'w', 'utf-8') file.write(content) file.close() return needs_update def get_target_content(group, cache, **kwargs): content = '' for handler in group: content += get_file_content(handler, cache, **kwargs) content += '\n' return content def get_targets(combine_media=settings.COMBINE_MEDIA, **kwargs): """Returns all files that must be combined.""" targets = [] for target in sorted(combine_media.keys()): group = combine_media[target] if '.site_data.js' in group: # site_data must always come first because other modules might # depend on it group.remove('.site_data.js') group.insert(0, site_data) if '%(LANGUAGE_CODE)s' in target: # This file uses i18n, so generate a separate file per language. # The language data is always added before all other files. for LANGUAGE_CODE in LANGUAGES: data = kwargs.copy() data['LANGUAGE_CODE'] = LANGUAGE_CODE filename = target % data data['target'] = filename group.insert(0, lang_data) targets.append((filename, data, group)) elif '%(LANGUAGE_DIR)s' in target: # Generate CSS files for both text directions for LANGUAGE_DIR in ('ltr', 'rtl'): data = kwargs.copy() data['LANGUAGE_DIR'] = LANGUAGE_DIR filename = target % data data['target'] = filename targets.append((filename, data, group)) else: data = kwargs.copy() filename = target % data data['target'] = filename targets.append((filename, data, group)) return targets def get_copy_targets(media_dirs, **kwargs): """Returns paths of files that must be copied directly.""" # Some files types (MUST_COMBINE) never get copied. # They must always be combined. targets = {} for app, media_dir in media_dirs.items(): for root, dirs, files in os.walk(media_dir): for name in dirs[:]: if name.startswith('.'): dirs.remove(name) for file in files: if file.startswith('.') or file.endswith(tuple(MUST_COMBINE)): continue path = os.path.abspath(os.path.join(root, file)) base = app + path[len(media_dir):] targets[base.replace(os.sep, '/')] = path return targets def cleanup_dir(dir, paths): # Remove old generated files keep = [] dir = os.path.abspath(dir) for path in paths: if not os.path.isabs(path): path = os.path.join(dir, path) path = os.path.abspath(path) while path not in keep and path != dir: keep.append(path) path = os.path.dirname(path) for root, dirs, files in os.walk(dir): for name in dirs[:]: path = os.path.abspath(os.path.join(root, name)) if path not in keep: shutil.rmtree(path) dirs.remove(name) for file in files: path = os.path.abspath(os.path.join(root, file)) if path not in keep: os.remove(path) def get_media_dirs(): from ragendja.apputils import get_app_dirs media_dirs = get_app_dirs('media') media_dirs['global'] = os.path.join(PROJECT_ROOT, 'media') return media_dirs def updatemedia(compressed=None): if 'mediautils' not in settings.INSTALLED_APPS: return # Remove unused media versions if os.path.exists(GENERATED_MEDIA): entries = os.listdir(GENERATED_MEDIA) if len(entries) != 1 or MEDIA_VERSION not in entries: shutil.rmtree(GENERATED_MEDIA) from ragendja.apputils import get_app_dirs # Remove old media if settings got modified (too much work to check # if COMBINE_MEDIA was changed) mtime = getmtime(os.path.join(PROJECT_ROOT, 'settings.py')) for app_path in get_app_dirs().values(): path = os.path.join(app_path, 'settings.py') if os.path.exists(path) and os.path.getmtime(path) > mtime: mtime = os.path.getmtime(path) if os.path.exists(MEDIA_ROOT) and getmtime(MEDIA_ROOT) <= mtime: shutil.rmtree(MEDIA_ROOT) if not os.path.exists(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) if not os.path.exists(DYNAMIC_MEDIA): os.makedirs(DYNAMIC_MEDIA) if compressed is None: compressed = not getattr(settings, 'FORCE_UNCOMPRESSED_MEDIA', False) media_dirs = get_media_dirs() data = {'media_dirs': media_dirs} targets = get_targets(**data) copy_targets = get_copy_targets(**data) target_names = [target[0] for target in targets] # Remove unneeded files cleanup_dir(MEDIA_ROOT, target_names + copy_targets.keys()) dynamic_files = [] for target, kwargs, group in targets: for handler in group: if callable(handler): dynamic_files.append(get_file_path(handler, **kwargs)) cleanup_dir(DYNAMIC_MEDIA, dynamic_files) # Copy files for target in sorted(copy_targets.keys()): # Only overwrite files if they've been modified. Also, only # copy files that won't get combined. path = copy_targets[target] generated = os.path.join(MEDIA_ROOT, target.replace('/', os.sep)) if os.path.exists(generated) and \ getmtime(generated) >= getmtime(path): continue print 'Copying %s...' % target copy_file(path, generated) # Update dynamic files cache = {} for target, kwargs, group in targets: for handler in group: if callable(handler): update_dynamic_file(handler, cache, **kwargs) # Combine media files for target, kwargs, group in targets: files = [get_file_path(handler, **kwargs) for handler in group] path = os.path.join(MEDIA_ROOT, target.replace('/', os.sep)) # Only overwrite files if they've been modified if os.path.exists(path): target_mtime = getmtime(path) if not [1 for name in files if os.path.exists(name) and getmtime(name) >= target_mtime]: continue print 'Combining %s...' % target dirpath = os.path.dirname(path) if not os.path.exists(dirpath): os.makedirs(dirpath) file = codecs.open(path, 'w', 'utf-8') file.write(get_target_content(group, cache, **kwargs)) file.close() if compressed: compress_file(path)
100uhaco
trunk/GAE/common/appenginepatch/mediautils/generatemedia.py
Python
asf20
12,670
# -*- coding: utf-8 -*- from os.path import getmtime import codecs, os def updatemessages(): from django.conf import settings if not settings.USE_I18N: return from django.core.management.commands.compilemessages import compile_messages if any([needs_update(path) for path in settings.LOCALE_PATHS]): compile_messages() LOCALE_PATHS = settings.LOCALE_PATHS settings.LOCALE_PATHS = () cwd = os.getcwdu() for app in settings.INSTALLED_APPS: path = os.path.dirname(__import__(app, {}, {}, ['']).__file__) locale = os.path.join(path, 'locale') if os.path.isdir(locale): # Copy Python translations into JavaScript translations update_js_translations(locale) if needs_update(locale): os.chdir(path) compile_messages() settings.LOCALE_PATHS = LOCALE_PATHS os.chdir(cwd) def needs_update(locale): for root, dirs, files in os.walk(locale): po_files = [os.path.join(root, file) for file in files if file.endswith('.po')] for po_file in po_files: mo_file = po_file[:-2] + 'mo' if not os.path.exists(mo_file) or \ getmtime(po_file) > getmtime(mo_file): return True return False def update_js_translations(locale): for lang in os.listdir(locale): base_path = os.path.join(locale, lang, 'LC_MESSAGES') py_file = os.path.join(base_path, 'django.po') js_file = os.path.join(base_path, 'djangojs.po') modified = False if os.path.exists(py_file) and os.path.exists(js_file): py_lines, py_mapping = load_translations(py_file) js_lines, js_mapping = load_translations(js_file) for msgid in js_mapping: if msgid in py_mapping: py_index = py_mapping[msgid] js_index = js_mapping[msgid] if py_lines[py_index] != js_lines[js_index]: modified = True # Copy comment to JS, too if js_index >= 2 and py_index >= 2: if js_lines[js_index - 2].startswith('#') and \ py_lines[py_index - 2].startswith('#'): js_lines[js_index - 2] = py_lines[py_index - 2] js_lines[js_index] = py_lines[py_index] if modified: print 'Updating JS locale for %s' % os.path.join(locale, lang) file = codecs.open(js_file, 'w', 'utf-8') file.write(''.join(js_lines)) file.close() def load_translations(path): """Loads translations grouped into logical sections.""" file = codecs.open(path, 'r', 'utf-8') lines = file.readlines() file.close() mapping = {} msgid = None start = -1 resultlines = [] for index, line in enumerate(lines): # Group comments if line.startswith('#'): if resultlines and resultlines[-1].startswith('#'): resultlines[-1] = resultlines[-1] + lines[index] else: resultlines.append(lines[index]) continue if msgid is not None and (not line.strip() or line.startswith('msgid ')): mapping[msgid] = len(resultlines) resultlines.append(''.join(lines[start:index])) msgid = None start = -1 if line.startswith('msgid '): line = line[len('msgid'):].strip() start = -1 msgid = '' if start < 0 and line.startswith('"'): msgid += line.strip()[1:-1] resultlines.append(lines[index]) continue if line.startswith('msgstr') and start < 0: start = index if start < 0: if resultlines and not resultlines[-1].startswith('msgstr'): resultlines[-1] = resultlines[-1] + lines[index] else: resultlines.append(lines[index]) if msgid and start: mapping[msgid] = len(resultlines) resultlines.append(''.join(lines[start:])) return resultlines, mapping
100uhaco
trunk/GAE/common/appenginepatch/mediautils/compilemessages.py
Python
asf20
4,228
# -*- coding: utf-8 -*- """ This app combines media files specified in the COMBINE_MEDIA setting into one single file. It's a dictionary mapping the combined name to a tuple of files that should be combined: COMBINE_MEDIA = { 'global/js/combined.js': ( 'global/js/main.js', 'app/js/other.js', ), 'global/css/main.css': ( 'global/css/base.css', 'app/css/app.css', ) } The files will automatically be combined if you use manage.py runserver. Files that shouldn't be combined are simply copied. Also, all css and js files get compressed with yuicompressor. The result is written in a folder named _generated_media. If the target is a JavaScript file whose name contains the string '%(LANGUAGE_CODE)s' it'll automatically be internationalized and multiple files will be generated (one for each language code). """ from django.core.management.base import NoArgsCommand from optparse import make_option from mediautils.generatemedia import generatemedia, updatemedia, MEDIA_ROOT import os, shutil class Command(NoArgsCommand): help = 'Combines and compresses your media files and saves them in _generated_media.' option_list = NoArgsCommand.option_list + ( make_option('--uncompressed', action='store_true', dest='uncompressed', help='Do not run yuicompressor on generated media.'), make_option('--update', action='store_true', dest='update', help='Only update changed files instead of regenerating everything.'), ) requires_model_validation = False def handle_noargs(self, **options): compressed = None if options.get('uncompressed'): compressed = False if options.get('update'): updatemedia(compressed) else: generatemedia(compressed)
100uhaco
trunk/GAE/common/appenginepatch/mediautils/management/commands/generatemedia.py
Python
asf20
1,813
# -*- coding: utf-8 -*- from django.core.management.base import NoArgsCommand, CommandError from optparse import make_option import os, cStringIO, gzip, mimetypes class Command(NoArgsCommand): help = 'Uploads your _generated_media folder to Amazon S3.' option_list = NoArgsCommand.option_list + ( make_option('--production', action='store_true', dest='production', help='Does a real upload instead of a simulation.'), ) requires_model_validation = False def handle_noargs(self, **options): s3uploadmedia(options.get('production', False)) def submit_cb(bytes_so_far, total_bytes): print ' %d bytes transferred / %d bytes total\r' % (bytes_so_far, total_bytes), def s3uploadmedia(production): from django.conf import settings from ragendja.apputils import get_app_dirs try: from boto.s3.connection import S3Connection except ImportError: raise CommandError('This command requires boto.') bucket_name = settings.MEDIA_BUCKET if production: connection = S3Connection() bucket = connection.get_bucket(bucket_name) print 'Uploading to %s' % bucket_name print '\nDeleting old files...' if production: for key in bucket: key.delete() print '\nUploading new files...' base = os.path.abspath('_generated_media') for root, dirs, files in os.walk(base): for file in files: path = os.path.join(root, file) key_name = path[len(base)+1:].replace(os.sep, '/') print 'Copying %s (%d bytes)' % (key_name, os.path.getsize(path)) if production: key = bucket.new_key(key_name) fp = open(path, 'rb') headers = {} # Text files should be compressed to speed up site loading if file.split('.')[-1] in ('css', 'ht', 'js'): print ' GZipping...', gzbuf = cStringIO.StringIO() zfile = gzip.GzipFile(mode='wb', fileobj=gzbuf) zfile.write(fp.read()) zfile.close() fp.close() print '%d bytes' % gzbuf.tell() gzbuf.seek(0) fp = gzbuf headers['Content-Encoding'] = 'gzip' headers['Content-Type'] = mimetypes.guess_type(file)[0] if production: key.set_contents_from_file(fp, headers=headers, cb=submit_cb, num_cb=10, policy='public-read') fp.close() if not production: print '==============================================' print 'This was just a simulation.' print 'Please use --production to enforce the update.' print 'Warning: This will change the production site!' print '=============================================='
100uhaco
trunk/GAE/common/appenginepatch/mediautils/management/commands/s3uploadmedia.py
Python
asf20
2,908
# -*- coding: utf-8 -*- from django.http import HttpResponse, Http404 from django.views.decorators.cache import cache_control from mediautils.generatemedia import get_targets, get_copy_targets, \ get_target_content, get_media_dirs from mimetypes import guess_type from ragendja.template import render_to_response @cache_control(public=True, max_age=3600*24*60*60) def get_file(request, path): media_dirs = get_media_dirs() data = {'media_dirs': media_dirs} targets = get_targets(**data) copy_targets = get_copy_targets(**data) target_names = [target[0] for target in targets] name = path.rsplit('/', 1)[-1] cache = {} if path in target_names: target, kwargs, group = targets[target_names.index(path)] content = get_target_content(group, cache, **kwargs) elif path in copy_targets: fp = open(copy_targets[path], 'rb') content = fp.read() fp.close() else: raise Http404('Media file not found: %s' % path) return HttpResponse(content, content_type=guess_type(name)[0] or 'application/octet-stream')
100uhaco
trunk/GAE/common/appenginepatch/mediautils/views.py
Python
asf20
1,103
# -*- coding: utf-8 -*- from django.conf import settings from mediautils.views import get_file class MediaMiddleware(object): """Returns media files. This is a middleware, so it can handle the request as early as possible and thus with minimum overhead.""" def process_request(self, request): if request.path.startswith(settings.MEDIA_URL): path = request.path[len(settings.MEDIA_URL):] return get_file(request, path) return None
100uhaco
trunk/GAE/common/appenginepatch/mediautils/middleware.py
Python
asf20
492
from django.conf import settings from django.core.cache import cache from django.contrib.sites.models import Site from ragendja.dbutils import db_create from ragendja.pyutils import make_tls_property _default_site_id = getattr(settings, 'SITE_ID', None) SITE_ID = settings.__class__.SITE_ID = make_tls_property() class DynamicSiteIDMiddleware(object): """Sets settings.SIDE_ID based on request's domain""" def process_request(self, request): # Ignore port if it's 80 or 443 if ':' in request.get_host(): domain, port = request.get_host().split(':') if int(port) not in (80, 443): domain = request.get_host() else: domain = request.get_host().split(':')[0] # We cache the SITE_ID cache_key = 'Site:domain:%s' % domain site = cache.get(cache_key) if site: SITE_ID.value = site else: site = Site.all().filter('domain =', domain).get() if not site: # Fall back to with/without 'www.' if domain.startswith('www.'): fallback_domain = domain[4:] else: fallback_domain = 'www.' + domain site = Site.all().filter('domain =', fallback_domain).get() # Add site if it doesn't exist if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY', True): site = db_create(Site, domain=domain, name=domain) site.put() # Set SITE_ID for this thread/request if site: SITE_ID.value = str(site.key()) else: SITE_ID.value = _default_site_id cache.set(cache_key, SITE_ID.value, 5*60)
100uhaco
trunk/GAE/common/appenginepatch/ragendja/sites/dynamicsite.py
Python
asf20
1,805
# -*- coding: utf-8 -*- """ Imports urlpatterns from apps, so we can have nice plug-n-play installation. :) """ from django.conf.urls.defaults import * from django.conf import settings IGNORE_APP_URLSAUTO = getattr(settings, 'IGNORE_APP_URLSAUTO', ()) check_app_imports = getattr(settings, 'check_app_imports', None) urlpatterns = patterns('') for app in settings.INSTALLED_APPS: if app == 'ragendja' or app.startswith('django.') or \ app in IGNORE_APP_URLSAUTO: continue appname = app.rsplit('.', 1)[-1] try: if check_app_imports: check_app_imports(app) module = __import__(app + '.urlsauto', {}, {}, ['']) except ImportError: pass else: if hasattr(module, 'urlpatterns'): urlpatterns += patterns('', (r'^%s/' % appname, include(app + '.urlsauto')),) if hasattr(module, 'rootpatterns'): urlpatterns += module.rootpatterns
100uhaco
trunk/GAE/common/appenginepatch/ragendja/urlsauto.py
Python
asf20
983
from django.conf import settings import os def import_module(module_name): return __import__(module_name, {}, {}, ['']) def import_package(package_name): package = [import_module(package_name)] if package[0].__file__.rstrip('.pyc').rstrip('.py').endswith('__init__'): package.extend([import_module(package_name + '.' + name) for name in list_modules(package[0])]) return package def list_modules(package): dir = os.path.normpath(os.path.dirname(package.__file__)) try: return set([name.rsplit('.', 1)[0] for name in os.listdir(dir) if not name.startswith('_') and name.endswith(('.py', '.pyc'))]) except OSError: return [] def get_app_modules(module_name=None): app_map = {} for app in settings.INSTALLED_APPS: appname = app.rsplit('.', 1)[-1] try: if module_name: app_map[appname] = import_package(app + '.' + module_name) else: app_map[appname] = [import_module(app)] except ImportError: if module_name in list_modules(import_module(app)): raise return app_map def get_app_dirs(subdir=None): app_map = {} for appname, module in get_app_modules().items(): dir = os.path.abspath(os.path.dirname(module[0].__file__)) if subdir: dir = os.path.join(dir, subdir) if os.path.isdir(dir): app_map[appname] = dir return app_map
100uhaco
trunk/GAE/common/appenginepatch/ragendja/apputils.py
Python
asf20
1,497
# -*- coding: utf-8 -*- from django.utils._threading_local import local def make_tls_property(default=None): """Creates a class-wide instance property with a thread-specific value.""" class TLSProperty(object): def __init__(self): self.local = local() def __get__(self, instance, cls): if not instance: return self return self.value def __set__(self, instance, value): self.value = value def _get_value(self): return getattr(self.local, 'value', default) def _set_value(self, value): self.local.value = value value = property(_get_value, _set_value) return TLSProperty() def getattr_by_path(obj, attr, *default): """Like getattr(), but can go down a hierarchy like 'attr.subattr'""" value = obj for part in attr.split('.'): if not hasattr(value, part) and len(default): return default[0] value = getattr(value, part) if callable(value): value = value() return value def subdict(data, *attrs): """Returns a subset of the keys of a dictionary.""" result = {} result.update([(key, data[key]) for key in attrs]) return result def equal_lists(left, right): """ Compares two lists and returs True if they contain the same elements, but doesn't require that they have the same order. """ right = list(right) if len(left) != len(right): return False for item in left: if item in right: del right[right.index(item)] else: return False return True def object_list_to_table(headings, dict_list): """ Converts objects to table-style list of rows with heading: Example: x.a = 1 x.b = 2 x.c = 3 y.a = 11 y.b = 12 y.c = 13 object_list_to_table(('a', 'b', 'c'), [x, y]) results in the following (dict keys reordered for better readability): [ ('a', 'b', 'c'), (1, 2, 3), (11, 12, 13), ] """ return [headings] + [tuple([getattr_by_path(row, heading, None) for heading in headings]) for row in dict_list] def dict_list_to_table(headings, dict_list): """ Converts dict to table-style list of rows with heading: Example: dict_list_to_table(('a', 'b', 'c'), [{'a': 1, 'b': 2, 'c': 3}, {'a': 11, 'b': 12, 'c': 13}]) results in the following (dict keys reordered for better readability): [ ('a', 'b', 'c'), (1, 2, 3), (11, 12, 13), ] """ return [headings] + [tuple([row[heading] for heading in headings]) for row in dict_list]
100uhaco
trunk/GAE/common/appenginepatch/ragendja/pyutils.py
Python
asf20
2,758
# -*- coding: utf-8 -*- from django.test import TestCase from google.appengine.ext import db from pyutils import object_list_to_table, equal_lists import os class ModelTestCase(TestCase): """ A test case for models that provides an easy way to validate the DB contents against a given list of row-values. You have to specify the model to validate using the 'model' attribute: class MyTestCase(ModelTestCase): model = MyModel """ def validate_state(self, columns, *state_table): """ Validates that the DB contains exactly the values given in the state table. The list of columns is given in the columns tuple. Example: self.validate_state( ('a', 'b', 'c'), (1, 2, 3), (11, 12, 13), ) validates that the table contains exactly two rows and that their 'a', 'b', and 'c' attributes are 1, 2, 3 for one row and 11, 12, 13 for the other row. The order of the rows doesn't matter. """ current_state = object_list_to_table(columns, self.model.all())[1:] if not equal_lists(current_state, state_table): print 'DB state not valid:' print 'Current state:' print columns for state in current_state: print state print 'Should be:' for state in state_table: print state self.fail('DB state not valid')
100uhaco
trunk/GAE/common/appenginepatch/ragendja/testutils.py
Python
asf20
1,487
from copy import deepcopy import re from django import forms from django.utils.datastructures import SortedDict, MultiValueDict from django.utils.html import conditional_escape from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode from django.utils.safestring import mark_safe from django.forms.widgets import flatatt from google.appengine.ext import db class FakeModelIterator(object): def __init__(self, fake_model): self.fake_model = fake_model def __iter__(self): for item in self.fake_model.all(): yield (item.get_value_for_datastore(), unicode(item)) class FakeModelChoiceField(forms.ChoiceField): def __init__(self, fake_model, *args, **kwargs): self.fake_model = fake_model kwargs['choices'] = () super(FakeModelChoiceField, self).__init__(*args, **kwargs) def _get_choices(self): return self._choices def _set_choices(self, choices): self._choices = self.widget.choices = FakeModelIterator(self.fake_model) choices = property(_get_choices, _set_choices) def clean(self, value): value = super(FakeModelChoiceField, self).clean(value) return self.fake_model.make_value_from_datastore(value) class FakeModelMultipleChoiceField(forms.MultipleChoiceField): def __init__(self, fake_model, *args, **kwargs): self.fake_model = fake_model kwargs['choices'] = () super(FakeModelMultipleChoiceField, self).__init__(*args, **kwargs) def _get_choices(self): return self._choices def _set_choices(self, choices): self._choices = self.widget.choices = FakeModelIterator(self.fake_model) choices = property(_get_choices, _set_choices) def clean(self, value): value = super(FakeModelMultipleChoiceField, self).clean(value) return [self.fake_model.make_value_from_datastore(item) for item in value] class FormWithSets(object): def __init__(self, form, formsets=()): self.form = form setattr(self, '__module__', form.__module__) setattr(self, '__name__', form.__name__ + 'WithSets') setattr(self, '__doc__', form.__doc__) self._meta = form._meta fields = [(name, field) for name, field in form.base_fields.iteritems() if isinstance(field, FormSetField)] formset_dict = dict(formsets) newformsets = [] for name, field in fields: if formset_dict.has_key(name): continue newformsets.append((name, {'formset':field.make_formset(form._meta.model)})) self.formsets = formsets + tuple(newformsets) def __call__(self, *args, **kwargs): prefix = kwargs['prefix'] + '-' if 'prefix' in kwargs else '' form = self.form(*args, **kwargs) if 'initial' in kwargs: del kwargs['initial'] formsets = [] for name, formset in self.formsets: kwargs['prefix'] = prefix + name instance = formset['formset'](*args, **kwargs) if form.base_fields.has_key(name): field = form.base_fields[name] else: field = FormSetField(formset['formset'].model, **formset) formsets.append(BoundFormSet(field, instance, name, formset)) return type(self.__name__ + 'Instance', (FormWithSetsInstance, ), {})(self, form, formsets) def pretty_name(name): "Converts 'first_name' to 'First name'" name = name[0].upper() + name[1:] return name.replace('_', ' ') table_sections_re = re.compile(r'^(.*?)(<tr>.*</tr>)(.*?)$', re.DOTALL) table_row_re = re.compile(r'(<tr>(<th><label.*?</label></th>)(<td>.*?</td>)</tr>)', re.DOTALL) ul_sections_re = re.compile(r'^(.*?)(<li>.*</li>)(.*?)$', re.DOTALL) ul_row_re = re.compile(r'(<li>(<label.*?</label>)(.*?)</li>)', re.DOTALL) p_sections_re = re.compile(r'^(.*?)(<p>.*</p>)(.*?)$', re.DOTALL) p_row_re = re.compile(r'(<p>(<label.*?</label>)(.*?)</p>)', re.DOTALL) label_re = re.compile(r'^(.*)<label for="id_(.*?)">(.*)</label>(.*)$') hidden_re = re.compile(r'(<input type="hidden".* />)', re.DOTALL) class BoundFormSet(StrAndUnicode): def __init__(self, field, formset, name, args): self.field = field self.formset = formset self.name = name self.args = args if self.field.label is None: self.label = pretty_name(name) else: self.label = self.field.label self.auto_id = self.formset.auto_id % self.formset.prefix if args.has_key('attrs'): self.attrs = args['attrs'].copy() else: self.attrs = {} def __unicode__(self): """Renders this field as an HTML widget.""" return self.as_widget() def as_widget(self, attrs=None): """ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used. """ attrs = attrs or {} auto_id = self.auto_id if auto_id and 'id' not in attrs and not self.args.has_key('id'): attrs['id'] = auto_id try: data = self.formset.as_table() name = self.name return self.render(name, data, attrs=attrs) except Exception, e: import traceback return traceback.format_exc() def render(self, name, value, attrs=None): table_sections = table_sections_re.search(value).groups() output = [] heads = [] current_row = [] first_row = True first_head_id = None prefix = 'id_%s-%%s-' % self.formset.prefix for row, head, item in table_row_re.findall(table_sections[1]): if first_row: head_groups = label_re.search(head).groups() if first_head_id == head_groups[1]: first_row = False output.append(current_row) current_row = [] else: heads.append('%s%s%s' % (head_groups[0], head_groups[2], head_groups[3])) if first_head_id is None: first_head_id = head_groups[1].replace('-0-','-1-') current_row.append(item) if not first_row and len(current_row) >= len(heads): output.append(current_row) current_row = [] if len(current_row) != 0: raise Exception('Unbalanced render') return mark_safe(u'%s<table%s><tr>%s</tr><tr>%s</tr></table>%s'%( table_sections[0], flatatt(attrs), u''.join(heads), u'</tr><tr>'.join((u''.join(x) for x in output)), table_sections[2])) class CachedQuerySet(object): def __init__(self, get_queryset): self.queryset_results = (x for x in get_queryset()) def __call__(self): return self.queryset_results class FormWithSetsInstance(object): def __init__(self, master, form, formsets): self.master = master self.form = form self.formsets = formsets self.instance = form.instance def __unicode__(self): return self.as_table() def is_valid(self): result = self.form.is_valid() for bf in self.formsets: result = bf.formset.is_valid() and result return result def save(self, *args, **kwargs): def save_forms(forms, obj=None): for form in forms: if not instance and form != self.form: for row in form.forms: row.cleaned_data[form.rel_name] = obj form_obj = form.save(*args, **kwargs) if form == self.form: obj = form_obj return obj instance = self.form.instance grouped = [] ungrouped = [] # cache the result of get_queryset so that it doesn't run inside the transaction for bf in self.formsets: if bf.formset.rel_name == 'parent': grouped.append(bf.formset) else: ungrouped.append(bf.formset) bf.formset_get_queryset = bf.formset.get_queryset bf.formset.get_queryset = CachedQuerySet(bf.formset_get_queryset) if grouped: grouped.insert(0, self.form) else: ungrouped.insert(0, self.form) obj = None if grouped: obj = db.run_in_transaction(save_forms, grouped) obj = save_forms(ungrouped, obj) for bf in self.formsets: bf.formset.get_queryset = bf.formset_get_queryset del bf.formset_get_queryset return obj def _html_output(self, form_as, normal_row, help_text_html, sections_re, row_re): formsets = SortedDict() for bf in self.formsets: if bf.label: label = conditional_escape(force_unicode(bf.label)) # Only add the suffix if the label does not end in # punctuation. if self.form.label_suffix: if label[-1] not in ':?.!': label += self.form.label_suffix label = label or '' else: label = '' if bf.field.help_text: help_text = help_text_html % force_unicode(bf.field.help_text) else: help_text = u'' formsets[bf.name] = {'label': force_unicode(label), 'field': unicode(bf), 'help_text': help_text} try: output = [] data = form_as() section_search = sections_re.search(data) if formsets: hidden = u''.join(hidden_re.findall(data)) last_formset_name, last_formset = formsets.items()[-1] last_formset['field'] = last_formset['field'] + hidden formsets[last_formset_name] = normal_row % last_formset for name, formset in formsets.items()[:-1]: formsets[name] = normal_row % formset if not section_search: output.append(data) else: section_groups = section_search.groups() for row, head, item in row_re.findall(section_groups[1]): head_search = label_re.search(head) if head_search: id = head_search.groups()[1] if formsets.has_key(id): row = formsets[id] del formsets[id] output.append(row) for name, row in formsets.items(): if name in self.form.fields.keyOrder: output.append(row) return mark_safe(u'\n'.join(output)) except Exception,e: import traceback return traceback.format_exc() def as_table(self): "Returns this form rendered as HTML <tr>s -- excluding the <table></table>." return self._html_output(self.form.as_table, u'<tr><th>%(label)s</th><td>%(help_text)s%(field)s</td></tr>', u'<br />%s', table_sections_re, table_row_re) def as_ul(self): "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>." return self._html_output(self.form.as_ul, u'<li>%(label)s %(help_text)s%(field)s</li>', u' %s', ul_sections_re, ul_row_re) def as_p(self): "Returns this form rendered as HTML <p>s." return self._html_output(self.form.as_p, u'<p>%(label)s %(help_text)s</p>%(field)s', u' %s', p_sections_re, p_row_re) def full_clean(self): self.form.full_clean() for bf in self.formsets: bf.formset.full_clean() def has_changed(self): result = self.form.has_changed() for bf in self.formsets: result = bf.formset.has_changed() or result return result def is_multipart(self): result = self.form.is_multipart() for bf in self.formsets: result = bf.formset.is_multipart() or result return result @property def media(self): return mark_safe(unicode(self.form.media) + u'\n'.join([unicode(f.formset.media) for f in self.formsets])) from django.forms.fields import Field from django.forms.widgets import Widget from django.forms.models import inlineformset_factory class FormSetWidget(Widget): def __init__(self, field, attrs=None): super(FormSetWidget, self).__init__(attrs) self.field = field def render(self, name, value, attrs=None): if value is None: value = 'FormWithSets decorator required to render %s FormSet' % self.field.model.__name__ value = force_unicode(value) final_attrs = self.build_attrs(attrs, name=name) return mark_safe(conditional_escape(value)) class FormSetField(Field): def __init__(self, model, widget=FormSetWidget, label=None, initial=None, help_text=None, error_messages=None, show_hidden_initial=False, formset_factory=inlineformset_factory, *args, **kwargs): widget = widget(self) super(FormSetField, self).__init__(required=False, widget=widget, label=label, initial=initial, help_text=help_text, error_messages=error_messages, show_hidden_initial=show_hidden_initial) self.model = model self.formset_factory = formset_factory self.args = args self.kwargs = kwargs def make_formset(self, parent_model): return self.formset_factory(parent_model, self.model, *self.args, **self.kwargs)
100uhaco
trunk/GAE/common/appenginepatch/ragendja/forms.py
Python
asf20
13,674
# -*- coding: utf-8 -*- from copy import deepcopy from django.forms.forms import NON_FIELD_ERRORS from django.template import Library from django.utils.datastructures import SortedDict from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from ragendja.dbutils import prefetch_references register = Library() register.filter('prefetch_references', prefetch_references) _js_escapes = { '>': r'\x3E', '<': r'\x3C', '&': r'\x26', '=': r'\x3D', '-': r'\x2D', ';': r'\x3B', } @register.filter def encodejs(value): from django.utils import simplejson from ragendja.json import LazyEncoder value = simplejson.dumps(value, cls=LazyEncoder) for bad, good in _js_escapes.items(): value = value.replace(bad, good) return mark_safe(value) @register.filter def urlquerybase(url): """ Appends '?' or '&' to an url, so you can easily add extra GET parameters. """ if url: if '?' in url: url += '&' else: url += '?' return url @register.simple_tag def htrans(value): """ Creates a "hidden" translation. Translates a string, but doesn't add it to django.po. This is useful if you use the same string in multiple apps and don't want to translate it in each of them (the translations will get overriden by the last app, anyway). """ return _(value) @register.simple_tag def exclude_form_fields(form=None, fields=None, as_choice='as_table', global_errors=True): fields=fields.replace(' ', '').split(',') if not global_errors: form.errors[NON_FIELD_ERRORS] = form.error_class() fields_backup = deepcopy(form.fields) for field in fields: if field in form.fields: del form.fields[field] resulting_text = getattr(form, as_choice)() form.fields = fields_backup return resulting_text @register.simple_tag def include_form_fields(form=None, fields=None, as_choice='as_table', global_errors=True): fields=fields.replace(' ', '').split(',') if not global_errors: form.errors[NON_FIELD_ERRORS] = form.error_class() fields_backup = deepcopy(form.fields) form.fields = SortedDict() for field in fields: if field in fields_backup: form.fields[field] = fields_backup[field] resulting_text = getattr(form, as_choice)() form.fields = fields_backup return resulting_text @register.simple_tag def ordered_form(form=None, fields=None, as_choice='as_table'): resulting_text = '' if len(form.non_field_errors()) != 0: fields_backup = deepcopy(form.fields) form.fields = {} resulting_text = getattr(form, as_choice)() form.fields = fields_backup resulting_text = resulting_text + include_form_fields(form, fields, as_choice, False) + exclude_form_fields(form, fields, as_choice, False) return resulting_text
100uhaco
trunk/GAE/common/appenginepatch/ragendja/templatetags/ragendjatags.py
Python
asf20
3,006
# -*- coding: utf-8 -*- from django.conf import settings from django.template import Library from django.utils.html import escape from google.appengine.api import users register = Library() @register.simple_tag def google_login_url(redirect=settings.LOGIN_REDIRECT_URL): return escape(users.create_login_url(redirect)) @register.simple_tag def google_logout_url(redirect='/'): prefixes = getattr(settings, 'LOGIN_REQUIRED_PREFIXES', ()) if any(redirect.startswith(prefix) for prefix in prefixes): redirect = '/' return escape(users.create_logout_url(redirect))
100uhaco
trunk/GAE/common/appenginepatch/ragendja/templatetags/googletags.py
Python
asf20
588
from django.contrib.auth.models import * from django.contrib.auth.models import DjangoCompatibleUser as User
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/models.py
Python
asf20
109
# -*- coding: utf-8 -*- """ Provides basic set of auth urls. """ from django.conf.urls.defaults import * from django.conf import settings urlpatterns = patterns('') LOGIN = '^%s$' % settings.LOGIN_URL.lstrip('/') LOGOUT = '^%s$' % settings.LOGOUT_URL.lstrip('/') # If user set a LOGOUT_REDIRECT_URL we do a redirect. # Otherwise we display the default template. LOGOUT_DATA = {'next_page': getattr(settings, 'LOGOUT_REDIRECT_URL', None)} # register auth urls depending on whether we use google or hybrid auth if 'ragendja.auth.middleware.GoogleAuthenticationMiddleware' in \ settings.MIDDLEWARE_CLASSES: urlpatterns += patterns('', url(LOGIN, 'ragendja.auth.views.google_login', name='django.contrib.auth.views.login'), url(LOGOUT, 'ragendja.auth.views.google_logout', LOGOUT_DATA, name='django.contrib.auth.views.logout'), ) elif 'ragendja.auth.middleware.HybridAuthenticationMiddleware' in \ settings.MIDDLEWARE_CLASSES: urlpatterns += patterns('', url(LOGIN, 'ragendja.auth.views.hybrid_login', name='django.contrib.auth.views.login'), url(LOGOUT, 'ragendja.auth.views.hybrid_logout', LOGOUT_DATA, name='django.contrib.auth.views.logout'), ) # When faking a real function we always have to add the real function, too. urlpatterns += patterns('', url(LOGIN, 'django.contrib.auth.views.login'), url(LOGOUT, 'django.contrib.auth.views.logout', LOGOUT_DATA,), )
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/urls.py
Python
asf20
1,486
# -*- coding: utf-8 -*- from google.appengine.api import users def google_user(request): return {'google_user': users.get_current_user()}
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/context_processors.py
Python
asf20
143
from django.utils.translation import ugettext_lazy as _ from django.conf import settings from google.appengine.api import users from google.appengine.ext import db from ragendja.auth.models import EmailUserTraits class GoogleUserTraits(EmailUserTraits): @classmethod def get_djangouser_for_user(cls, user): django_user = cls.all().filter('user =', user).get() if django_user: if getattr(settings, 'AUTH_ADMIN_USER_AS_SUPERUSER', True): is_admin = users.is_current_user_admin() if django_user.is_staff != is_admin or \ django_user.is_superuser != is_admin: django_user.is_superuser = django_user.is_staff = is_admin django_user.put() else: django_user = cls.create_djangouser_for_user(user) django_user.is_active = True if getattr(settings, 'AUTH_ADMIN_USER_AS_SUPERUSER', True) and \ users.is_current_user_admin(): django_user.is_staff = True django_user.is_superuser = True django_user.put() return django_user class Meta: abstract = True class User(GoogleUserTraits): """Extended User class that provides support for Google Accounts.""" user = db.UserProperty(required=True) class Meta: verbose_name = _('user') verbose_name_plural = _('users') @property def username(self): return self.user.nickname() @property def email(self): return self.user.email() @classmethod def create_djangouser_for_user(cls, user): return cls(user=user)
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/google_models.py
Python
asf20
1,678
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from functools import wraps from ragendja.auth.views import google_redirect_to_login from ragendja.template import render_to_response def staff_only(view): """ Decorator that requires user.is_staff. Otherwise renders no_access.html. """ @login_required def wrapped(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: return view(request, *args, **kwargs) return render_to_response(request, 'no_access.html') return wraps(view)(wrapped) def google_login_required(function): def login_required_wrapper(request, *args, **kw): if request.user.is_authenticated(): return function(request, *args, **kw) return google_redirect_to_login(request.get_full_path()) return wraps(function)(login_required_wrapper)
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/decorators.py
Python
asf20
901
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import login, logout from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from google.appengine.api import users from ragendja.template import render_to_response def get_redirect_to(request, redirect_field_name): redirect_to = request.REQUEST.get(redirect_field_name) # Light security check -- make sure redirect_to isn't garbage. if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL return redirect_to def google_login(request, template_name=None, redirect_field_name=REDIRECT_FIELD_NAME): redirect_to = get_redirect_to(request, redirect_field_name) return HttpResponseRedirect(users.create_login_url(redirect_to)) def hybrid_login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME): # Don't login using both authentication systems at the same time if request.user.is_authenticated(): redirect_to = get_redirect_to(request, redirect_field_name) return HttpResponseRedirect(redirect_to) return login(request, template_name, redirect_field_name) def google_logout(request, next_page=None, template_name='registration/logged_out.html'): if users.get_current_user(): # Redirect to this page until the session has been cleared. logout_url = users.create_logout_url(next_page or request.path) return HttpResponseRedirect(logout_url) if not next_page: return render_to_response(request, template_name, {'title': _('Logged out')}) return HttpResponseRedirect(next_page) def hybrid_logout(request, next_page=None, template_name='registration/logged_out.html'): if users.get_current_user(): return google_logout(request, next_page) return logout(request, next_page, template_name) def google_logout_then_login(request, login_url=None): if not login_url: login_url = settings.LOGIN_URL return google_logout(request, login_url) def hybrid_logout_then_login(request, login_url=None): if not login_url: login_url = settings.LOGIN_URL return hybrid_logout(request, login_url) def google_redirect_to_login(next, login_url=None, redirect_field_name=None): return HttpResponseRedirect(users.create_login_url(next))
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/views.py
Python
asf20
2,483
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ class UserAdmin(admin.ModelAdmin): fieldsets = ( (_('Personal info'), {'fields': ('user',)}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}), (_('Important dates'), {'fields': ('date_joined',)}), (_('Groups'), {'fields': ('groups',)}), ) list_display = ('email', 'username', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active') search_fields = ('user',) filter_horizontal = ('user_permissions',)
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/google_admin.py
Python
asf20
604
# Parts of this code are taken from Google's django-helper (license: Apache 2) class LazyGoogleUser(object): def __init__(self, middleware_class): self._middleware_class = middleware_class def __get__(self, request, obj_type=None): if not hasattr(request, '_cached_user'): from django.contrib.auth import get_user from django.contrib.auth.models import AnonymousUser, User from google.appengine.api import users if self._middleware_class is HybridAuthenticationMiddleware: request._cached_user = get_user(request) else: request._cached_user = AnonymousUser() if request._cached_user.is_anonymous(): user = users.get_current_user() if user: request._cached_user = User.get_djangouser_for_user(user) return request._cached_user class GoogleAuthenticationMiddleware(object): def process_request(self, request): request.__class__.user = LazyGoogleUser(self.__class__) class HybridAuthenticationMiddleware(GoogleAuthenticationMiddleware): pass
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/middleware.py
Python
asf20
1,147
from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db from ragendja.auth.google_models import GoogleUserTraits class User(GoogleUserTraits): """User class that provides support for Django and Google Accounts.""" user = db.UserProperty() username = db.StringProperty(required=True, verbose_name=_('username')) email = db.EmailProperty(verbose_name=_('e-mail address')) first_name = db.StringProperty(verbose_name=_('first name')) last_name = db.StringProperty(verbose_name=_('last name')) class Meta: verbose_name = _('user') verbose_name_plural = _('users') @classmethod def create_djangouser_for_user(cls, user): return cls(user=user, email=user.email(), username=user.email())
100uhaco
trunk/GAE/common/appenginepatch/ragendja/auth/hybrid_models.py
Python
asf20
780
# -*- coding: utf-8 -*- """ This is a set of utilities for faster development with Django templates. render_to_response() and render_to_string() use RequestContext internally. The app_prefixed_loader is a template loader that loads directly from the app's 'templates' folder when you specify an app prefix ('app/template.html'). The JSONResponse() function automatically converts a given Python object into JSON and returns it as an HttpResponse. """ from django.conf import settings from django.http import HttpResponse from django.template import RequestContext, loader, \ TemplateDoesNotExist, Library, Node, Variable, generic_tag_compiler from django.utils.functional import curry from inspect import getargspec from ragendja.apputils import get_app_dirs import os class Library(Library): def context_tag(self, func): params, xx, xxx, defaults = getargspec(func) class ContextNode(Node): def __init__(self, vars_to_resolve): self.vars_to_resolve = map(Variable, vars_to_resolve) def render(self, context): resolved_vars = [var.resolve(context) for var in self.vars_to_resolve] return func(context, *resolved_vars) params = params[1:] compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, ContextNode) compile_func.__doc__ = func.__doc__ self.tag(getattr(func, "_decorated_function", func).__name__, compile_func) return func # The following defines a template loader that loads templates from a specific # app based on the prefix of the template path: # get_template("app/template.html") => app/templates/template.html # This keeps the code DRY and prevents name clashes. def app_prefixed_loader(template_name, template_dirs=None): packed = template_name.split('/', 1) if len(packed) == 2 and packed[0] in app_template_dirs: path = os.path.join(app_template_dirs[packed[0]], packed[1]) try: return (open(path).read().decode(settings.FILE_CHARSET), path) except IOError: pass raise TemplateDoesNotExist, template_name app_prefixed_loader.is_usable = True def render_to_string(request, template_name, data=None): return loader.render_to_string(template_name, data, context_instance=RequestContext(request)) def render_to_response(request, template_name, data=None, mimetype=None): if mimetype is None: mimetype = settings.DEFAULT_CONTENT_TYPE original_mimetype = mimetype if mimetype == 'application/xhtml+xml': # Internet Explorer only understands XHTML if it's served as text/html if request.META.get('HTTP_ACCEPT').find(mimetype) == -1: mimetype = 'text/html' response = HttpResponse(render_to_string(request, template_name, data), content_type='%s; charset=%s' % (mimetype, settings.DEFAULT_CHARSET)) if original_mimetype == 'application/xhtml+xml': # Since XHTML is served with two different MIME types, depending on the # browser, we need to tell proxies to serve different versions. from django.utils.cache import patch_vary_headers patch_vary_headers(response, ['User-Agent']) return response def JSONResponse(pyobj): from ragendja.json import JSONResponse as real_class global JSONResponse JSONResponse = real_class return JSONResponse(pyobj) def TextResponse(string=''): return HttpResponse(string, content_type='text/plain; charset=%s' % settings.DEFAULT_CHARSET) # This is needed by app_prefixed_loader. app_template_dirs = get_app_dirs('templates')
100uhaco
trunk/GAE/common/appenginepatch/ragendja/template.py
Python
asf20
3,680
# -*- coding: utf-8 -*- from django.conf import settings from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse from django.utils import simplejson from django.utils.encoding import force_unicode from django.utils.functional import Promise class LazyEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj) class JSONResponse(HttpResponse): def __init__(self, pyobj, **kwargs): super(JSONResponse, self).__init__( simplejson.dumps(pyobj, cls=LazyEncoder), content_type='application/json; charset=%s' % settings.DEFAULT_CHARSET, **kwargs)
100uhaco
trunk/GAE/common/appenginepatch/ragendja/json.py
Python
asf20
784
# -*- coding: utf-8 -*- from django.http import HttpRequest class RegisterVars(dict): """ This class provides a simplified mechanism to build context processors that only add variables or functions without processing a request. Your module should have a global instance of this class called 'register'. You can then add the 'register' variable as a context processor in your settings.py. How to use: >>> register = RegisterVars() >>> def func(): ... pass >>> register(func) # doctest:+ELLIPSIS <function func at ...> >>> @register ... def otherfunc(): ... pass >>> register['otherfunc'] is otherfunc True Alternatively you can specify the name of the function with either of: def func(...): ... register(func, 'new_name') @register('new_name') def ... You can even pass a dict or RegisterVars instance: register(othermodule.register) register({'myvar': myvar}) """ def __call__(self, item=None, name=None): # Allow for using a RegisterVars instance as a context processor if isinstance(item, HttpRequest): return self if name is None and isinstance(item, basestring): # @register('as_name') # first param (item) contains the name name, item = item, name elif name is None and isinstance(item, dict): # register(somedict) or register(othermodule.register) return self.update(item) if item is None and isinstance(name, basestring): # @register(name='as_name') return lambda func: self(func, name) self[name or item.__name__] = item return item
100uhaco
trunk/GAE/common/appenginepatch/ragendja/registervars.py
Python
asf20
1,731
# -*- coding: utf-8 -*- from appenginepatcher import on_production_server, have_appserver import os DEBUG = not on_production_server # The MEDIA_VERSION will get integrated via %d MEDIA_URL = '/media/%d/' # The MEDIA_URL will get integrated via %s ADMIN_MEDIA_PREFIX = '%sadmin_media/' ADMINS = () DATABASE_ENGINE = 'appengine' DATABASE_SUPPORTS_TRANSACTIONS = False # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = 'user' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'user@localhost' SERVER_EMAIL = 'user@localhost' LOGIN_REQUIRED_PREFIXES = () NO_LOGIN_REQUIRED_PREFIXES = () ROOT_URLCONF = 'urls' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'ragendja.template.app_prefixed_loader', 'django.template.loaders.app_directories.load_template_source', ) PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname( os.path.dirname(__file__)))) COMMON_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) MAIN_DIRS = (PROJECT_DIR, COMMON_DIR) TEMPLATE_DIRS = tuple([os.path.join(dir, 'templates') for dir in MAIN_DIRS]) LOCALE_PATHS = ( os.path.join(PROJECT_DIR, 'media', 'locale'), ) + tuple([os.path.join(dir, 'locale') for dir in TEMPLATE_DIRS]) FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', ) CACHE_BACKEND = 'memcached://?timeout=0' COMBINE_MEDIA = {} if not on_production_server: INTERNAL_IPS = ('127.0.0.1',) IGNORE_APP_SETTINGS = ()
100uhaco
trunk/GAE/common/appenginepatch/ragendja/settings_pre.py
Python
asf20
1,646
from django.conf import settings from django.http import HttpResponseServerError from ragendja.template import render_to_string def server_error(request, *args, **kwargs): debugkey = request.REQUEST.get('debugkey') if debugkey and debugkey == getattr(settings, 'DEBUGKEY', None): import sys from django.views import debug return debug.technical_500_response(request, *sys.exc_info()) return HttpResponseServerError(render_to_string(request, '500.html')) def maintenance(request, *args, **kwargs): return HttpResponseServerError(render_to_string(request, 'maintenance.html'))
100uhaco
trunk/GAE/common/appenginepatch/ragendja/views.py
Python
asf20
625