Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4599dcd988 | ||
|
|
14bdfd3321 | ||
|
|
e7d14c028b | ||
|
|
0207a17afa | ||
|
|
73b049f361 | ||
|
|
5695fe34f0 | ||
|
|
f2e44f96d6 | ||
|
|
2ccc707059 | ||
|
|
30490a0c5c | ||
|
|
4c1102026d | ||
|
|
63b589170c | ||
|
|
2b0d098027 | ||
|
|
fcfaa63f33 | ||
|
|
f497aa7fcf | ||
|
|
d91f7381e1 | ||
|
|
bad0af15f6 | ||
|
|
d7cc15c85d | ||
|
|
1f1e65dcb5 | ||
|
|
930d4dcdd0 | ||
|
|
b640820052 | ||
|
|
be0003927a | ||
|
|
0015a265a9 | ||
|
|
12ff451f4b | ||
|
|
63cefe0862 | ||
|
|
bf3a24e515 | ||
|
|
4378a8a792 | ||
|
|
1532cecb25 | ||
|
|
22af4db51d | ||
|
|
523cb34119 | ||
|
|
24b037c307 | ||
|
|
bd933ca43d | ||
|
|
676b2ef54b | ||
|
|
353a66f44c | ||
|
|
689dfcd83e | ||
|
|
8f7b82fdb3 | ||
|
|
c574a97cad | ||
|
|
5e7de996e0 | ||
|
|
52ba4bb0ea | ||
|
|
c43aa3545f | ||
|
|
8e48a816f8 | ||
|
|
afef829571 | ||
|
|
f4e5de995c | ||
|
|
70a4e06f18 | ||
|
|
f241c008d4 | ||
|
|
9920b7592d | ||
|
|
fee2c667b3 | ||
|
|
ebc9d98a87 | ||
|
|
06f5a32c48 | ||
|
|
35cb9ee529 | ||
|
|
f0e59ca617 | ||
|
|
1bbfd80c24 | ||
|
|
a9600faa9f | ||
|
|
6f39f96799 | ||
|
|
b06df4740b | ||
|
|
d354e4f767 | ||
|
|
caef44d4f9 | ||
|
|
f9eb2c5a0a | ||
|
|
3a05be49f6 | ||
|
|
b92e169b69 | ||
|
|
882f42de8f | ||
|
|
c8e64ac4f7 | ||
|
|
da1751dc1b | ||
|
|
304ae277fe | ||
|
|
0e93162080 | ||
|
|
6ced9dd235 | ||
|
|
e2da57f448 | ||
|
|
d0047e6e5b | ||
|
|
90955bdcab | ||
|
|
d2b4099cdb | ||
|
|
1e7315d4a8 | ||
|
|
d7ace92c04 | ||
|
|
568c33d7d6 | ||
|
|
ef8f10c42d | ||
|
|
fc7c4432e9 | ||
|
|
04a7d9a92d | ||
|
|
b83673f1c8 | ||
|
|
ba21ce887a | ||
|
|
5764482acd | ||
|
|
1b0e08cfa0 | ||
|
|
e59cb43b0b | ||
|
|
2cbca7a43d | ||
|
|
d2dd3d0ac6 | ||
|
|
6324ed7a9c | ||
|
|
23595c0608 | ||
|
|
eebc3418f9 | ||
|
|
867caae3da | ||
|
|
d0098a878a | ||
|
|
ee7db631ee | ||
|
|
b388f41f80 | ||
|
|
9f5391bbc0 | ||
|
|
22ca52a1cb | ||
|
|
b56cfb372d | ||
|
|
c8367e257f | ||
|
|
62d37702a9 | ||
|
|
74fc2a2d85 | ||
|
|
0ac1298501 | ||
|
|
faf76ac715 | ||
|
|
3ece96ae08 | ||
|
|
e91cf7f6ac | ||
|
|
019d3e07b5 | ||
|
|
e3046845bf | ||
|
|
b8f52ed76a | ||
|
|
662abd29cb | ||
|
|
3560337b40 | ||
|
|
c7985e8881 | ||
|
|
a69bc44314 | ||
|
|
651c92c175 | ||
|
|
7319574f30 | ||
|
|
b9821f1c21 | ||
|
|
52ca6af024 | ||
|
|
cc4d27c6d2 | ||
|
|
b687977663 | ||
|
|
3e85f5bf39 | ||
|
|
23165d9382 | ||
|
|
1abc31895e | ||
|
|
6fc70fbc55 | ||
|
|
bf86becc5e | ||
|
|
510142ad2d | ||
|
|
6eb361d8f7 | ||
|
|
e56f588dea | ||
|
|
0ee551de71 | ||
|
|
7dc40f68db | ||
|
|
adb0c08933 | ||
|
|
2fea9495b3 | ||
|
|
1f767c3497 | ||
|
|
09bae08dfa | ||
|
|
8a137691ff | ||
|
|
7de90f18cc | ||
|
|
859636e6e0 | ||
|
|
a511682ce1 | ||
|
|
6a81420fc0 | ||
|
|
fa019e8960 | ||
|
|
b17358e761 | ||
|
|
c9b41a4343 | ||
|
|
8affdbdc86 | ||
|
|
a61e388498 | ||
|
|
d72752f453 | ||
|
|
d67af48f29 | ||
|
|
b18a2a7aa3 | ||
|
|
693dce0e6c | ||
|
|
e1cd36771e | ||
|
|
12107da9bd | ||
|
|
96eee74f56 | ||
|
|
2f881085ef | ||
|
|
7b2afa109e | ||
|
|
8dae3f832d | ||
|
|
c61e0e11bb | ||
|
|
04caa5f4e4 | ||
|
|
6a13c33c70 | ||
|
|
4357edb1d4 | ||
|
|
9d7e009c0f | ||
|
|
7549f77edc | ||
|
|
5ee2ab9b6b | ||
|
|
54b98b4e05 | ||
|
|
6e0e48e150 | ||
|
|
fe5a1c6a8d | ||
|
|
8332106754 | ||
|
|
aa149d2e7b | ||
|
|
a5f883c2f0 | ||
|
|
5953377060 | ||
|
|
5a478302f4 | ||
|
|
1621825166 | ||
|
|
6af2e859ac | ||
|
|
fb22a8843e | ||
|
|
529dda0e6d | ||
|
|
35c893d47a | ||
|
|
99e2397981 | ||
|
|
b6d68f97d6 | ||
|
|
74024301a5 | ||
|
|
1f100bbe88 | ||
|
|
c94c192e17 | ||
|
|
0d9e5985e4 | ||
|
|
b31bfdaaf5 | ||
|
|
5f67edbf87 | ||
|
|
093e8b356e | ||
|
|
43d4c2831d | ||
|
|
55a0dbeb86 | ||
|
|
2f1f2dccc1 | ||
|
|
a4cef60c49 | ||
|
|
96ee377279 | ||
|
|
4152c72de5 | ||
|
|
ab066397b2 | ||
|
|
8c514df120 | ||
|
|
0eab35842d | ||
|
|
752bb7e048 | ||
|
|
9e897dcc46 | ||
|
|
2bb3485827 | ||
|
|
0be4abe9c2 | ||
|
|
37bc09169f | ||
|
|
1cc2decfdd | ||
|
|
e9eb1689e2 | ||
|
|
0f446833c0 | ||
|
|
cb9c2a8ef9 | ||
|
|
b37ed1c1e0 | ||
|
|
b484955005 | ||
|
|
654626d519 | ||
|
|
ca0313c514 | ||
|
|
fb357eb241 | ||
|
|
1a83487221 | ||
|
|
6cda7a29fc | ||
|
|
17f495e9c5 | ||
|
|
dd32a90844 | ||
|
|
4b2ba185ae | ||
|
|
b716df1a05 | ||
|
|
d552eb2eeb | ||
|
|
de2337dfe3 | ||
|
|
e707cfc67c | ||
|
|
c3c5df6394 | ||
|
|
72739ebb97 | ||
|
|
39c94b8dcf | ||
|
|
5af380223a | ||
|
|
1ea379180a | ||
|
|
ca3d050a0b | ||
|
|
161b2271b3 | ||
|
|
013c94cdf6 | ||
|
|
addbb78151 | ||
|
|
f6789eaf39 | ||
|
|
c13b4f18f7 | ||
|
|
67840e9481 | ||
|
|
41c40974a3 | ||
|
|
9a6ce11f09 | ||
|
|
d404e40508 | ||
|
|
b6a496aae5 | ||
|
|
ecaed07a3d | ||
|
|
30ec8e645b | ||
|
|
3a1ba53a4b | ||
|
|
ab95dfa7cd | ||
|
|
6b9ebb6dc5 | ||
|
|
e2e843d2ed | ||
|
|
d5381d7b36 | ||
|
|
f7c0f0341b | ||
|
|
9f7fd68728 |
@@ -1,3 +1,40 @@
|
|||||||
|
## 2.3.1 - 2.3.2
|
||||||
|
|
||||||
|
- new virtual fields syntax:
|
||||||
|
``db.define_table('person',Field('name'),Field.Virtual('namey',lambda row: row.person.name+'y'))``
|
||||||
|
- db.thing(name='Cohen',_orderby=db.thing.name), thanks Yair
|
||||||
|
- made many modules Python 3.3 friendly (compile but not tested)
|
||||||
|
- better welcome css, thanks Paolo
|
||||||
|
- jQuery 1.8.3
|
||||||
|
- Bootstrap 2.2.2
|
||||||
|
- Modernizr 2.6.2 (custom full options)
|
||||||
|
- integration with analyitics.js (0.2.0)
|
||||||
|
- better scheduler, thanks Niphlod
|
||||||
|
- page and media preview in wiki, thanks Niphlod
|
||||||
|
- create new auth.wiki page from slug model, thanks Nico
|
||||||
|
- conditional menus with auth.wiki(menugroups=['wiki_editor'])
|
||||||
|
- better security in grid/smartgrid
|
||||||
|
- allow LOADing multiple grids, thanks Niphlod
|
||||||
|
- auth.settings.login_onfail, thanks Yair
|
||||||
|
- better handling of session files for speed
|
||||||
|
- added heroku support (experimental)
|
||||||
|
- added rocket support for IPV6, thanks Chirs Winebrinner
|
||||||
|
- more customizable menus with MENU(li_first, li_last..)
|
||||||
|
- added support for paymentech (gluon/contrib/paymentech.py)
|
||||||
|
- fixed broken cron
|
||||||
|
- fixed possible xss with share.js
|
||||||
|
- many bug fixes. Closed more than 50 tickets since 2.2.1
|
||||||
|
|
||||||
|
## 2.2.1
|
||||||
|
|
||||||
|
- session.connect(cookie_key='secret', compression_level=9) stores sessions in cookies
|
||||||
|
- T.is_writable = False prevents T from dynamically updating langauge files
|
||||||
|
- all code is more PEP8 compliant
|
||||||
|
- better custom_importer behaviour (now works per app, is smalled and faster)
|
||||||
|
- fixed some bugs
|
||||||
|
- upgraded feedparser.py and rss2.py
|
||||||
|
- codemirror has autoresize
|
||||||
|
|
||||||
## 2.1.0
|
## 2.1.0
|
||||||
|
|
||||||
- overall faster web2py
|
- overall faster web2py
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ update:
|
|||||||
wget -O gluon/contrib/simplejsonrpc.py http://rad2py.googlecode.com/hg/ide2py/simplejsonrpc.py
|
wget -O gluon/contrib/simplejsonrpc.py http://rad2py.googlecode.com/hg/ide2py/simplejsonrpc.py
|
||||||
echo "remember that pymysql was tweaked"
|
echo "remember that pymysql was tweaked"
|
||||||
src:
|
src:
|
||||||
echo 'Version 2.1.1 ('`date +%Y-%m-%d\ %H:%M:%S`') stable' > VERSION
|
echo 'Version 2.3.2 ('`date +%Y-%m-%d\ %H:%M:%S`') stable' > VERSION
|
||||||
### rm -f all junk files
|
### rm -f all junk files
|
||||||
make clean
|
make clean
|
||||||
### clean up baisc apps
|
### clean up baisc apps
|
||||||
@@ -43,6 +43,8 @@ src:
|
|||||||
rm -f applications/admin/uploads/*
|
rm -f applications/admin/uploads/*
|
||||||
rm -f applications/welcome/uploads/*
|
rm -f applications/welcome/uploads/*
|
||||||
rm -f applications/examples/uploads/*
|
rm -f applications/examples/uploads/*
|
||||||
|
### make epydoc
|
||||||
|
make epydoc
|
||||||
### make welcome layout and appadmin the default
|
### make welcome layout and appadmin the default
|
||||||
cp applications/welcome/views/appadmin.html applications/admin/views
|
cp applications/welcome/views/appadmin.html applications/admin/views
|
||||||
cp applications/welcome/views/appadmin.html applications/examples/views
|
cp applications/welcome/views/appadmin.html applications/examples/views
|
||||||
@@ -54,7 +56,6 @@ src:
|
|||||||
cd ..; zip -r web2py/web2py_src.zip web2py/gluon/*.py web2py/gluon/contrib/* web2py/splashlogo.gif web2py/*.py web2py/README.markdown web2py/LICENSE web2py/CHANGELOG web2py/NEWINSTALL web2py/VERSION web2py/Makefile web2py/epydoc.css web2py/epydoc.conf web2py/app.example.yaml web2py/logging.example.conf web2py_exe.conf web2py/queue.example.yaml MANIFEST.in w2p_apps w2p_clone w2p_run startweb2py web2py/scripts/*.sh web2py/scripts/*.py web2py/applications/admin web2py/applications/examples/ web2py/applications/welcome web2py/applications/__init__.py web2py/site-packages/__init__.py web2py/gluon/tests/*.sh web2py/gluon/tests/*.py
|
cd ..; zip -r web2py/web2py_src.zip web2py/gluon/*.py web2py/gluon/contrib/* web2py/splashlogo.gif web2py/*.py web2py/README.markdown web2py/LICENSE web2py/CHANGELOG web2py/NEWINSTALL web2py/VERSION web2py/Makefile web2py/epydoc.css web2py/epydoc.conf web2py/app.example.yaml web2py/logging.example.conf web2py_exe.conf web2py/queue.example.yaml MANIFEST.in w2p_apps w2p_clone w2p_run startweb2py web2py/scripts/*.sh web2py/scripts/*.py web2py/applications/admin web2py/applications/examples/ web2py/applications/welcome web2py/applications/__init__.py web2py/site-packages/__init__.py web2py/gluon/tests/*.sh web2py/gluon/tests/*.py
|
||||||
|
|
||||||
mdp:
|
mdp:
|
||||||
make epydoc
|
|
||||||
make src
|
make src
|
||||||
make app
|
make app
|
||||||
make win
|
make win
|
||||||
@@ -130,5 +131,5 @@ pip:
|
|||||||
# after upload clean Web2py sources with rm -R ./dist
|
# after upload clean Web2py sources with rm -R ./dist
|
||||||
# http://guide.python-distribute.org/creation.html
|
# http://guide.python-distribute.org/creation.html
|
||||||
python setup.py sdist
|
python setup.py sdist
|
||||||
python setup.py register
|
sudo python setup.py register
|
||||||
python setup.py sdist upload
|
sudo python setup.py sdist upload
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -1 +1 @@
|
|||||||
Version 2.1.1 (2012-10-15 06:40:52) stable
|
Version 2.3.2 (2012-12-17 08:59:58) stable
|
||||||
|
|||||||
-10
@@ -1,10 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+41
-22
@@ -9,13 +9,18 @@ License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
|
|||||||
This file is based, although a rewrite, on MIT-licensed code from the Bottle web framework.
|
This file is based, although a rewrite, on MIT-licensed code from the Bottle web framework.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os, sys, optparse, urllib
|
import os
|
||||||
|
import sys
|
||||||
|
import optparse
|
||||||
|
import urllib
|
||||||
|
|
||||||
path = os.path.dirname(os.path.abspath(__file__))
|
path = os.path.dirname(os.path.abspath(__file__))
|
||||||
os.chdir(path)
|
os.chdir(path)
|
||||||
sys.path = [path] + [p for p in sys.path if not p == path]
|
sys.path = [path] + [p for p in sys.path if not p == path]
|
||||||
import gluon.main
|
import gluon.main
|
||||||
from gluon.fileutils import read_file, write_file
|
from gluon.fileutils import read_file, write_file
|
||||||
|
|
||||||
|
|
||||||
class Servers:
|
class Servers:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def cgi(app, address=None, **options):
|
def cgi(app, address=None, **options):
|
||||||
@@ -30,8 +35,10 @@ class Servers:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def wsgiref(app, address, **options): # pragma: no cover
|
def wsgiref(app, address, **options): # pragma: no cover
|
||||||
from wsgiref.simple_server import make_server, WSGIRequestHandler
|
from wsgiref.simple_server import make_server, WSGIRequestHandler
|
||||||
|
|
||||||
class QuietHandler(WSGIRequestHandler):
|
class QuietHandler(WSGIRequestHandler):
|
||||||
def log_request(*args, **kw): pass
|
def log_request(*args, **kw):
|
||||||
|
pass
|
||||||
options['handler_class'] = QuietHandler
|
options['handler_class'] = QuietHandler
|
||||||
srv = make_server(address[0], address[1], app, **options)
|
srv = make_server(address[0], address[1], app, **options)
|
||||||
srv.serve_forever()
|
srv.serve_forever()
|
||||||
@@ -76,19 +83,21 @@ class Servers:
|
|||||||
from fapws import base
|
from fapws import base
|
||||||
evwsgi.start(address[0], str(address[1]))
|
evwsgi.start(address[0], str(address[1]))
|
||||||
evwsgi.set_base_module(base)
|
evwsgi.set_base_module(base)
|
||||||
|
|
||||||
def app(environ, start_response):
|
def app(environ, start_response):
|
||||||
environ['wsgi.multiprocess'] = False
|
environ['wsgi.multiprocess'] = False
|
||||||
return app(environ, start_response)
|
return app(environ, start_response)
|
||||||
evwsgi.wsgi_cb(('', app))
|
evwsgi.wsgi_cb(('', app))
|
||||||
evwsgi.run()
|
evwsgi.run()
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def gevent(app, address, **options):
|
def gevent(app, address, **options):
|
||||||
from gevent import monkey; monkey.patch_all()
|
from gevent import monkey
|
||||||
|
monkey.patch_all()
|
||||||
from gevent import pywsgi
|
from gevent import pywsgi
|
||||||
from gevent.pool import Pool
|
from gevent.pool import Pool
|
||||||
pywsgi.WSGIServer(address, app, spawn = 'workers' in options and Pool(int(options.workers)) or 'default').serve_forever()
|
pywsgi.WSGIServer(address, app, spawn='workers' in options and Pool(
|
||||||
|
int(options.workers)) or 'default').serve_forever()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def bjoern(app, address, **options):
|
def bjoern(app, address, **options):
|
||||||
@@ -129,9 +138,11 @@ class Servers:
|
|||||||
config = {'bind': "%s:%d" % address}
|
config = {'bind': "%s:%d" % address}
|
||||||
config.update(options)
|
config.update(options)
|
||||||
sys.argv = ['anyserver.py']
|
sys.argv = ['anyserver.py']
|
||||||
|
|
||||||
class GunicornApplication(Application):
|
class GunicornApplication(Application):
|
||||||
def init(self, parser, opts, args):
|
def init(self, parser, opts, args):
|
||||||
return config
|
return config
|
||||||
|
|
||||||
def load(self):
|
def load(self):
|
||||||
return app
|
return app
|
||||||
g = GunicornApplication()
|
g = GunicornApplication()
|
||||||
@@ -165,6 +176,7 @@ def run(servername,ip,port,softcron=True,logging=False,profiler=None):
|
|||||||
global_settings.web2py_crontype = 'soft'
|
global_settings.web2py_crontype = 'soft'
|
||||||
getattr(Servers, servername)(application, (ip, int(port)))
|
getattr(Servers, servername)(application, (ip, int(port)))
|
||||||
|
|
||||||
|
|
||||||
def mongrel2_handler(application, conn, debug=False):
|
def mongrel2_handler(application, conn, debug=False):
|
||||||
"""
|
"""
|
||||||
Based on :
|
Based on :
|
||||||
@@ -190,14 +202,17 @@ def mongrel2_handler(application,conn,debug=False):
|
|||||||
# and responses. Unless I have missed something.
|
# and responses. Unless I have missed something.
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
if debug: print "WAITING FOR REQUEST"
|
if debug:
|
||||||
|
print "WAITING FOR REQUEST"
|
||||||
|
|
||||||
# receive a request
|
# receive a request
|
||||||
req = conn.recv()
|
req = conn.recv()
|
||||||
if debug: print "REQUEST BODY: %r\n" % req.body
|
if debug:
|
||||||
|
print "REQUEST BODY: %r\n" % req.body
|
||||||
|
|
||||||
if req.is_disconnect():
|
if req.is_disconnect():
|
||||||
if debug: print "DISCONNECT"
|
if debug:
|
||||||
|
print "DISCONNECT"
|
||||||
continue # effectively ignore the disconnect from the client
|
continue # effectively ignore the disconnect from the client
|
||||||
|
|
||||||
# Set a couple of environment attributes a.k.a. header attributes
|
# Set a couple of environment attributes a.k.a. header attributes
|
||||||
@@ -217,11 +232,13 @@ def mongrel2_handler(application,conn,debug=False):
|
|||||||
environ['QUERY_STRING'] = environ['URI'].split('?')[1]
|
environ['QUERY_STRING'] = environ['URI'].split('?')[1]
|
||||||
else:
|
else:
|
||||||
environ['QUERY_STRING'] = ''
|
environ['QUERY_STRING'] = ''
|
||||||
if environ.has_key('Content-Length'):
|
if 'Content-Length' in environ:
|
||||||
environ['CONTENT_LENGTH'] = environ['Content-Length'] # necessary for POST to work with Django
|
environ['CONTENT_LENGTH'] = environ[
|
||||||
|
'Content-Length'] # necessary for POST to work with Django
|
||||||
environ['wsgi.input'] = req.body
|
environ['wsgi.input'] = req.body
|
||||||
|
|
||||||
if debug: print "ENVIRON: %r\n" % environ
|
if debug:
|
||||||
|
print "ENVIRON: %r\n" % environ
|
||||||
|
|
||||||
# SimpleHandler needs file-like stream objects for
|
# SimpleHandler needs file-like stream objects for
|
||||||
# requests, errors and responses
|
# requests, errors and responses
|
||||||
@@ -230,7 +247,8 @@ def mongrel2_handler(application,conn,debug=False):
|
|||||||
respIO = StringIO.StringIO()
|
respIO = StringIO.StringIO()
|
||||||
|
|
||||||
# execute the application
|
# execute the application
|
||||||
handler = SimpleHandler(reqIO, respIO, errIO, environ, multithread = False, multiprocess = False)
|
handler = SimpleHandler(reqIO, respIO, errIO, environ,
|
||||||
|
multithread=False, multiprocess=False)
|
||||||
handler.run(application)
|
handler.run(application)
|
||||||
|
|
||||||
# Get the response and filter out the response (=data) itself,
|
# Get the response and filter out the response (=data) itself,
|
||||||
@@ -254,11 +272,15 @@ def mongrel2_handler(application,conn,debug=False):
|
|||||||
errors = errIO.getvalue()
|
errors = errIO.getvalue()
|
||||||
|
|
||||||
# return the response
|
# return the response
|
||||||
if debug: print "RESPONSE: %r\n" % response
|
if debug:
|
||||||
|
print "RESPONSE: %r\n" % response
|
||||||
if errors:
|
if errors:
|
||||||
if debug: print "ERRORS: %r" % errors
|
if debug:
|
||||||
|
print "ERRORS: %r" % errors
|
||||||
data = "%s\r\n\r\n%s" % (data, errors)
|
data = "%s\r\n\r\n%s" % (data, errors)
|
||||||
conn.reply_http(req, data, code = code, status = status, headers = headers)
|
conn.reply_http(
|
||||||
|
req, data, code=code, status=status, headers=headers)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
usage = "python anyserver.py -s tornado -i 127.0.0.1 -p 8000 -l -P"
|
usage = "python anyserver.py -s tornado -i 127.0.0.1 -p 8000 -l -P"
|
||||||
@@ -300,13 +322,10 @@ def main():
|
|||||||
dest='workers',
|
dest='workers',
|
||||||
help='number of workers number')
|
help='number of workers number')
|
||||||
(options, args) = parser.parse_args()
|
(options, args) = parser.parse_args()
|
||||||
print 'starting %s on %s:%s...' % (options.server,options.ip,options.port)
|
print 'starting %s on %s:%s...' % (
|
||||||
run(options.server,options.ip,options.port,logging=options.logging,profiler=options.profiler)
|
options.server, options.ip, options.port)
|
||||||
|
run(options.server, options.ip, options.port,
|
||||||
|
logging=options.logging, profiler=options.profiler)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,3 @@ def webapp_add_wsgi_middleware(app):
|
|||||||
from google.appengine.ext.appstats import recording
|
from google.appengine.ext.appstats import recording
|
||||||
app = recording.appstats_wsgi_middleware(app)
|
app = recording.appstats_wsgi_middleware(app)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
@@ -102,17 +102,16 @@ def query_by_table_type(tablename,db,request=request):
|
|||||||
cond = '>0'
|
cond = '>0'
|
||||||
if firstkey.type in ['string', 'text']:
|
if firstkey.type in ['string', 'text']:
|
||||||
cond = '!=""'
|
cond = '!=""'
|
||||||
qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond)
|
qry = '%s.%s.%s%s' % (
|
||||||
|
request.args[0], request.args[1], firstkey.name, cond)
|
||||||
else:
|
else:
|
||||||
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
||||||
return qry
|
return qry
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# ##########################################################
|
# ##########################################################
|
||||||
# ## list all databases and tables
|
# ## list all databases and tables
|
||||||
# ###########################################################
|
# ###########################################################
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
return dict(databases=databases)
|
return dict(databases=databases)
|
||||||
|
|
||||||
@@ -140,6 +139,7 @@ def download():
|
|||||||
db = get_database(request)
|
db = get_database(request)
|
||||||
return response.download(request, db)
|
return response.download(request, db)
|
||||||
|
|
||||||
|
|
||||||
def csv():
|
def csv():
|
||||||
import gluon.contenttype
|
import gluon.contenttype
|
||||||
response.headers['Content-Type'] = \
|
response.headers['Content-Type'] = \
|
||||||
@@ -156,6 +156,7 @@ def csv():
|
|||||||
def import_csv(table, file):
|
def import_csv(table, file):
|
||||||
table.import_from_csv_file(file)
|
table.import_from_csv_file(file)
|
||||||
|
|
||||||
|
|
||||||
def select():
|
def select():
|
||||||
import re
|
import re
|
||||||
db = get_database(request)
|
db = get_database(request)
|
||||||
@@ -192,7 +193,8 @@ def select():
|
|||||||
session.last_query = request.vars.query
|
session.last_query = request.vars.query
|
||||||
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
||||||
_name='query', _value=request.vars.query or '',
|
_name='query', _value=request.vars.query or '',
|
||||||
requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'),
|
requires=IS_NOT_EMPTY(
|
||||||
|
error_message=T("Cannot be empty")))), TR(T('Update:'),
|
||||||
INPUT(_name='update_check', _type='checkbox',
|
INPUT(_name='update_check', _type='checkbox',
|
||||||
value=False), INPUT(_style='width:400px',
|
value=False), INPUT(_style='width:400px',
|
||||||
_name='update_fields', _value=request.vars.update_fields
|
_name='update_fields', _value=request.vars.update_fields
|
||||||
@@ -200,13 +202,14 @@ def select():
|
|||||||
_class='delete', _type='checkbox', value=False), ''),
|
_class='delete', _type='checkbox', value=False), ''),
|
||||||
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
||||||
_action=URL(r=request, args=request.args))
|
_action=URL(r=request, args=request.args))
|
||||||
|
|
||||||
|
tb = None
|
||||||
if form.accepts(request.vars, formname=None):
|
if form.accepts(request.vars, formname=None):
|
||||||
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
||||||
match = regex.match(form.vars.query.strip())
|
match = regex.match(form.vars.query.strip())
|
||||||
if match:
|
if match:
|
||||||
table = match.group('table')
|
table = match.group('table')
|
||||||
try:
|
try:
|
||||||
tb = None
|
|
||||||
nrows = db(query).count()
|
nrows = db(query).count()
|
||||||
if form.vars.update_check and form.vars.update_fields:
|
if form.vars.update_check and form.vars.update_fields:
|
||||||
db(query).update(**eval_in_global_env('dict(%s)'
|
db(query).update(**eval_in_global_env('dict(%s)'
|
||||||
@@ -217,9 +220,11 @@ def select():
|
|||||||
response.flash = T('%s %%{row} deleted', nrows)
|
response.flash = T('%s %%{row} deleted', nrows)
|
||||||
nrows = db(query).count()
|
nrows = db(query).count()
|
||||||
if orderby:
|
if orderby:
|
||||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop), orderby=eval_in_global_env(orderby))
|
rows = db(query, ignore_common_filters=True).select(limitby=(
|
||||||
|
start, stop), orderby=eval_in_global_env(orderby))
|
||||||
else:
|
else:
|
||||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop))
|
rows = db(query, ignore_common_filters=True).select(
|
||||||
|
limitby=(start, stop))
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
import traceback
|
import traceback
|
||||||
tb = traceback.format_exc()
|
tb = traceback.format_exc()
|
||||||
@@ -268,9 +273,11 @@ def update():
|
|||||||
if keyed:
|
if keyed:
|
||||||
key = [f for f in request.vars if f in db[table]._primarykey]
|
key = [f for f in request.vars if f in db[table]._primarykey]
|
||||||
if key:
|
if key:
|
||||||
record = db(db[table][key[0]] == request.vars[key[0]], ignore_common_filters=True).select().first()
|
record = db(db[table][key[0]] == request.vars[key[
|
||||||
|
0]], ignore_common_filters=True).select().first()
|
||||||
else:
|
else:
|
||||||
record = db(db[table].id == request.args(2),ignore_common_filters=True).select().first()
|
record = db(db[table].id == request.args(
|
||||||
|
2), ignore_common_filters=True).select().first()
|
||||||
|
|
||||||
if not record:
|
if not record:
|
||||||
qry = query_by_table_type(table, db)
|
qry = query_by_table_type(table, db)
|
||||||
@@ -282,7 +289,8 @@ def update():
|
|||||||
for k in db[table]._primarykey:
|
for k in db[table]._primarykey:
|
||||||
db[table][k].writable = False
|
db[table][k].writable = False
|
||||||
|
|
||||||
form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'),
|
form = SQLFORM(
|
||||||
|
db[table], record, deletable=True, delete_label=T('Check to delete'),
|
||||||
ignore_rw=ignore_rw and not keyed,
|
ignore_rw=ignore_rw and not keyed,
|
||||||
linkto=URL('select',
|
linkto=URL('select',
|
||||||
args=request.args[:1]), upload=URL(r=request,
|
args=request.args[:1]), upload=URL(r=request,
|
||||||
@@ -304,11 +312,15 @@ def update():
|
|||||||
def state():
|
def state():
|
||||||
return dict()
|
return dict()
|
||||||
|
|
||||||
|
|
||||||
def ccache():
|
def ccache():
|
||||||
form = FORM(
|
form = FORM(
|
||||||
P(TAG.BUTTON(T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
P(TAG.BUTTON(
|
||||||
P(TAG.BUTTON(T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||||
P(TAG.BUTTON(T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
P(TAG.BUTTON(
|
||||||
|
T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||||
|
P(TAG.BUTTON(
|
||||||
|
T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||||
)
|
)
|
||||||
|
|
||||||
if form.accepts(request.vars, session):
|
if form.accepts(request.vars, session):
|
||||||
@@ -332,11 +344,16 @@ def ccache():
|
|||||||
redirect(URL(r=request))
|
redirect(URL(r=request))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from guppy import hpy; hp=hpy()
|
from guppy import hpy
|
||||||
|
hp = hpy()
|
||||||
except ImportError:
|
except ImportError:
|
||||||
hp = False
|
hp = False
|
||||||
|
|
||||||
import shelve, os, copy, time, math
|
import shelve
|
||||||
|
import os
|
||||||
|
import copy
|
||||||
|
import time
|
||||||
|
import math
|
||||||
from gluon import portalocker
|
from gluon import portalocker
|
||||||
|
|
||||||
ram = {
|
ram = {
|
||||||
@@ -379,11 +396,13 @@ def ccache():
|
|||||||
if value[0] < ram['oldest']:
|
if value[0] < ram['oldest']:
|
||||||
ram['oldest'] = value[0]
|
ram['oldest'] = value[0]
|
||||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||||
|
folder = os.path.join(request.folder,'cache')
|
||||||
locker = open(os.path.join(request.folder,
|
if not os.path.exists(folder):
|
||||||
'cache/cache.lock'), 'a')
|
os.mkdir(folder)
|
||||||
|
locker = open(os.path.join(folder, 'cache.lock'), 'a')
|
||||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||||
disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve'))
|
disk_storage = shelve.open(
|
||||||
|
os.path.join(folder, 'cache.shelve'))
|
||||||
try:
|
try:
|
||||||
for key, value in disk_storage.items():
|
for key, value in disk_storage.items():
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
@@ -414,7 +433,8 @@ def ccache():
|
|||||||
total['misses'] = ram['misses'] + disk['misses']
|
total['misses'] = ram['misses'] + disk['misses']
|
||||||
total['keys'] = ram['keys'] + disk['keys']
|
total['keys'] = ram['keys'] + disk['keys']
|
||||||
try:
|
try:
|
||||||
total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses'])
|
total['ratio'] = total['hits'] * 100 / (total['hits'] +
|
||||||
|
total['misses'])
|
||||||
except (KeyError, ZeroDivisionError):
|
except (KeyError, ZeroDivisionError):
|
||||||
total['ratio'] = 0
|
total['ratio'] = 0
|
||||||
|
|
||||||
@@ -440,6 +460,3 @@ def ccache():
|
|||||||
|
|
||||||
return dict(form=form, total=total,
|
return dict(form=form, total=total,
|
||||||
ram=ram, disk=disk, object_stats=hp != False)
|
ram=ram, disk=disk, object_stats=hp != False)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import gluon.contrib.shell
|
|||||||
import gluon.dal
|
import gluon.dal
|
||||||
import gluon.html
|
import gluon.html
|
||||||
import gluon.validators
|
import gluon.validators
|
||||||
import code, thread
|
import code
|
||||||
|
import thread
|
||||||
from gluon.debug import communicate, web_debugger, qdb_debugger
|
from gluon.debug import communicate, web_debugger, qdb_debugger
|
||||||
import pydoc
|
import pydoc
|
||||||
|
|
||||||
@@ -16,6 +17,7 @@ if DEMO_MODE or MULTI_USER_MODE:
|
|||||||
|
|
||||||
FE = 10 ** 9
|
FE = 10 ** 9
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
app = request.args(0) or 'admin'
|
app = request.args(0) or 'admin'
|
||||||
reset()
|
reset()
|
||||||
@@ -23,6 +25,7 @@ def index():
|
|||||||
data = communicate()
|
data = communicate()
|
||||||
return dict(app=app, data=data)
|
return dict(app=app, data=data)
|
||||||
|
|
||||||
|
|
||||||
def callback():
|
def callback():
|
||||||
app = request.args[0]
|
app = request.args[0]
|
||||||
command = request.vars.statement
|
command = request.vars.statement
|
||||||
@@ -31,6 +34,7 @@ def callback():
|
|||||||
k = len(session['debug_commands:' + app]) - 1
|
k = len(session['debug_commands:' + app]) - 1
|
||||||
return '[%i] %s%s\n' % (k + 1, command, output)
|
return '[%i] %s%s\n' % (k + 1, command, output)
|
||||||
|
|
||||||
|
|
||||||
def reset():
|
def reset():
|
||||||
app = request.args(0) or 'admin'
|
app = request.args(0) or 'admin'
|
||||||
session['debug_commands:' + app] = []
|
session['debug_commands:' + app] = []
|
||||||
@@ -81,26 +85,32 @@ def interact():
|
|||||||
f_globals=f_globals, f_locals=f_locals,
|
f_globals=f_globals, f_locals=f_locals,
|
||||||
exception=web_debugger.exception_info)
|
exception=web_debugger.exception_info)
|
||||||
|
|
||||||
|
|
||||||
def step():
|
def step():
|
||||||
web_debugger.do_step()
|
web_debugger.do_step()
|
||||||
redirect(URL("interact"))
|
redirect(URL("interact"))
|
||||||
|
|
||||||
|
|
||||||
def next():
|
def next():
|
||||||
web_debugger.do_next()
|
web_debugger.do_next()
|
||||||
redirect(URL("interact"))
|
redirect(URL("interact"))
|
||||||
|
|
||||||
|
|
||||||
def cont():
|
def cont():
|
||||||
web_debugger.do_continue()
|
web_debugger.do_continue()
|
||||||
redirect(URL("interact"))
|
redirect(URL("interact"))
|
||||||
|
|
||||||
|
|
||||||
def ret():
|
def ret():
|
||||||
web_debugger.do_return()
|
web_debugger.do_return()
|
||||||
redirect(URL("interact"))
|
redirect(URL("interact"))
|
||||||
|
|
||||||
|
|
||||||
def stop():
|
def stop():
|
||||||
web_debugger.do_quit()
|
web_debugger.do_quit()
|
||||||
redirect(URL("interact"))
|
redirect(URL("interact"))
|
||||||
|
|
||||||
|
|
||||||
def execute():
|
def execute():
|
||||||
app = request.args[0]
|
app = request.args[0]
|
||||||
command = request.vars.statement
|
command = request.vars.statement
|
||||||
@@ -166,6 +176,8 @@ def toggle_breakpoint():
|
|||||||
try:
|
try:
|
||||||
filename = os.path.join(request.env['applications_parent'],
|
filename = os.path.join(request.env['applications_parent'],
|
||||||
'applications', request.vars.filename)
|
'applications', request.vars.filename)
|
||||||
|
# normalize path name: replace slashes, references, etc...
|
||||||
|
filename = os.path.normpath(os.path.normcase(filename))
|
||||||
if not request.vars.data:
|
if not request.vars.data:
|
||||||
# ace send us the line number!
|
# ace send us the line number!
|
||||||
lineno = int(request.vars.sel_start) + 1
|
lineno = int(request.vars.sel_start) + 1
|
||||||
@@ -182,6 +194,8 @@ def toggle_breakpoint():
|
|||||||
if lineno is not None:
|
if lineno is not None:
|
||||||
for bp in qdb_debugger.do_list_breakpoint():
|
for bp in qdb_debugger.do_list_breakpoint():
|
||||||
no, bp_filename, bp_lineno, temporary, enabled, hits, cond = bp
|
no, bp_filename, bp_lineno, temporary, enabled, hits, cond = bp
|
||||||
|
# normalize path name: replace slashes, references, etc...
|
||||||
|
bp_filename = os.path.normpath(os.path.normcase(bp_filename))
|
||||||
if filename == bp_filename and lineno == bp_lineno:
|
if filename == bp_filename and lineno == bp_lineno:
|
||||||
err = qdb_debugger.do_clear_breakpoint(filename, lineno)
|
err = qdb_debugger.do_clear_breakpoint(filename, lineno)
|
||||||
response.flash = T("Removed Breakpoint on %s at line %s", (
|
response.flash = T("Removed Breakpoint on %s at line %s", (
|
||||||
@@ -198,4 +212,3 @@ def toggle_breakpoint():
|
|||||||
except Exception, e:
|
except Exception, e:
|
||||||
session.flash = str(e)
|
session.flash = str(e)
|
||||||
return response.json({'ok': ok, 'lineno': lineno})
|
return response.json({'ok': ok, 'lineno': lineno})
|
||||||
|
|
||||||
|
|||||||
@@ -39,26 +39,33 @@ if FILTER_APPS and request.args(0) and not request.args(0) in FILTER_APPS:
|
|||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
|
|
||||||
|
|
||||||
if not session.token: session.token = web2py_uuid()
|
if not session.token:
|
||||||
|
session.token = web2py_uuid()
|
||||||
|
|
||||||
|
|
||||||
def count_lines(data):
|
def count_lines(data):
|
||||||
return len([line for line in data.split('\n') if line.strip() and not line.startswith('#')])
|
return len([line for line in data.split('\n') if line.strip() and not line.startswith('#')])
|
||||||
|
|
||||||
|
|
||||||
def log_progress(app, mode='EDIT', filename=None, progress=0):
|
def log_progress(app, mode='EDIT', filename=None, progress=0):
|
||||||
progress_file = os.path.join(apath(app, r=request), 'progress.log')
|
progress_file = os.path.join(apath(app, r=request), 'progress.log')
|
||||||
now = str(request.now)[:19]
|
now = str(request.now)[:19]
|
||||||
if not os.path.exists(progress_file):
|
if not os.path.exists(progress_file):
|
||||||
safe_open(progress_file, 'w').write('[%s] START\n' % now)
|
safe_open(progress_file, 'w').write('[%s] START\n' % now)
|
||||||
if filename:
|
if filename:
|
||||||
safe_open(progress_file,'a').write('[%s] %s %s: %s\n' % (now,mode,filename,progress))
|
safe_open(progress_file, 'a').write(
|
||||||
|
'[%s] %s %s: %s\n' % (now, mode, filename, progress))
|
||||||
|
|
||||||
|
|
||||||
def safe_open(a, b):
|
def safe_open(a, b):
|
||||||
if DEMO_MODE and ('w' in b or 'a' in b):
|
if DEMO_MODE and ('w' in b or 'a' in b):
|
||||||
class tmp:
|
class tmp:
|
||||||
def write(self,data): pass
|
def write(self, data):
|
||||||
|
pass
|
||||||
return tmp()
|
return tmp()
|
||||||
return open(a, b)
|
return open(a, b)
|
||||||
|
|
||||||
|
|
||||||
def safe_read(a, b='r'):
|
def safe_read(a, b='r'):
|
||||||
safe_file = safe_open(a, b)
|
safe_file = safe_open(a, b)
|
||||||
try:
|
try:
|
||||||
@@ -66,6 +73,7 @@ def safe_read(a, b='r'):
|
|||||||
finally:
|
finally:
|
||||||
safe_file.close()
|
safe_file.close()
|
||||||
|
|
||||||
|
|
||||||
def safe_write(a, value, b='w'):
|
def safe_write(a, value, b='w'):
|
||||||
safe_file = safe_open(a, b)
|
safe_file = safe_open(a, b)
|
||||||
try:
|
try:
|
||||||
@@ -73,14 +81,16 @@ def safe_write(a, value, b='w'):
|
|||||||
finally:
|
finally:
|
||||||
safe_file.close()
|
safe_file.close()
|
||||||
|
|
||||||
|
|
||||||
def get_app(name=None):
|
def get_app(name=None):
|
||||||
app = name or request.args(0)
|
app = name or request.args(0)
|
||||||
if app and (not MULTI_USER_MODE or is_manager() or \
|
if app and (not MULTI_USER_MODE or is_manager() or
|
||||||
db(db.app.name == app)(db.app.owner == auth.user.id).count()):
|
db(db.app.name == app)(db.app.owner == auth.user.id).count()):
|
||||||
return app
|
return app
|
||||||
session.flash = T('App does not exist or your are not authorized')
|
session.flash = T('App does not exist or your are not authorized')
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
""" Index handler """
|
""" Index handler """
|
||||||
|
|
||||||
@@ -137,9 +147,10 @@ def check_version():
|
|||||||
return SPAN('You should upgrade to version %s.%s.%s' % version_number[:3])
|
return SPAN('You should upgrade to version %s.%s.%s' % version_number[:3])
|
||||||
else:
|
else:
|
||||||
return sp_button(URL('upgrade_web2py'), T('upgrade now')) \
|
return sp_button(URL('upgrade_web2py'), T('upgrade now')) \
|
||||||
+ XML(' <strong class="upgrade_version">%s.%s.%s</strong>' \
|
+ XML(' <strong class="upgrade_version">%s.%s.%s</strong>'
|
||||||
% version_number[:3])
|
% version_number[:3])
|
||||||
|
|
||||||
|
|
||||||
def logout():
|
def logout():
|
||||||
""" Logout handler """
|
""" Logout handler """
|
||||||
session.authorized = None
|
session.authorized = None
|
||||||
@@ -151,10 +162,12 @@ def logout():
|
|||||||
def change_password():
|
def change_password():
|
||||||
|
|
||||||
if session.pam_user:
|
if session.pam_user:
|
||||||
session.flash = T('PAM authenticated user, cannot change password here')
|
session.flash = T(
|
||||||
|
'PAM authenticated user, cannot change password here')
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
form = SQLFORM.factory(Field('current_admin_password', 'password'),
|
form = SQLFORM.factory(Field('current_admin_password', 'password'),
|
||||||
Field('new_admin_password','password',requires=IS_STRONG()),
|
Field('new_admin_password',
|
||||||
|
'password', requires=IS_STRONG()),
|
||||||
Field('new_admin_password_again', 'password'))
|
Field('new_admin_password_again', 'password'))
|
||||||
if form.accepts(request.vars):
|
if form.accepts(request.vars):
|
||||||
if not verify_password(request.vars.current_admin_password):
|
if not verify_password(request.vars.current_admin_password):
|
||||||
@@ -163,7 +176,8 @@ def change_password():
|
|||||||
form.errors.new_admin_password_again = T('no match')
|
form.errors.new_admin_password_again = T('no match')
|
||||||
else:
|
else:
|
||||||
path = abspath('parameters_%s.py' % request.env.server_port)
|
path = abspath('parameters_%s.py' % request.env.server_port)
|
||||||
safe_write(path, 'password="%s"' % CRYPT()(request.vars.new_admin_password)[0])
|
safe_write(path, 'password="%s"' % CRYPT()(
|
||||||
|
request.vars.new_admin_password)[0])
|
||||||
session.flash = T('password changed')
|
session.flash = T('password changed')
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
return dict(form=form)
|
return dict(form=form)
|
||||||
@@ -295,8 +309,10 @@ def report_progress(app):
|
|||||||
matches = regex.findall(open(progress_file, 'r').read())
|
matches = regex.findall(open(progress_file, 'r').read())
|
||||||
events, counter = [], 0
|
events, counter = [], 0
|
||||||
for m in matches:
|
for m in matches:
|
||||||
if not m: continue
|
if not m:
|
||||||
days = -(request.now - datetime.datetime.strptime(m[0],'%Y-%m-%d %H:%M:%S')).days
|
continue
|
||||||
|
days = -(request.now - datetime.datetime.strptime(m[0],
|
||||||
|
'%Y-%m-%d %H:%M:%S')).days
|
||||||
counter += int(m[1])
|
counter += int(m[1])
|
||||||
events.append([days, counter])
|
events.append([days, counter])
|
||||||
return events
|
return events
|
||||||
@@ -324,6 +340,7 @@ def pack():
|
|||||||
session.flash = T('internal error: %s' % e)
|
session.flash = T('internal error: %s' % e)
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
|
|
||||||
|
|
||||||
def pack_plugin():
|
def pack_plugin():
|
||||||
app = get_app()
|
app = get_app()
|
||||||
if len(request.args) == 2:
|
if len(request.args) == 2:
|
||||||
@@ -338,6 +355,7 @@ def pack_plugin():
|
|||||||
session.flash = T('internal error')
|
session.flash = T('internal error')
|
||||||
redirect(URL('plugin', args=request.args))
|
redirect(URL('plugin', args=request.args))
|
||||||
|
|
||||||
|
|
||||||
def upgrade_web2py():
|
def upgrade_web2py():
|
||||||
dialog = FORM.confirm(T('Upgrade'),
|
dialog = FORM.confirm(T('Upgrade'),
|
||||||
{T('Cancel'): URL('site')})
|
{T('Cancel'): URL('site')})
|
||||||
@@ -350,6 +368,7 @@ def upgrade_web2py():
|
|||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
return dict(dialog=dialog)
|
return dict(dialog=dialog)
|
||||||
|
|
||||||
|
|
||||||
def uninstall():
|
def uninstall():
|
||||||
app = get_app()
|
app = get_app()
|
||||||
|
|
||||||
@@ -407,6 +426,7 @@ def remove_compiled_app():
|
|||||||
session.flash = T('compiled application removed')
|
session.flash = T('compiled application removed')
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
|
|
||||||
|
|
||||||
def delete():
|
def delete():
|
||||||
""" Object delete handler """
|
""" Object delete handler """
|
||||||
app = get_app()
|
app = get_app()
|
||||||
@@ -432,6 +452,7 @@ def delete():
|
|||||||
redirect(URL(sender, anchor=request.vars.id2))
|
redirect(URL(sender, anchor=request.vars.id2))
|
||||||
return dict(filename=filename, sender=sender)
|
return dict(filename=filename, sender=sender)
|
||||||
|
|
||||||
|
|
||||||
def delete():
|
def delete():
|
||||||
""" Object delete handler """
|
""" Object delete handler """
|
||||||
app = get_app()
|
app = get_app()
|
||||||
@@ -458,6 +479,7 @@ def delete():
|
|||||||
redirect(URL(sender, anchor=request.vars.id2))
|
redirect(URL(sender, anchor=request.vars.id2))
|
||||||
return dict(dialog=dialog, filename=filename)
|
return dict(dialog=dialog, filename=filename)
|
||||||
|
|
||||||
|
|
||||||
def enable():
|
def enable():
|
||||||
app = get_app()
|
app = get_app()
|
||||||
filename = os.path.join(apath(app, r=request), 'DISABLED')
|
filename = os.path.join(apath(app, r=request), 'DISABLED')
|
||||||
@@ -470,6 +492,7 @@ def enable():
|
|||||||
safe_open(filename, 'wb').write(time.ctime())
|
safe_open(filename, 'wb').write(time.ctime())
|
||||||
return SPAN(T('Enable'), _style='color:red')
|
return SPAN(T('Enable'), _style='color:red')
|
||||||
|
|
||||||
|
|
||||||
def peek():
|
def peek():
|
||||||
""" Visualize object code """
|
""" Visualize object code """
|
||||||
app = get_app(request.vars.app)
|
app = get_app(request.vars.app)
|
||||||
@@ -491,6 +514,7 @@ def peek():
|
|||||||
data=data,
|
data=data,
|
||||||
extension=extension)
|
extension=extension)
|
||||||
|
|
||||||
|
|
||||||
def test():
|
def test():
|
||||||
""" Execute controller tests """
|
""" Execute controller tests """
|
||||||
app = get_app()
|
app = get_app()
|
||||||
@@ -499,16 +523,20 @@ def test():
|
|||||||
else:
|
else:
|
||||||
file = '.*\.py'
|
file = '.*\.py'
|
||||||
|
|
||||||
controllers = listdir(apath('%s/controllers/' % app, r=request), file + '$')
|
controllers = listdir(
|
||||||
|
apath('%s/controllers/' % app, r=request), file + '$')
|
||||||
|
|
||||||
return dict(app=app, controllers=controllers)
|
return dict(app=app, controllers=controllers)
|
||||||
|
|
||||||
|
|
||||||
def keepalive():
|
def keepalive():
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|
||||||
def search():
|
def search():
|
||||||
keywords = request.vars.keywords or ''
|
keywords = request.vars.keywords or ''
|
||||||
app = get_app()
|
app = get_app()
|
||||||
|
|
||||||
def match(filename, keywords):
|
def match(filename, keywords):
|
||||||
filename = os.path.join(apath(app, r=request), filename)
|
filename = os.path.join(apath(app, r=request), filename)
|
||||||
if keywords in read_file(filename, 'rb'):
|
if keywords in read_file(filename, 'rb'):
|
||||||
@@ -518,9 +546,11 @@ def search():
|
|||||||
files1 = glob(os.path.join(path, '*/*.py'))
|
files1 = glob(os.path.join(path, '*/*.py'))
|
||||||
files2 = glob(os.path.join(path, '*/*.html'))
|
files2 = glob(os.path.join(path, '*/*.html'))
|
||||||
files3 = glob(os.path.join(path, '*/*/*.html'))
|
files3 = glob(os.path.join(path, '*/*/*.html'))
|
||||||
files=[x[len(path)+1:].replace('\\','/') for x in files1+files2+files3 if match(x,keywords)]
|
files = [x[len(path) + 1:].replace(
|
||||||
|
'\\', '/') for x in files1 + files2 + files3 if match(x, keywords)]
|
||||||
return response.json(dict(files=files, message=T.M('Searching: **%s** %%{file}', len(files))))
|
return response.json(dict(files=files, message=T.M('Searching: **%s** %%{file}', len(files))))
|
||||||
|
|
||||||
|
|
||||||
def edit():
|
def edit():
|
||||||
""" File edit handler """
|
""" File edit handler """
|
||||||
# Load json only if it is ajax edited...
|
# Load json only if it is ajax edited...
|
||||||
@@ -590,7 +620,8 @@ def edit():
|
|||||||
data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
|
data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
|
||||||
safe_write(path, data)
|
safe_write(path, data)
|
||||||
lineno_new = count_lines(data)
|
lineno_new = count_lines(data)
|
||||||
log_progress(app,'EDIT',filename,progress=lineno_new-lineno_old)
|
log_progress(
|
||||||
|
app, 'EDIT', filename, progress=lineno_new - lineno_old)
|
||||||
file_hash = md5_hash(data)
|
file_hash = md5_hash(data)
|
||||||
saved_on = time.ctime(os.stat(path)[stat.ST_MTIME])
|
saved_on = time.ctime(os.stat(path)[stat.ST_MTIME])
|
||||||
response.flash = T('file saved on %s', saved_on)
|
response.flash = T('file saved on %s', saved_on)
|
||||||
@@ -609,28 +640,33 @@ def edit():
|
|||||||
in enumerate(request.vars.data.split("\n"))
|
in enumerate(request.vars.data.split("\n"))
|
||||||
if l < e.lineno - 1])
|
if l < e.lineno - 1])
|
||||||
if e.text and e.offset:
|
if e.text and e.offset:
|
||||||
offset = e.offset - (len(e.text) - len(e.text.splitlines()[-1]))
|
offset = e.offset - (len(e.text) - len(
|
||||||
|
e.text.splitlines()[-1]))
|
||||||
else:
|
else:
|
||||||
offset = 0
|
offset = 0
|
||||||
highlight = {'start': start, 'end': start + offset + 1, 'lineno': e.lineno}
|
highlight = {'start': start, 'end': start +
|
||||||
|
offset + 1, 'lineno': e.lineno}
|
||||||
try:
|
try:
|
||||||
ex_name = e.__class__.__name__
|
ex_name = e.__class__.__name__
|
||||||
except:
|
except:
|
||||||
ex_name = 'unknown exception!'
|
ex_name = 'unknown exception!'
|
||||||
response.flash = DIV(T('failed to compile file because:'), BR(),
|
response.flash = DIV(T('failed to compile file because:'), BR(),
|
||||||
B(ex_name), ' ' + T('at line %s', e.lineno),
|
B(ex_name), ' ' + T('at line %s', e.lineno),
|
||||||
offset and ' '+T('at char %s', offset) or '',
|
offset and ' ' +
|
||||||
|
T('at char %s', offset) or '',
|
||||||
PRE(str(e)))
|
PRE(str(e)))
|
||||||
|
|
||||||
if data_or_revert and request.args[1] == 'modules':
|
if data_or_revert and request.args[1] == 'modules':
|
||||||
# Lets try to reload the modules
|
# Lets try to reload the modules
|
||||||
try:
|
try:
|
||||||
mopath = '.'.join(request.args[2:])[:-3]
|
mopath = '.'.join(request.args[2:])[:-3]
|
||||||
exec 'import applications.%s.modules.%s' % (request.args[0], mopath)
|
exec 'import applications.%s.modules.%s' % (
|
||||||
|
request.args[0], mopath)
|
||||||
reload(sys.modules['applications.%s.modules.%s'
|
reload(sys.modules['applications.%s.modules.%s'
|
||||||
% (request.args[0], mopath)])
|
% (request.args[0], mopath)])
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
response.flash = DIV(T('failed to reload module because:'),PRE(str(e)))
|
response.flash = DIV(
|
||||||
|
T('failed to reload module because:'), PRE(str(e)))
|
||||||
|
|
||||||
edit_controller = None
|
edit_controller = None
|
||||||
editviewlinks = None
|
editviewlinks = None
|
||||||
@@ -660,7 +696,7 @@ def edit():
|
|||||||
for v in viewlist:
|
for v in viewlist:
|
||||||
vf = os.path.split(v)[-1]
|
vf = os.path.split(v)[-1]
|
||||||
vargs = "/".join([viewpath.replace(os.sep, "/"), vf])
|
vargs = "/".join([viewpath.replace(os.sep, "/"), vf])
|
||||||
editviewlinks.append(A(vf.split(".")[0],\
|
editviewlinks.append(A(vf.split(".")[0],
|
||||||
_href=URL('edit', args=[vargs])))
|
_href=URL('edit', args=[vargs])))
|
||||||
|
|
||||||
if len(request.args) > 2 and request.args[1] == 'controllers':
|
if len(request.args) > 2 and request.args[1] == 'controllers':
|
||||||
@@ -680,7 +716,7 @@ def edit():
|
|||||||
editarea_preferences['REPLACE_TAB_BY_SPACES'] = '4'
|
editarea_preferences['REPLACE_TAB_BY_SPACES'] = '4'
|
||||||
editarea_preferences['DISPLAY'] = 'onload'
|
editarea_preferences['DISPLAY'] = 'onload'
|
||||||
for key in editarea_preferences:
|
for key in editarea_preferences:
|
||||||
if globals().has_key(key):
|
if key in globals():
|
||||||
editarea_preferences[key] = globals()[key]
|
editarea_preferences[key] = globals()[key]
|
||||||
return dict(app=request.args[0],
|
return dict(app=request.args[0],
|
||||||
filename=filename,
|
filename=filename,
|
||||||
@@ -695,6 +731,7 @@ def edit():
|
|||||||
editarea_preferences=editarea_preferences,
|
editarea_preferences=editarea_preferences,
|
||||||
editviewlinks=editviewlinks)
|
editviewlinks=editviewlinks)
|
||||||
|
|
||||||
|
|
||||||
def resolve():
|
def resolve():
|
||||||
"""
|
"""
|
||||||
"""
|
"""
|
||||||
@@ -739,7 +776,7 @@ def resolve():
|
|||||||
return 'minus'
|
return 'minus'
|
||||||
|
|
||||||
if request.vars:
|
if request.vars:
|
||||||
c = '\n'.join([item[2:].rstrip() for (i, item) in enumerate(d) if item[0] \
|
c = '\n'.join([item[2:].rstrip() for (i, item) in enumerate(d) if item[0]
|
||||||
== ' ' or 'line%i' % i in request.vars])
|
== ' ' or 'line%i' % i in request.vars])
|
||||||
safe_write(path, c)
|
safe_write(path, c)
|
||||||
session.flash = 'files merged'
|
session.flash = 'files merged'
|
||||||
@@ -770,7 +807,8 @@ def edit_language():
|
|||||||
form = SPAN(strings['__corrupted__'], _class='error')
|
form = SPAN(strings['__corrupted__'], _class='error')
|
||||||
return dict(filename=filename, form=form)
|
return dict(filename=filename, form=form)
|
||||||
|
|
||||||
keys = sorted(strings.keys(),lambda x,y: cmp(unicode(x,'utf-8').lower(), unicode(y,'utf-8').lower()))
|
keys = sorted(strings.keys(), lambda x, y: cmp(
|
||||||
|
unicode(x, 'utf-8').lower(), unicode(y, 'utf-8').lower()))
|
||||||
rows = []
|
rows = []
|
||||||
rows.append(H2(T('Original/Translation')))
|
rows.append(H2(T('Original/Translation')))
|
||||||
|
|
||||||
@@ -805,18 +843,21 @@ def edit_language():
|
|||||||
strs = dict()
|
strs = dict()
|
||||||
for key in keys:
|
for key in keys:
|
||||||
name = md5_hash(key)
|
name = md5_hash(key)
|
||||||
if form.vars[name]==chr(127): continue
|
if form.vars[name] == chr(127):
|
||||||
|
continue
|
||||||
strs[key] = form.vars[name]
|
strs[key] = form.vars[name]
|
||||||
write_dict(apath(filename, r=request), strs)
|
write_dict(apath(filename, r=request), strs)
|
||||||
session.flash = T('file saved on %(time)s', dict(time=time.ctime()))
|
session.flash = T('file saved on %(time)s', dict(time=time.ctime()))
|
||||||
redirect(URL(r=request, args=request.args))
|
redirect(URL(r=request, args=request.args))
|
||||||
return dict(app=request.args[0], filename=filename, form=form)
|
return dict(app=request.args[0], filename=filename, form=form)
|
||||||
|
|
||||||
|
|
||||||
def edit_plurals():
|
def edit_plurals():
|
||||||
""" Edit plurals file """
|
""" Edit plurals file """
|
||||||
app = get_app()
|
app = get_app()
|
||||||
filename = '/'.join(request.args)
|
filename = '/'.join(request.args)
|
||||||
plurals = read_plural_dict(apath(filename, r=request)) # plural forms dictionary
|
plurals = read_plural_dict(
|
||||||
|
apath(filename, r=request)) # plural forms dictionary
|
||||||
nplurals = int(request.vars.nplurals) - 1 # plural forms quantity
|
nplurals = int(request.vars.nplurals) - 1 # plural forms quantity
|
||||||
xnplurals = xrange(nplurals)
|
xnplurals = xrange(nplurals)
|
||||||
|
|
||||||
@@ -825,7 +866,8 @@ def edit_plurals():
|
|||||||
form = SPAN(plurals['__corrupted__'], _class='error')
|
form = SPAN(plurals['__corrupted__'], _class='error')
|
||||||
return dict(filename=filename, form=form)
|
return dict(filename=filename, form=form)
|
||||||
|
|
||||||
keys = sorted(plurals.keys(),lambda x,y: cmp(unicode(x,'utf-8').lower(), unicode(y,'utf-8').lower()))
|
keys = sorted(plurals.keys(), lambda x, y: cmp(
|
||||||
|
unicode(x, 'utf-8').lower(), unicode(y, 'utf-8').lower()))
|
||||||
rows = []
|
rows = []
|
||||||
|
|
||||||
row = [T("Singular Form")]
|
row = [T("Singular Form")]
|
||||||
@@ -840,8 +882,10 @@ def edit_plurals():
|
|||||||
forms.extend(None for i in xrange(nplurals - len(forms)))
|
forms.extend(None for i in xrange(nplurals - len(forms)))
|
||||||
|
|
||||||
row = [B(key)]
|
row = [B(key)]
|
||||||
row.extend([INPUT(_type='text', _name=name+'_'+str(n), value=forms[n], _size=20) for n in xnplurals])
|
row.extend([INPUT(_type='text', _name=name + '_' + str(n),
|
||||||
row.append(TD(TAG.BUTTON(T('delete'), _onclick='return delkey("%s")' % name)))
|
value=forms[n], _size=20) for n in xnplurals])
|
||||||
|
row.append(TD(
|
||||||
|
TAG.BUTTON(T('delete'), _onclick='return delkey("%s")' % name)))
|
||||||
rows.append(TR(row, _id=name))
|
rows.append(TR(row, _id=name))
|
||||||
if rows:
|
if rows:
|
||||||
table.append(TBODY(rows))
|
table.append(TBODY(rows))
|
||||||
@@ -851,11 +895,14 @@ def edit_plurals():
|
|||||||
new_plurals = dict()
|
new_plurals = dict()
|
||||||
for key in keys:
|
for key in keys:
|
||||||
name = md5_hash(key)
|
name = md5_hash(key)
|
||||||
if form.vars[name+'_0']==chr(127): continue
|
if form.vars[name + '_0'] == chr(127):
|
||||||
new_plurals[key] = [form.vars[name+'_'+str(n)] for n in xnplurals]
|
continue
|
||||||
|
new_plurals[key] = [form.vars[name + '_' + str(n)]
|
||||||
|
for n in xnplurals]
|
||||||
write_plural_dict(apath(filename, r=request), new_plurals)
|
write_plural_dict(apath(filename, r=request), new_plurals)
|
||||||
session.flash = T('file saved on %(time)s', dict(time=time.ctime()))
|
session.flash = T('file saved on %(time)s', dict(time=time.ctime()))
|
||||||
redirect(URL(r=request, args=request.args, vars=dict(nplurals=request.vars.nplurals)))
|
redirect(URL(r=request, args=request.args, vars=dict(
|
||||||
|
nplurals=request.vars.nplurals)))
|
||||||
return dict(app=request.args[0], filename=filename, form=form)
|
return dict(app=request.args[0], filename=filename, form=form)
|
||||||
|
|
||||||
|
|
||||||
@@ -879,7 +926,7 @@ def design():
|
|||||||
if request.vars and not request.vars.token == session.token:
|
if request.vars and not request.vars.token == session.token:
|
||||||
redirect(URL('logout'))
|
redirect(URL('logout'))
|
||||||
|
|
||||||
if request.vars.pluginfile!=None and not isinstance(request.vars.pluginfile,str):
|
if request.vars.pluginfile is not None and not isinstance(request.vars.pluginfile, str):
|
||||||
filename = os.path.basename(request.vars.pluginfile.filename)
|
filename = os.path.basename(request.vars.pluginfile.filename)
|
||||||
if plugin_install(app, request.vars.pluginfile.file,
|
if plugin_install(app, request.vars.pluginfile.file,
|
||||||
request, filename):
|
request, filename):
|
||||||
@@ -893,7 +940,6 @@ def design():
|
|||||||
session.flash = T('plugin not specified')
|
session.flash = T('plugin not specified')
|
||||||
redirect(URL(r=request))
|
redirect(URL(r=request))
|
||||||
|
|
||||||
|
|
||||||
# If we have only pyc files it means that
|
# If we have only pyc files it means that
|
||||||
# we cannot design
|
# we cannot design
|
||||||
if os.path.exists(apath('%s/compiled' % app, r=request)):
|
if os.path.exists(apath('%s/compiled' % app, r=request)):
|
||||||
@@ -911,7 +957,8 @@ def design():
|
|||||||
defines[m].sort()
|
defines[m].sort()
|
||||||
|
|
||||||
# Get all controllers
|
# Get all controllers
|
||||||
controllers = sorted(listdir(apath('%s/controllers/' % app, r=request), '.*\.py$'))
|
controllers = sorted(
|
||||||
|
listdir(apath('%s/controllers/' % app, r=request), '.*\.py$'))
|
||||||
controllers = [x.replace('\\', '/') for x in controllers]
|
controllers = [x.replace('\\', '/') for x in controllers]
|
||||||
functions = {}
|
functions = {}
|
||||||
for c in controllers:
|
for c in controllers:
|
||||||
@@ -920,7 +967,8 @@ def design():
|
|||||||
functions[c] = items
|
functions[c] = items
|
||||||
|
|
||||||
# Get all views
|
# Get all views
|
||||||
views = sorted(listdir(apath('%s/views/' % app, r=request), '[\w/\-]+(\.\w+)+$'))
|
views = sorted(
|
||||||
|
listdir(apath('%s/views/' % app, r=request), '[\w/\-]+(\.\w+)+$'))
|
||||||
views = [x.replace('\\', '/') for x in views if not x.endswith('.bak')]
|
views = [x.replace('\\', '/') for x in views if not x.endswith('.bak')]
|
||||||
extend = {}
|
extend = {}
|
||||||
include = {}
|
include = {}
|
||||||
@@ -950,22 +998,25 @@ def design():
|
|||||||
statics.sort()
|
statics.sort()
|
||||||
|
|
||||||
# Get all languages
|
# Get all languages
|
||||||
|
langpath = os.path.join(apath(app, r=request),'languages')
|
||||||
languages = dict([(lang, info) for lang, info
|
languages = dict([(lang, info) for lang, info
|
||||||
in read_possible_languages(
|
in read_possible_languages(langpath).iteritems()
|
||||||
apath(app, r=request)).iteritems()
|
|
||||||
if info[2] != 0]) # info[2] is langfile_mtime:
|
if info[2] != 0]) # info[2] is langfile_mtime:
|
||||||
# get only existed files
|
# get only existed files
|
||||||
|
|
||||||
#Get crontab
|
#Get crontab
|
||||||
cronfolder = apath('%s/cron' % app, r=request)
|
cronfolder = apath('%s/cron' % app, r=request)
|
||||||
if not os.path.exists(cronfolder): os.mkdir(cronfolder)
|
if not os.path.exists(cronfolder):
|
||||||
|
os.mkdir(cronfolder)
|
||||||
crontab = apath('%s/cron/crontab' % app, r=request)
|
crontab = apath('%s/cron/crontab' % app, r=request)
|
||||||
if not os.path.exists(crontab):
|
if not os.path.exists(crontab):
|
||||||
safe_write(crontab, '#crontab')
|
safe_write(crontab, '#crontab')
|
||||||
|
|
||||||
plugins = []
|
plugins = []
|
||||||
|
|
||||||
def filter_plugins(items, plugins):
|
def filter_plugins(items, plugins):
|
||||||
plugins+=[item[7:].split('/')[0].split('.')[0] for item in items if item.startswith('plugin_')]
|
plugins += [item[7:].split('/')[0].split(
|
||||||
|
'.')[0] for item in items if item.startswith('plugin_')]
|
||||||
plugins[:] = list(set(plugins))
|
plugins[:] = list(set(plugins))
|
||||||
plugins.sort()
|
plugins.sort()
|
||||||
return [item for item in items if not item.startswith('plugin_')]
|
return [item for item in items if not item.startswith('plugin_')]
|
||||||
@@ -985,6 +1036,7 @@ def design():
|
|||||||
crontab=crontab,
|
crontab=crontab,
|
||||||
plugins=plugins)
|
plugins=plugins)
|
||||||
|
|
||||||
|
|
||||||
def delete_plugin():
|
def delete_plugin():
|
||||||
""" Object delete handler """
|
""" Object delete handler """
|
||||||
app = request.args(0)
|
app = request.args(0)
|
||||||
@@ -1014,6 +1066,7 @@ def delete_plugin():
|
|||||||
redirect(URL('design', args=request.args(0), anchor=request.vars.id2))
|
redirect(URL('design', args=request.args(0), anchor=request.vars.id2))
|
||||||
return dict(dialog=dialog, plugin=plugin)
|
return dict(dialog=dialog, plugin=plugin)
|
||||||
|
|
||||||
|
|
||||||
def plugin():
|
def plugin():
|
||||||
""" Application design handler """
|
""" Application design handler """
|
||||||
app = get_app()
|
app = get_app()
|
||||||
@@ -1040,7 +1093,8 @@ def plugin():
|
|||||||
defines[m].sort()
|
defines[m].sort()
|
||||||
|
|
||||||
# Get all controllers
|
# Get all controllers
|
||||||
controllers = sorted(listdir(apath('%s/controllers/' % app, r=request), '.*\.py$'))
|
controllers = sorted(
|
||||||
|
listdir(apath('%s/controllers/' % app, r=request), '.*\.py$'))
|
||||||
controllers = [x.replace('\\', '/') for x in controllers]
|
controllers = [x.replace('\\', '/') for x in controllers]
|
||||||
functions = {}
|
functions = {}
|
||||||
for c in controllers:
|
for c in controllers:
|
||||||
@@ -1049,7 +1103,8 @@ def plugin():
|
|||||||
functions[c] = items
|
functions[c] = items
|
||||||
|
|
||||||
# Get all views
|
# Get all views
|
||||||
views = sorted(listdir(apath('%s/views/' % app, r=request), '[\w/\-]+\.\w+$'))
|
views = sorted(
|
||||||
|
listdir(apath('%s/views/' % app, r=request), '[\w/\-]+\.\w+$'))
|
||||||
views = [x.replace('\\', '/') for x in views]
|
views = [x.replace('\\', '/') for x in views]
|
||||||
extend = {}
|
extend = {}
|
||||||
include = {}
|
include = {}
|
||||||
@@ -1195,7 +1250,8 @@ def create_file():
|
|||||||
if len(filename) == 5:
|
if len(filename) == 5:
|
||||||
raise SyntaxError
|
raise SyntaxError
|
||||||
|
|
||||||
msg = T('This is the %(filename)s template', dict(filename=filename))
|
msg = T(
|
||||||
|
'This is the %(filename)s template', dict(filename=filename))
|
||||||
if extension == 'html':
|
if extension == 'html':
|
||||||
text = dedent("""
|
text = dedent("""
|
||||||
{{extend 'layout.html'}}
|
{{extend 'layout.html'}}
|
||||||
@@ -1245,8 +1301,10 @@ def create_file():
|
|||||||
session.flash = T('file "%(filename)s" created',
|
session.flash = T('file "%(filename)s" created',
|
||||||
dict(filename=full_filename[len(path):]))
|
dict(filename=full_filename[len(path):]))
|
||||||
vars = {}
|
vars = {}
|
||||||
if request.vars.id: vars['id']=request.vars.id
|
if request.vars.id:
|
||||||
if request.vars.app: vars['app']=request.vars.app
|
vars['id'] = request.vars.id
|
||||||
|
if request.vars.app:
|
||||||
|
vars['app'] = request.vars.app
|
||||||
redirect(URL('edit',
|
redirect(URL('edit',
|
||||||
args=[os.path.join(request.vars.location, filename)], vars=vars))
|
args=[os.path.join(request.vars.location, filename)], vars=vars))
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
@@ -1319,7 +1377,8 @@ def errors():
|
|||||||
method = request.args(1) or 'new'
|
method = request.args(1) or 'new'
|
||||||
db_ready = {}
|
db_ready = {}
|
||||||
db_ready['status'] = get_ticket_storage(app)
|
db_ready['status'] = get_ticket_storage(app)
|
||||||
db_ready['errmessage'] = T("No ticket_storage.txt found under /private folder")
|
db_ready['errmessage'] = T(
|
||||||
|
"No ticket_storage.txt found under /private folder")
|
||||||
db_ready['errlink'] = "http://web2py.com/books/default/chapter/29/13#Collecting-tickets"
|
db_ready['errlink'] = "http://web2py.com/books/default/chapter/29/13#Collecting-tickets"
|
||||||
|
|
||||||
if method == 'new':
|
if method == 'new':
|
||||||
@@ -1334,7 +1393,8 @@ def errors():
|
|||||||
|
|
||||||
for fn in listdir(errors_path, '^[a-fA-F0-9.\-]+$'):
|
for fn in listdir(errors_path, '^[a-fA-F0-9.\-]+$'):
|
||||||
fullpath = os.path.join(errors_path, fn)
|
fullpath = os.path.join(errors_path, fn)
|
||||||
if not os.path.isfile(fullpath): continue
|
if not os.path.isfile(fullpath):
|
||||||
|
continue
|
||||||
try:
|
try:
|
||||||
fullpath_file = open(fullpath, 'r')
|
fullpath_file = open(fullpath, 'r')
|
||||||
try:
|
try:
|
||||||
@@ -1367,7 +1427,6 @@ def errors():
|
|||||||
|
|
||||||
return dict(errors=[x[1] for x in decorated], app=app, method=method, db_ready=db_ready)
|
return dict(errors=[x[1] for x in decorated], app=app, method=method, db_ready=db_ready)
|
||||||
|
|
||||||
|
|
||||||
elif method == 'dbnew':
|
elif method == 'dbnew':
|
||||||
errors_path = apath('%s/errors' % app, r=request)
|
errors_path = apath('%s/errors' % app, r=request)
|
||||||
tk_db, tk_table = get_ticket_storage(app)
|
tk_db, tk_table = get_ticket_storage(app)
|
||||||
@@ -1417,7 +1476,8 @@ def errors():
|
|||||||
tk_db.commit()
|
tk_db.commit()
|
||||||
tickets_ = tk_db(tk_table.id > 0).select(tk_table.ticket_id, tk_table.created_datetime, orderby=~tk_table.created_datetime)
|
tickets_ = tk_db(tk_table.id > 0).select(tk_table.ticket_id, tk_table.created_datetime, orderby=~tk_table.created_datetime)
|
||||||
tickets = [row.ticket_id for row in tickets_]
|
tickets = [row.ticket_id for row in tickets_]
|
||||||
times = dict([(row.ticket_id, row.created_datetime) for row in tickets_])
|
times = dict(
|
||||||
|
[(row.ticket_id, row.created_datetime) for row in tickets_])
|
||||||
|
|
||||||
return dict(app=app, tickets=tickets, method=method, times=times)
|
return dict(app=app, tickets=tickets, method=method, times=times)
|
||||||
|
|
||||||
@@ -1425,14 +1485,16 @@ def errors():
|
|||||||
for item in request.vars:
|
for item in request.vars:
|
||||||
if item[:7] == 'delete_':
|
if item[:7] == 'delete_':
|
||||||
os.unlink(apath('%s/errors/%s' % (app, item[7:]), r=request))
|
os.unlink(apath('%s/errors/%s' % (app, item[7:]), r=request))
|
||||||
func = lambda p: os.stat(apath('%s/errors/%s' % \
|
func = lambda p: os.stat(apath('%s/errors/%s' %
|
||||||
(app, p), r=request)).st_mtime
|
(app, p), r=request)).st_mtime
|
||||||
tickets = sorted(listdir(apath('%s/errors/' % app, r=request), '^\w.*'),
|
tickets = sorted(
|
||||||
|
listdir(apath('%s/errors/' % app, r=request), '^\w.*'),
|
||||||
key=func,
|
key=func,
|
||||||
reverse=True)
|
reverse=True)
|
||||||
|
|
||||||
return dict(app=app, tickets=tickets, method=method, db_ready=db_ready)
|
return dict(app=app, tickets=tickets, method=method, db_ready=db_ready)
|
||||||
|
|
||||||
|
|
||||||
def get_ticket_storage(app):
|
def get_ticket_storage(app):
|
||||||
private_folder = apath('%s/private' % app, r=request)
|
private_folder = apath('%s/private' % app, r=request)
|
||||||
ticket_file = os.path.join(private_folder, 'ticket_storage.txt')
|
ticket_file = os.path.join(private_folder, 'ticket_storage.txt')
|
||||||
@@ -1454,6 +1516,7 @@ def get_ticket_storage(app):
|
|||||||
)
|
)
|
||||||
return ticketsdb, ticketsdb.get(tablename)
|
return ticketsdb, ticketsdb.get(tablename)
|
||||||
|
|
||||||
|
|
||||||
def make_link(path):
|
def make_link(path):
|
||||||
""" Create a link from a path """
|
""" Create a link from a path """
|
||||||
tryFile = path.replace('\\', '/')
|
tryFile = path.replace('\\', '/')
|
||||||
@@ -1536,6 +1599,7 @@ def ticket():
|
|||||||
layer=e.layer,
|
layer=e.layer,
|
||||||
myversion=myversion)
|
myversion=myversion)
|
||||||
|
|
||||||
|
|
||||||
def ticketdb():
|
def ticketdb():
|
||||||
""" Ticket handler """
|
""" Ticket handler """
|
||||||
|
|
||||||
@@ -1559,10 +1623,12 @@ def ticketdb():
|
|||||||
layer=e.layer,
|
layer=e.layer,
|
||||||
myversion=myversion)
|
myversion=myversion)
|
||||||
|
|
||||||
|
|
||||||
def error():
|
def error():
|
||||||
""" Generate a ticket (for testing) """
|
""" Generate a ticket (for testing) """
|
||||||
raise RuntimeError('admin ticket generator at your service')
|
raise RuntimeError('admin ticket generator at your service')
|
||||||
|
|
||||||
|
|
||||||
def update_languages():
|
def update_languages():
|
||||||
""" Update available languages """
|
""" Update available languages """
|
||||||
|
|
||||||
@@ -1600,12 +1666,14 @@ def user():
|
|||||||
else:
|
else:
|
||||||
return dict(form=T("Disabled"))
|
return dict(form=T("Disabled"))
|
||||||
|
|
||||||
|
|
||||||
def reload_routes():
|
def reload_routes():
|
||||||
""" Reload routes.py """
|
""" Reload routes.py """
|
||||||
import gluon.rewrite
|
import gluon.rewrite
|
||||||
gluon.rewrite.load()
|
gluon.rewrite.load()
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
|
|
||||||
|
|
||||||
def manage_students():
|
def manage_students():
|
||||||
if not (MULTI_USER_MODE and is_manager()):
|
if not (MULTI_USER_MODE and is_manager()):
|
||||||
session.flash = T('Not Authorized')
|
session.flash = T('Not Authorized')
|
||||||
@@ -1614,6 +1682,7 @@ def manage_students():
|
|||||||
grid = SQLFORM.grid(db.auth_user)
|
grid = SQLFORM.grid(db.auth_user)
|
||||||
return locals()
|
return locals()
|
||||||
|
|
||||||
|
|
||||||
def bulk_register():
|
def bulk_register():
|
||||||
if not (MULTI_USER_MODE and is_manager()):
|
if not (MULTI_USER_MODE and is_manager()):
|
||||||
session.flash = T('Not Authorized')
|
session.flash = T('Not Authorized')
|
||||||
@@ -1634,6 +1703,7 @@ def bulk_register():
|
|||||||
# 2) should not prompt user at console
|
# 2) should not prompt user at console
|
||||||
# 3) should give option to force commit and not reuqire manual merge
|
# 3) should give option to force commit and not reuqire manual merge
|
||||||
|
|
||||||
|
|
||||||
def git_pull():
|
def git_pull():
|
||||||
""" Git Pull handler """
|
""" Git Pull handler """
|
||||||
app = get_app()
|
app = get_app()
|
||||||
@@ -1660,10 +1730,12 @@ def git_pull():
|
|||||||
session.flash = T("Pull is not possible because you have unmerged files. Fix them up in the work tree, and then try again.")
|
session.flash = T("Pull is not possible because you have unmerged files. Fix them up in the work tree, and then try again.")
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
except GitCommandError, status:
|
except GitCommandError, status:
|
||||||
session.flash = T("Pull failed, git exited abnormally. See logs for details.")
|
session.flash = T(
|
||||||
|
"Pull failed, git exited abnormally. See logs for details.")
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
session.flash = T("Pull failed, git exited abnormally. See logs for details.")
|
session.flash = T(
|
||||||
|
"Pull failed, git exited abnormally. See logs for details.")
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
elif 'cancel' in request.vars:
|
elif 'cancel' in request.vars:
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
@@ -1688,13 +1760,14 @@ def git_push():
|
|||||||
new_commit = index.commit(form.vars.changelog)
|
new_commit = index.commit(form.vars.changelog)
|
||||||
origin = repo.remotes.origin
|
origin = repo.remotes.origin
|
||||||
origin.push()
|
origin.push()
|
||||||
session.flash = T("Git repo updated with latest application changes.")
|
session.flash = T(
|
||||||
|
"Git repo updated with latest application changes.")
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
except UnmergedEntriesError:
|
except UnmergedEntriesError:
|
||||||
session.flash = T("Push failed, there are unmerged entries in the cache. Resolve merge issues manually and try again.")
|
session.flash = T("Push failed, there are unmerged entries in the cache. Resolve merge issues manually and try again.")
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
session.flash = T("Push failed, git exited abnormally. See logs for details.")
|
session.flash = T(
|
||||||
|
"Push failed, git exited abnormally. See logs for details.")
|
||||||
redirect(URL('site'))
|
redirect(URL('site'))
|
||||||
return dict(app=app, form=form)
|
return dict(app=app, form=form)
|
||||||
|
|
||||||
|
|||||||
@@ -18,28 +18,34 @@ if MULTI_USER_MODE and not is_manager():
|
|||||||
|
|
||||||
forever = 10 ** 8
|
forever = 10 ** 8
|
||||||
|
|
||||||
|
|
||||||
def kill():
|
def kill():
|
||||||
p = cache.ram('gae_upload', lambda: None, forever)
|
p = cache.ram('gae_upload', lambda: None, forever)
|
||||||
if not p or p.poll()!=None:
|
if not p or p.poll() is not None:
|
||||||
return 'oops'
|
return 'oops'
|
||||||
os.kill(p.pid, signal.SIGKILL)
|
os.kill(p.pid, signal.SIGKILL)
|
||||||
cache.ram('gae_upload', lambda: None, -1)
|
cache.ram('gae_upload', lambda: None, -1)
|
||||||
|
|
||||||
|
|
||||||
class EXISTS(object):
|
class EXISTS(object):
|
||||||
def __init__(self, error_message='file not found'):
|
def __init__(self, error_message='file not found'):
|
||||||
self.error_message = error_message
|
self.error_message = error_message
|
||||||
|
|
||||||
def __call__(self, value):
|
def __call__(self, value):
|
||||||
if os.path.exists(value):
|
if os.path.exists(value):
|
||||||
return (value, None)
|
return (value, None)
|
||||||
return (value, self.error_message)
|
return (value, self.error_message)
|
||||||
|
|
||||||
|
|
||||||
def deploy():
|
def deploy():
|
||||||
regex = re.compile('^\w+$')
|
regex = re.compile('^\w+$')
|
||||||
apps = sorted(file for file in os.listdir(apath(r=request)) if regex.match(file))
|
apps = sorted(
|
||||||
|
file for file in os.listdir(apath(r=request)) if regex.match(file))
|
||||||
form = SQLFORM.factory(
|
form = SQLFORM.factory(
|
||||||
Field('appcfg', default=GAE_APPCFG, label=T('Path to appcfg.py'),
|
Field('appcfg', default=GAE_APPCFG, label=T('Path to appcfg.py'),
|
||||||
requires=EXISTS(error_message=T('file not found'))),
|
requires=EXISTS(error_message=T('file not found'))),
|
||||||
Field('google_application_id',requires=IS_MATCH('[\w\-]+'),label=T('Google Application Id')),
|
Field('google_application_id', requires=IS_MATCH(
|
||||||
|
'[\w\-]+'), label=T('Google Application Id')),
|
||||||
Field('applications', 'list:string',
|
Field('applications', 'list:string',
|
||||||
requires=IS_IN_SET(apps, multiple=True),
|
requires=IS_IN_SET(apps, multiple=True),
|
||||||
label=T('web2py apps to deploy')),
|
label=T('web2py apps to deploy')),
|
||||||
@@ -51,7 +57,7 @@ def deploy():
|
|||||||
kill()
|
kill()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
ignore_apps = [item for item in apps \
|
ignore_apps = [item for item in apps
|
||||||
if not item in form.vars.applications]
|
if not item in form.vars.applications]
|
||||||
regex = re.compile('\(applications/\(.*')
|
regex = re.compile('\(applications/\(.*')
|
||||||
yaml = apath('../app.yaml', r=request)
|
yaml = apath('../app.yaml', r=request)
|
||||||
@@ -59,8 +65,10 @@ def deploy():
|
|||||||
example = apath('../app.example.yaml', r=request)
|
example = apath('../app.example.yaml', r=request)
|
||||||
shutil.copyfile(example, yaml)
|
shutil.copyfile(example, yaml)
|
||||||
data = read_file(yaml)
|
data = read_file(yaml)
|
||||||
data = re.sub('application:.*','application: %s' % form.vars.google_application_id,data)
|
data = re.sub('application:.*', 'application: %s' %
|
||||||
data = regex.sub('(applications/(%s)/.*)|' % '|'.join(ignore_apps),data)
|
form.vars.google_application_id, data)
|
||||||
|
data = regex.sub(
|
||||||
|
'(applications/(%s)/.*)|' % '|'.join(ignore_apps), data)
|
||||||
write_file(yaml, data)
|
write_file(yaml, data)
|
||||||
|
|
||||||
path = request.env.applications_parent
|
path = request.env.applications_parent
|
||||||
@@ -76,9 +84,10 @@ def deploy():
|
|||||||
fcntl.fcntl(p.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
|
fcntl.fcntl(p.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
|
||||||
return dict(form=form, command=cmd)
|
return dict(form=form, command=cmd)
|
||||||
|
|
||||||
|
|
||||||
def callback():
|
def callback():
|
||||||
p = cache.ram('gae_upload', lambda: None, forever)
|
p = cache.ram('gae_upload', lambda: None, forever)
|
||||||
if not p or p.poll()!=None:
|
if not p or p.poll() is not None:
|
||||||
return '<done/>'
|
return '<done/>'
|
||||||
try:
|
try:
|
||||||
output = p.stdout.read()
|
output = p.stdout.read()
|
||||||
@@ -89,5 +98,3 @@ def callback():
|
|||||||
except:
|
except:
|
||||||
errors = ''
|
errors = ''
|
||||||
return (output + errors).replace('\n', '<br/>')
|
return (output + errors).replace('\n', '<br/>')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ sessions/*
|
|||||||
errors/*
|
errors/*
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def hg_repo(path):
|
def hg_repo(path):
|
||||||
import os
|
import os
|
||||||
uio = ui.ui()
|
uio = ui.ui()
|
||||||
@@ -37,6 +38,7 @@ def hg_repo(path):
|
|||||||
write_file(hgignore, _hgignore_content)
|
write_file(hgignore, _hgignore_content)
|
||||||
return repo
|
return repo
|
||||||
|
|
||||||
|
|
||||||
def commit():
|
def commit():
|
||||||
app = request.args(0)
|
app = request.args(0)
|
||||||
path = apath(app, r=request)
|
path = apath(app, r=request)
|
||||||
@@ -63,6 +65,7 @@ def commit():
|
|||||||
changes = []
|
changes = []
|
||||||
return dict(form=form, files=files, changes=changes, repo=repo)
|
return dict(form=form, files=files, changes=changes, repo=repo)
|
||||||
|
|
||||||
|
|
||||||
def revision():
|
def revision():
|
||||||
app = request.args(0)
|
app = request.args(0)
|
||||||
path = apath(app, r=request)
|
path = apath(app, r=request)
|
||||||
@@ -80,5 +83,3 @@ def revision():
|
|||||||
desc=ctx.description(),
|
desc=ctx.description(),
|
||||||
form=form
|
form=form
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
import os
|
import os
|
||||||
|
try:
|
||||||
from distutils import dir_util
|
from distutils import dir_util
|
||||||
|
except ImportError:
|
||||||
|
session.flash = T('requires distutils, but not installed')
|
||||||
|
redirect(URL('default', 'site'))
|
||||||
try:
|
try:
|
||||||
from git import *
|
from git import *
|
||||||
except ImportError:
|
except ImportError:
|
||||||
session.flash = T('requires python-git, but not installed')
|
session.flash = T('requires python-git, but not installed')
|
||||||
redirect(URL('default', 'site'))
|
redirect(URL('default', 'site'))
|
||||||
|
|
||||||
|
|
||||||
def deploy():
|
def deploy():
|
||||||
apps = sorted(file for file in os.listdir(apath(r=request)))
|
apps = sorted(file for file in os.listdir(apath(r=request)))
|
||||||
form = SQLFORM.factory(
|
form = SQLFORM.factory(
|
||||||
Field('osrepo',default='/tmp',label=T('Path to local openshift repo root.'),
|
Field(
|
||||||
|
'osrepo', default='/tmp', label=T('Path to local openshift repo root.'),
|
||||||
requires=EXISTS(error_message=T('directory not found'))),
|
requires=EXISTS(error_message=T('directory not found'))),
|
||||||
Field('osname', default='web2py', label=T('WSGI reference name')),
|
Field('osname', default='web2py', label=T('WSGI reference name')),
|
||||||
Field('applications', 'list:string',
|
Field('applications', 'list:string',
|
||||||
@@ -23,7 +29,8 @@ def deploy():
|
|||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
ignore_apps = [item for item in apps if not item in form.vars.applications]
|
ignore_apps = [
|
||||||
|
item for item in apps if not item in form.vars.applications]
|
||||||
regex = re.compile('\(applications/\(.*')
|
regex = re.compile('\(applications/\(.*')
|
||||||
w2p_origin = os.getcwd()
|
w2p_origin = os.getcwd()
|
||||||
osrepo = form.vars.osrepo
|
osrepo = form.vars.osrepo
|
||||||
@@ -47,9 +54,11 @@ def deploy():
|
|||||||
#Git code ends here
|
#Git code ends here
|
||||||
return dict(form=form, command=cmd)
|
return dict(form=form, command=cmd)
|
||||||
|
|
||||||
|
|
||||||
class EXISTS(object):
|
class EXISTS(object):
|
||||||
def __init__(self, error_message='file not found'):
|
def __init__(self, error_message='file not found'):
|
||||||
self.error_message = error_message
|
self.error_message = error_message
|
||||||
|
|
||||||
def __call__(self, value):
|
def __call__(self, value):
|
||||||
if os.path.exists(value):
|
if os.path.exists(value):
|
||||||
return (value, None)
|
return (value, None)
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
response.files = response.files[:3]
|
response.files = response.files[:3]
|
||||||
response.menu = []
|
response.menu = []
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
return locals()
|
return locals()
|
||||||
|
|
||||||
|
|
||||||
def about():
|
def about():
|
||||||
return locals()
|
return locals()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import sys
|
import sys
|
||||||
import cStringIO
|
import cStringIO
|
||||||
import gluon.contrib.shell
|
import gluon.contrib.shell
|
||||||
import code, thread
|
import code
|
||||||
|
import thread
|
||||||
from gluon.shell import env
|
from gluon.shell import env
|
||||||
|
|
||||||
if DEMO_MODE or MULTI_USER_MODE:
|
if DEMO_MODE or MULTI_USER_MODE:
|
||||||
@@ -10,16 +11,19 @@ if DEMO_MODE or MULTI_USER_MODE:
|
|||||||
|
|
||||||
FE = 10 ** 9
|
FE = 10 ** 9
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
app = request.args(0) or 'admin'
|
app = request.args(0) or 'admin'
|
||||||
reset()
|
reset()
|
||||||
return dict(app=app)
|
return dict(app=app)
|
||||||
|
|
||||||
|
|
||||||
def callback():
|
def callback():
|
||||||
app = request.args[0]
|
app = request.args[0]
|
||||||
command = request.vars.statement
|
command = request.vars.statement
|
||||||
escape = command[:1] != '!'
|
escape = command[:1] != '!'
|
||||||
history = session['history:'+app] = session.get('history:'+app,gluon.contrib.shell.History())
|
history = session['history:' + app] = session.get(
|
||||||
|
'history:' + app, gluon.contrib.shell.History())
|
||||||
if not escape:
|
if not escape:
|
||||||
command = command[1:]
|
command = command[1:]
|
||||||
if command == '%reset':
|
if command == '%reset':
|
||||||
@@ -31,17 +35,16 @@ def callback():
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
return ''
|
return ''
|
||||||
session['commands:' + app].append(command)
|
session['commands:' + app].append(command)
|
||||||
environ=env(app,True)
|
environ = env(app, True, extra_request=dict(is_https=request.is_https))
|
||||||
output = gluon.contrib.shell.run(history, command, environ)
|
output = gluon.contrib.shell.run(history, command, environ)
|
||||||
k = len(session['commands:' + app]) - 1
|
k = len(session['commands:' + app]) - 1
|
||||||
#output = PRE(output)
|
#output = PRE(output)
|
||||||
#return TABLE(TR('In[%i]:'%k,PRE(command)),TR('Out[%i]:'%k,output))
|
#return TABLE(TR('In[%i]:'%k,PRE(command)),TR('Out[%i]:'%k,output))
|
||||||
return 'In [%i] : %s%s\n' % (k + 1, command, output)
|
return 'In [%i] : %s%s\n' % (k + 1, command, output)
|
||||||
|
|
||||||
|
|
||||||
def reset():
|
def reset():
|
||||||
app = request.args(0) or 'admin'
|
app = request.args(0) or 'admin'
|
||||||
session['commands:' + app] = []
|
session['commands:' + app] = []
|
||||||
session['history:' + app] = gluon.contrib.shell.History()
|
session['history:' + app] = gluon.contrib.shell.History()
|
||||||
return 'done'
|
return 'done'
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,12 @@ import os
|
|||||||
from gluon.settings import global_settings, read_file
|
from gluon.settings import global_settings, read_file
|
||||||
#
|
#
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
app = request.args(0)
|
app = request.args(0)
|
||||||
return dict(app=app)
|
return dict(app=app)
|
||||||
|
|
||||||
|
|
||||||
def profiler():
|
def profiler():
|
||||||
"""
|
"""
|
||||||
to use the profiler start web2py with -F profiler.log
|
to use the profiler start web2py with -F profiler.log
|
||||||
@@ -27,5 +29,3 @@ def profiler():
|
|||||||
size += len(data)
|
size += len(data)
|
||||||
response.cookies[KEY] = size
|
response.cookies[KEY] = size
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ def install(app_name, filename, data, overwrite=True):
|
|||||||
|
|
||||||
return installed
|
return installed
|
||||||
|
|
||||||
|
|
||||||
@service.jsonrpc
|
@service.jsonrpc
|
||||||
def attach_debugger(host='localhost', port=6000, authkey='secret password'):
|
def attach_debugger(host='localhost', port=6000, authkey='secret password'):
|
||||||
import gluon.contrib.qdb as qdb
|
import gluon.contrib.qdb as qdb
|
||||||
@@ -124,7 +125,7 @@ def detach_debugger():
|
|||||||
gluon.debug.qdb_debugger = None
|
gluon.debug.qdb_debugger = None
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def call():
|
def call():
|
||||||
session.forget()
|
session.forget()
|
||||||
return service()
|
return service()
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
import os, uuid, re, pickle, urllib, glob
|
import os
|
||||||
|
import uuid
|
||||||
|
import re
|
||||||
|
import pickle
|
||||||
|
import urllib
|
||||||
|
import glob
|
||||||
from gluon.admin import app_create, plugin_install
|
from gluon.admin import app_create, plugin_install
|
||||||
from gluon.fileutils import abspath, read_file, write_file
|
from gluon.fileutils import abspath, read_file, write_file
|
||||||
|
|
||||||
|
|
||||||
def reset(session):
|
def reset(session):
|
||||||
session.app = {
|
session.app = {
|
||||||
'name': '',
|
'name': '',
|
||||||
@@ -30,16 +36,20 @@ def reset(session):
|
|||||||
'page_error': '# Error: the document does not exist',
|
'page_error': '# Error: the document does not exist',
|
||||||
}
|
}
|
||||||
|
|
||||||
if not session.app: reset(session)
|
if not session.app:
|
||||||
|
reset(session)
|
||||||
|
|
||||||
|
|
||||||
def listify(x):
|
def listify(x):
|
||||||
if not isinstance(x, (list, tuple)):
|
if not isinstance(x, (list, tuple)):
|
||||||
return x and [x] or []
|
return x and [x] or []
|
||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
def clean(name):
|
def clean(name):
|
||||||
return re.sub('\W+', '_', name.strip().lower())
|
return re.sub('\W+', '_', name.strip().lower())
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
response.view = 'wizard/step.html'
|
response.view = 'wizard/step.html'
|
||||||
reset(session)
|
reset(session)
|
||||||
@@ -49,11 +59,10 @@ def index():
|
|||||||
if form.accepts(request.vars):
|
if form.accepts(request.vars):
|
||||||
app = form.vars.name
|
app = form.vars.name
|
||||||
session.app['name'] = app
|
session.app['name'] = app
|
||||||
if MULTI_USER_MODE and db(db.app.name==app)\
|
if MULTI_USER_MODE and db(db.app.name == app)(db.app.owner != auth.user.id).count():
|
||||||
(db.app.owner!=auth.user.id).count():
|
|
||||||
session.flash = 'App belongs already to other user'
|
session.flash = 'App belongs already to other user'
|
||||||
elif app in apps:
|
elif app in apps:
|
||||||
meta = os.path.normpath(\
|
meta = os.path.normpath(
|
||||||
os.path.join(os.path.normpath(request.folder),
|
os.path.join(os.path.normpath(request.folder),
|
||||||
'..', app, 'wizard.metadata'))
|
'..', app, 'wizard.metadata'))
|
||||||
if os.path.exists(meta):
|
if os.path.exists(meta):
|
||||||
@@ -96,20 +105,26 @@ def step1():
|
|||||||
requires=IS_NOT_EMPTY()),
|
requires=IS_NOT_EMPTY()),
|
||||||
Field('subtitle', default=params.get('subtitle', None)),
|
Field('subtitle', default=params.get('subtitle', None)),
|
||||||
Field('author', default=params.get('author', None)),
|
Field('author', default=params.get('author', None)),
|
||||||
Field('author_email',default=params.get('author_email',None)),
|
Field(
|
||||||
|
'author_email', default=params.get('author_email', None)),
|
||||||
Field('keywords', default=params.get('keywords', None)),
|
Field('keywords', default=params.get('keywords', None)),
|
||||||
Field('description', 'text',
|
Field('description', 'text',
|
||||||
default=params.get('description', None)),
|
default=params.get('description', None)),
|
||||||
Field('layout_theme', requires=IS_IN_SET(themes),
|
Field('layout_theme', requires=IS_IN_SET(themes),
|
||||||
default=params.get('layout_theme', themes[0])),
|
default=params.get('layout_theme', themes[0])),
|
||||||
Field('database_uri',default=params.get('database_uri',None)),
|
Field(
|
||||||
Field('security_key',default=params.get('security_key',None)),
|
'database_uri', default=params.get('database_uri', None)),
|
||||||
Field('email_server',default=params.get('email_server',None)),
|
Field(
|
||||||
Field('email_sender',default=params.get('email_sender',None)),
|
'security_key', default=params.get('security_key', None)),
|
||||||
|
Field(
|
||||||
|
'email_server', default=params.get('email_server', None)),
|
||||||
|
Field(
|
||||||
|
'email_sender', default=params.get('email_sender', None)),
|
||||||
Field('email_login', default=params.get('email_login', None)),
|
Field('email_login', default=params.get('email_login', None)),
|
||||||
Field('login_method', requires=IS_IN_SET(('local', 'janrain')),
|
Field('login_method', requires=IS_IN_SET(('local', 'janrain')),
|
||||||
default=params.get('login_method', 'local')),
|
default=params.get('login_method', 'local')),
|
||||||
Field('login_config',default=params.get('login_config',None)),
|
Field(
|
||||||
|
'login_config', default=params.get('login_config', None)),
|
||||||
Field('plugins', 'list:string', requires=IS_IN_SET(plugins, multiple=True)))
|
Field('plugins', 'list:string', requires=IS_IN_SET(plugins, multiple=True)))
|
||||||
|
|
||||||
if form.accepts(request.vars):
|
if form.accepts(request.vars):
|
||||||
@@ -118,14 +133,15 @@ def step1():
|
|||||||
redirect(URL('step2'))
|
redirect(URL('step2'))
|
||||||
return dict(step='1: Setting Parameters', form=form)
|
return dict(step='1: Setting Parameters', form=form)
|
||||||
|
|
||||||
|
|
||||||
def step2():
|
def step2():
|
||||||
response.view = 'wizard/step.html'
|
response.view = 'wizard/step.html'
|
||||||
form = SQLFORM.factory(Field('table_names', 'list:string',
|
form = SQLFORM.factory(Field('table_names', 'list:string',
|
||||||
default=session.app['tables']))
|
default=session.app['tables']))
|
||||||
if form.accepts(request.vars):
|
if form.accepts(request.vars):
|
||||||
table_names = [clean(t) for t in listify(form.vars.table_names) \
|
table_names = [clean(t) for t in listify(form.vars.table_names)
|
||||||
if t.strip()]
|
if t.strip()]
|
||||||
if [t for t in table_names if t.startswith('auth_') and \
|
if [t for t in table_names if t.startswith('auth_') and
|
||||||
not t == 'auth_user']:
|
not t == 'auth_user']:
|
||||||
form.error.table_names = \
|
form.error.table_names = \
|
||||||
T('invalid table names (auth_* tables already defined)')
|
T('invalid table names (auth_* tables already defined)')
|
||||||
@@ -146,11 +162,13 @@ def step2():
|
|||||||
redirect(URL('step4'))
|
redirect(URL('step4'))
|
||||||
return dict(step='2: Tables', form=form)
|
return dict(step='2: Tables', form=form)
|
||||||
|
|
||||||
|
|
||||||
def step3():
|
def step3():
|
||||||
response.view = 'wizard/step.html'
|
response.view = 'wizard/step.html'
|
||||||
n = int(request.args(0) or 0)
|
n = int(request.args(0) or 0)
|
||||||
m = len(session.app['tables'])
|
m = len(session.app['tables'])
|
||||||
if n>=m: redirect(URL('step2'))
|
if n >= m:
|
||||||
|
redirect(URL('step2'))
|
||||||
table = session.app['tables'][n]
|
table = session.app['tables'][n]
|
||||||
form = SQLFORM.factory(Field('field_names', 'list:string',
|
form = SQLFORM.factory(Field('field_names', 'list:string',
|
||||||
default=session.app.get('table_' + table, [])))
|
default=session.app.get('table_' + table, [])))
|
||||||
@@ -172,9 +190,10 @@ def step3():
|
|||||||
redirect(URL('step3', args=n + 1))
|
redirect(URL('step3', args=n + 1))
|
||||||
else:
|
else:
|
||||||
redirect(URL('step4'))
|
redirect(URL('step4'))
|
||||||
return dict(step='3: Fields for table "%s" (%s of %s)' \
|
return dict(step='3: Fields for table "%s" (%s of %s)'
|
||||||
% (table, n + 1, m), table=table, form=form)
|
% (table, n + 1, m), table=table, form=form)
|
||||||
|
|
||||||
|
|
||||||
def step4():
|
def step4():
|
||||||
response.view = 'wizard/step.html'
|
response.view = 'wizard/step.html'
|
||||||
form = SQLFORM.factory(Field('pages', 'list:string',
|
form = SQLFORM.factory(Field('pages', 'list:string',
|
||||||
@@ -189,11 +208,13 @@ def step4():
|
|||||||
redirect(URL('step6'))
|
redirect(URL('step6'))
|
||||||
return dict(step='4: Pages', form=form)
|
return dict(step='4: Pages', form=form)
|
||||||
|
|
||||||
|
|
||||||
def step5():
|
def step5():
|
||||||
response.view = 'wizard/step.html'
|
response.view = 'wizard/step.html'
|
||||||
n = int(request.args(0) or 0)
|
n = int(request.args(0) or 0)
|
||||||
m = len(session.app['pages'])
|
m = len(session.app['pages'])
|
||||||
if n>=m: redirect(URL('step4'))
|
if n >= m:
|
||||||
|
redirect(URL('step4'))
|
||||||
page = session.app['pages'][n]
|
page = session.app['pages'][n]
|
||||||
markmin_url = 'http://web2py.com/examples/static/markmin.html'
|
markmin_url = 'http://web2py.com/examples/static/markmin.html'
|
||||||
form = SQLFORM.factory(Field('content', 'text',
|
form = SQLFORM.factory(Field('content', 'text',
|
||||||
@@ -209,6 +230,7 @@ def step5():
|
|||||||
redirect(URL('step6'))
|
redirect(URL('step6'))
|
||||||
return dict(step='5: View for page "%s" (%s of %s)' % (page, n + 1, m), form=form)
|
return dict(step='5: View for page "%s" (%s of %s)' % (page, n + 1, m), form=form)
|
||||||
|
|
||||||
|
|
||||||
def step6():
|
def step6():
|
||||||
response.view = 'wizard/step.html'
|
response.view = 'wizard/step.html'
|
||||||
params = dict(session.app['params'])
|
params = dict(session.app['params'])
|
||||||
@@ -230,9 +252,11 @@ def step6():
|
|||||||
redirect(URL('generated'))
|
redirect(URL('generated'))
|
||||||
return dict(step='6: Generate app "%s"' % app, form=form)
|
return dict(step='6: Generate app "%s"' % app, form=form)
|
||||||
|
|
||||||
|
|
||||||
def generated():
|
def generated():
|
||||||
return dict(app=session.app['name'])
|
return dict(app=session.app['name'])
|
||||||
|
|
||||||
|
|
||||||
def sort_tables(tables):
|
def sort_tables(tables):
|
||||||
import re
|
import re
|
||||||
regex = re.compile('(%s)' % '|'.join(tables))
|
regex = re.compile('(%s)' % '|'.join(tables))
|
||||||
@@ -245,6 +269,7 @@ def sort_tables(tables):
|
|||||||
tables = []
|
tables = []
|
||||||
if is_auth_user:
|
if is_auth_user:
|
||||||
tables.append('auth_user')
|
tables.append('auth_user')
|
||||||
|
|
||||||
def append(table, trail=[]):
|
def append(table, trail=[]):
|
||||||
if table in trail:
|
if table in trail:
|
||||||
raise RuntimeError
|
raise RuntimeError
|
||||||
@@ -253,12 +278,15 @@ def sort_tables(tables):
|
|||||||
append(t, trail=trail + [table])
|
append(t, trail=trail + [table])
|
||||||
if not table in tables:
|
if not table in tables:
|
||||||
tables.append(table)
|
tables.append(table)
|
||||||
for table in d: append(table)
|
for table in d:
|
||||||
|
append(table)
|
||||||
return tables
|
return tables
|
||||||
|
|
||||||
|
|
||||||
def make_table(table, fields):
|
def make_table(table, fields):
|
||||||
rawtable = table
|
rawtable = table
|
||||||
if table!='auth_user': table='t_'+table
|
if table != 'auth_user':
|
||||||
|
table = 't_' + table
|
||||||
s = ''
|
s = ''
|
||||||
s += '\n' + '#' * 40 + '\n'
|
s += '\n' + '#' * 40 + '\n'
|
||||||
s += "db.define_table('%s',\n" % table
|
s += "db.define_table('%s',\n" % table
|
||||||
@@ -277,11 +305,12 @@ def make_table(table,fields):
|
|||||||
has[key] = True
|
has[key] = True
|
||||||
tables = session.app['tables']
|
tables = session.app['tables']
|
||||||
refs = [t for t in tables if t in items]
|
refs = [t for t in tables if t in items]
|
||||||
items = items[:1] + [x for x in items[1:] \
|
items = items[:1] + [x for x in items[1:]
|
||||||
if not x in keys and not x in tables]
|
if not x in keys and not x in tables]
|
||||||
barename = name = '_'.join(items)
|
barename = name = '_'.join(items)
|
||||||
if table[:2] == 't_': name = 'f_' + name
|
if table[:2] == 't_': name = 'f_' + name
|
||||||
if first_field=='id': first_field=name
|
if first_field == 'id':
|
||||||
|
first_field = name
|
||||||
|
|
||||||
### determine field type
|
### determine field type
|
||||||
ftype = 'string'
|
ftype = 'string'
|
||||||
@@ -295,7 +324,8 @@ def make_table(table,fields):
|
|||||||
ftype = t
|
ftype = t
|
||||||
if refs:
|
if refs:
|
||||||
key = refs[0]
|
key = refs[0]
|
||||||
if not key=='auth_user': key='t_'+key
|
if not key == 'auth_user':
|
||||||
|
key = 't_' + key
|
||||||
if 'multiple' in has:
|
if 'multiple' in has:
|
||||||
ftype = 'list:reference %s' % key
|
ftype = 'list:reference %s' % key
|
||||||
else:
|
else:
|
||||||
@@ -352,17 +382,22 @@ def make_table(table,fields):
|
|||||||
s += " migrate=settings.migrate)\n\n"
|
s += " migrate=settings.migrate)\n\n"
|
||||||
if table == 'auth_user':
|
if table == 'auth_user':
|
||||||
s += """
|
s += """
|
||||||
db.auth_user.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
|
db.auth_user.first_name.requires = IS_NOT_EMPTY(
|
||||||
db.auth_user.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
|
error_message=auth.messages.is_empty)
|
||||||
db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key, min_length=4)
|
db.auth_user.last_name.requires = IS_NOT_EMPTY(
|
||||||
|
error_message=auth.messages.is_empty)
|
||||||
|
db.auth_user.password.requires = CRYPT(
|
||||||
|
key=auth.settings.hmac_key, min_length=4)
|
||||||
db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username)
|
db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username)
|
||||||
db.auth_user.email.requires = (IS_EMAIL(error_message=auth.messages.invalid_email),
|
db.auth_user.email.requires = (
|
||||||
|
IS_EMAIL(error_message=auth.messages.invalid_email),
|
||||||
IS_NOT_IN_DB(db, db.auth_user.email))
|
IS_NOT_IN_DB(db, db.auth_user.email))
|
||||||
"""
|
"""
|
||||||
else:
|
else:
|
||||||
s += "db.define_table('%s_archive',db.%s,Field('current_record','reference %s',readable=False,writable=False))\n" % (table, table, table)
|
s += "db.define_table('%s_archive',db.%s,Field('current_record','reference %s',readable=False,writable=False))\n" % (table, table, table)
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def fix_db(filename):
|
def fix_db(filename):
|
||||||
params = dict(session.app['params'])
|
params = dict(session.app['params'])
|
||||||
content = read_file(filename, 'rb')
|
content = read_file(filename, 'rb')
|
||||||
@@ -370,7 +405,7 @@ def fix_db(filename):
|
|||||||
auth_user = make_table('auth_user', session.app['table_auth_user'])
|
auth_user = make_table('auth_user', session.app['table_auth_user'])
|
||||||
content = content.replace('sqlite://storage.sqlite',
|
content = content.replace('sqlite://storage.sqlite',
|
||||||
params['database_uri'])
|
params['database_uri'])
|
||||||
content = content.replace('auth.define_tables()',\
|
content = content.replace('auth.define_tables()',
|
||||||
auth_user + 'auth.define_tables(migrate = settings.migrate)')
|
auth_user + 'auth.define_tables(migrate = settings.migrate)')
|
||||||
content += """
|
content += """
|
||||||
mail.settings.server = settings.email_server
|
mail.settings.server = settings.email_server
|
||||||
@@ -380,7 +415,8 @@ mail.settings.login = settings.email_login
|
|||||||
if params['login_method'] == 'janrain':
|
if params['login_method'] == 'janrain':
|
||||||
content += """
|
content += """
|
||||||
from gluon.contrib.login_methods.rpx_account import RPXAccount
|
from gluon.contrib.login_methods.rpx_account import RPXAccount
|
||||||
auth.settings.actions_disabled=['register','change_password','request_reset_password']
|
auth.settings.actions_disabled=['register','change_password',
|
||||||
|
'request_reset_password']
|
||||||
auth.settings.login_form = RPXAccount(request,
|
auth.settings.login_form = RPXAccount(request,
|
||||||
api_key = settings.login_config.split(':')[-1],
|
api_key = settings.login_config.split(':')[-1],
|
||||||
domain = settings.login_config.split(':')[0],
|
domain = settings.login_config.split(':')[0],
|
||||||
@@ -388,6 +424,7 @@ auth.settings.login_form = RPXAccount(request,
|
|||||||
"""
|
"""
|
||||||
write_file(filename, content, 'wb')
|
write_file(filename, content, 'wb')
|
||||||
|
|
||||||
|
|
||||||
def make_menu(pages):
|
def make_menu(pages):
|
||||||
s = ''
|
s = ''
|
||||||
s += 'response.title = settings.title\n'
|
s += 'response.title = settings.title\n'
|
||||||
@@ -408,6 +445,7 @@ def make_menu(pages):
|
|||||||
s += ']'
|
s += ']'
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def make_page(page, contents):
|
def make_page(page, contents):
|
||||||
if 'auth_user' in session.app['tables'] and not page in ('index', 'error'):
|
if 'auth_user' in session.app['tables'] and not page in ('index', 'error'):
|
||||||
s = "@auth.requires_login()\ndef %s():\n" % page
|
s = "@auth.requires_login()\ndef %s():\n" % page
|
||||||
@@ -421,11 +459,13 @@ def make_page(page,contents):
|
|||||||
s += " return dict()\n\n"
|
s += " return dict()\n\n"
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def make_view(page, contents):
|
def make_view(page, contents):
|
||||||
s = "{{extend 'layout.html'}}\n\n"
|
s = "{{extend 'layout.html'}}\n\n"
|
||||||
s += str(MARKMIN(contents))
|
s += str(MARKMIN(contents))
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def populate(tables):
|
def populate(tables):
|
||||||
s = 'from gluon.contrib.populate import populate\n'
|
s = 'from gluon.contrib.populate import populate\n'
|
||||||
s += 'if db(db.auth_user).isempty():\n'
|
s += 'if db(db.auth_user).isempty():\n'
|
||||||
@@ -434,6 +474,7 @@ def populate(tables):
|
|||||||
s += " populate(db.%s,10)\n" % t
|
s += " populate(db.%s,10)\n" % t
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def create(options):
|
def create(options):
|
||||||
if DEMO_MODE:
|
if DEMO_MODE:
|
||||||
session.flash = T('disabled in demo mode')
|
session.flash = T('disabled in demo mode')
|
||||||
@@ -461,7 +502,8 @@ def create(options):
|
|||||||
if options.apply_layout and params['layout_theme'] != 'Default':
|
if options.apply_layout and params['layout_theme'] != 'Default':
|
||||||
try:
|
try:
|
||||||
fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme']
|
fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme']
|
||||||
theme = urllib.urlopen(LAYOUTS_APP+'/static/plugin_layouts/plugins/'+fn)
|
theme = urllib.urlopen(
|
||||||
|
LAYOUTS_APP + '/static/plugin_layouts/plugins/' + fn)
|
||||||
plugin_install(app, theme, request, fn)
|
plugin_install(app, theme, request, fn)
|
||||||
except:
|
except:
|
||||||
session.flash = T("unable to download layout")
|
session.flash = T("unable to download layout")
|
||||||
@@ -502,20 +544,23 @@ def create(options):
|
|||||||
|
|
||||||
### create newapp/models/db_wizard.py
|
### create newapp/models/db_wizard.py
|
||||||
if options.generate_model:
|
if options.generate_model:
|
||||||
model = os.path.join(request.folder,'..',app,'models','db_wizard.py')
|
model = os.path.join(
|
||||||
|
request.folder, '..', app, 'models', 'db_wizard.py')
|
||||||
file = open(model, 'wb')
|
file = open(model, 'wb')
|
||||||
try:
|
try:
|
||||||
file.write('### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n')
|
file.write('### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n')
|
||||||
tables = sort_tables(session.app['tables'])
|
tables = sort_tables(session.app['tables'])
|
||||||
for table in tables:
|
for table in tables:
|
||||||
if table=='auth_user': continue
|
if table == 'auth_user':
|
||||||
|
continue
|
||||||
file.write(make_table(table, session.app['table_' + table]))
|
file.write(make_table(table, session.app['table_' + table]))
|
||||||
finally:
|
finally:
|
||||||
file.close()
|
file.close()
|
||||||
|
|
||||||
model = os.path.join(request.folder, '..', app,
|
model = os.path.join(request.folder, '..', app,
|
||||||
'models', 'db_wizard_populate.py')
|
'models', 'db_wizard_populate.py')
|
||||||
if os.path.exists(model): os.unlink(model)
|
if os.path.exists(model):
|
||||||
|
os.unlink(model)
|
||||||
if options.populate_database and session.app['tables']:
|
if options.populate_database and session.app['tables']:
|
||||||
file = open(model, 'wb')
|
file = open(model, 'wb')
|
||||||
try:
|
try:
|
||||||
@@ -525,7 +570,8 @@ def create(options):
|
|||||||
|
|
||||||
### create newapp/controllers/default.py
|
### create newapp/controllers/default.py
|
||||||
if options.generate_controller:
|
if options.generate_controller:
|
||||||
controller = os.path.join(request.folder,'..',app,'controllers','default.py')
|
controller = os.path.join(
|
||||||
|
request.folder, '..', app, 'controllers', 'default.py')
|
||||||
file = open(controller, 'wb')
|
file = open(controller, 'wb')
|
||||||
try:
|
try:
|
||||||
file.write("""# -*- coding: utf-8 -*-
|
file.write("""# -*- coding: utf-8 -*-
|
||||||
@@ -536,17 +582,20 @@ def call(): return service()
|
|||||||
### end requires
|
### end requires
|
||||||
""")
|
""")
|
||||||
for page in session.app['pages']:
|
for page in session.app['pages']:
|
||||||
file.write(make_page(page,session.app.get('page_'+page,'')))
|
file.write(
|
||||||
|
make_page(page, session.app.get('page_' + page, '')))
|
||||||
finally:
|
finally:
|
||||||
file.close()
|
file.close()
|
||||||
|
|
||||||
### create newapp/views/default/*.html
|
### create newapp/views/default/*.html
|
||||||
if options.generate_views:
|
if options.generate_views:
|
||||||
for page in session.app['pages']:
|
for page in session.app['pages']:
|
||||||
view = os.path.join(request.folder,'..',app,'views','default',page+'.html')
|
view = os.path.join(
|
||||||
|
request.folder, '..', app, 'views', 'default', page + '.html')
|
||||||
file = open(view, 'wb')
|
file = open(view, 'wb')
|
||||||
try:
|
try:
|
||||||
file.write(make_view(page,session.app.get('page_'+page,'')))
|
file.write(
|
||||||
|
make_view(page, session.app.get('page_' + page, '')))
|
||||||
finally:
|
finally:
|
||||||
file.close()
|
file.close()
|
||||||
|
|
||||||
@@ -554,5 +603,3 @@ def call(): return service()
|
|||||||
path = os.path.join(request.folder, '..', app, 'databases', '*')
|
path = os.path.join(request.folder, '..', app, 'databases', '*')
|
||||||
for file in glob.glob(path):
|
for file in glob.glob(path):
|
||||||
os.unlink(file)
|
os.unlink(file)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,5 +19,3 @@ for filename in os.listdir(path):
|
|||||||
os.unlink(fullpath)
|
os.unlink(fullpath)
|
||||||
except:
|
except:
|
||||||
logging.exception('failure to check %s' % fullpath)
|
logging.exception('failure to check %s' % fullpath)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -34,10 +34,12 @@
|
|||||||
'App does not exist or your are not authorized': 'Додаток не існує, або ви не авторизовані',
|
'App does not exist or your are not authorized': 'Додаток не існує, або ви не авторизовані',
|
||||||
'appadmin': 'Aдм.панель',
|
'appadmin': 'Aдм.панель',
|
||||||
'appadmin is disabled because insecure channel': "адмін.панель відключено через використання ненадійного каналу зв'язку",
|
'appadmin is disabled because insecure channel': "адмін.панель відключено через використання ненадійного каналу зв'язку",
|
||||||
|
'Application': 'Додаток (Application)',
|
||||||
'application "%s" uninstalled': 'додаток "%s" вилучено',
|
'application "%s" uninstalled': 'додаток "%s" вилучено',
|
||||||
'application %(appname)s installed with md5sum: %(digest)s': 'додаток %(appname)s встановлено з md5sum: %(digest)s',
|
'application %(appname)s installed with md5sum: %(digest)s': 'додаток %(appname)s встановлено з md5sum: %(digest)s',
|
||||||
'Application cannot be generated in demo mode': 'В демо-режимі генерувати додатки не можна',
|
'Application cannot be generated in demo mode': 'В демо-режимі генерувати додатки не можна',
|
||||||
'application compiled': 'додаток скомпільовано',
|
'application compiled': 'додаток скомпільовано',
|
||||||
|
'Application exists already': 'Додаток вже існує',
|
||||||
'application is compiled and cannot be designed': 'додаток скомпільований. налаштування змінювати не можна',
|
'application is compiled and cannot be designed': 'додаток скомпільований. налаштування змінювати не можна',
|
||||||
'Application name:': 'Назва додатку:',
|
'Application name:': 'Назва додатку:',
|
||||||
'are not used': 'не використовуються',
|
'are not used': 'не використовуються',
|
||||||
@@ -160,6 +162,7 @@
|
|||||||
'Error snapshot': 'Розгорнутий знімок стану (Error snapshot)',
|
'Error snapshot': 'Розгорнутий знімок стану (Error snapshot)',
|
||||||
'Error ticket': 'Позначка (ticket) про помилку',
|
'Error ticket': 'Позначка (ticket) про помилку',
|
||||||
'Errors': 'Помилки',
|
'Errors': 'Помилки',
|
||||||
|
'Errors in form, please check it out.': 'Помилка у формі, будь-ласка перевірте її.',
|
||||||
'Exception %(extype)s: %(exvalue)s': 'Виключення %(extype)s: %(exvalue)s',
|
'Exception %(extype)s: %(exvalue)s': 'Виключення %(extype)s: %(exvalue)s',
|
||||||
'Exception %s': 'Виключення %s',
|
'Exception %s': 'Виключення %s',
|
||||||
'Exception instance attributes': 'Атрибути примірника класу Exception (виключення)',
|
'Exception instance attributes': 'Атрибути примірника класу Exception (виключення)',
|
||||||
@@ -388,6 +391,7 @@
|
|||||||
'There are no models': 'Моделей, наразі, нема',
|
'There are no models': 'Моделей, наразі, нема',
|
||||||
'There are no modules': 'Модулів поки що нема',
|
'There are no modules': 'Модулів поки що нема',
|
||||||
'There are no plugins': 'Жодної втулки, наразі, не встановлено',
|
'There are no plugins': 'Жодної втулки, наразі, не встановлено',
|
||||||
|
'There are no private files': 'Приватних файлів поки що нема',
|
||||||
'There are no static files': 'Статичних файлів, наразі, нема',
|
'There are no static files': 'Статичних файлів, наразі, нема',
|
||||||
'There are no translators': 'Перекладів нема',
|
'There are no translators': 'Перекладів нема',
|
||||||
'There are no translators, only default language is supported': 'Перекладів нема, підтримується тільки мова оригіналу',
|
'There are no translators, only default language is supported': 'Перекладів нема, підтримується тільки мова оригіналу',
|
||||||
@@ -418,6 +422,7 @@
|
|||||||
'Traceback': 'Стек викликів (Traceback)',
|
'Traceback': 'Стек викликів (Traceback)',
|
||||||
'Translation strings for the application': 'Пари рядків <оригінал>:<переклад> для вибраної мови',
|
'Translation strings for the application': 'Пари рядків <оригінал>:<переклад> для вибраної мови',
|
||||||
'try something like': 'спробуйте щось схоже на',
|
'try something like': 'спробуйте щось схоже на',
|
||||||
|
'Try the mobile interface': 'Спробуйте мобільний інтерфейс',
|
||||||
'try view': 'дивитись результат',
|
'try view': 'дивитись результат',
|
||||||
'Type PDB debugger command in here and hit Return (Enter) to execute it.': 'наберіть тут будь-які команди ладнача PDB і натисніть клавішу [Return] ([Enter]), щоб запустити їх на виконання.',
|
'Type PDB debugger command in here and hit Return (Enter) to execute it.': 'наберіть тут будь-які команди ладнача PDB і натисніть клавішу [Return] ([Enter]), щоб запустити їх на виконання.',
|
||||||
'Type python statement in here and hit Return (Enter) to execute it.': 'Наберіть тут будь-які вирази Python і натисніть клавішу [Return] ([Enter]), щоб запустити їх на виконання.',
|
'Type python statement in here and hit Return (Enter) to execute it.': 'Наберіть тут будь-які вирази Python і натисніть клавішу [Return] ([Enter]), щоб запустити їх на виконання.',
|
||||||
@@ -463,7 +468,7 @@
|
|||||||
'Views': 'Відображення (Views)',
|
'Views': 'Відображення (Views)',
|
||||||
'views': 'відображення',
|
'views': 'відображення',
|
||||||
'WARNING:': 'ПОПЕРЕДЖЕННЯ:',
|
'WARNING:': 'ПОПЕРЕДЖЕННЯ:',
|
||||||
'Web Framework': 'Web Framework',
|
'Web Framework': 'Веб-каркас (Web Framework)',
|
||||||
'web2py apps to deploy': 'Готові до розгортання додатки web2py',
|
'web2py apps to deploy': 'Готові до розгортання додатки web2py',
|
||||||
'web2py Debugger': 'Ладнач web2py',
|
'web2py Debugger': 'Ладнач web2py',
|
||||||
'web2py downgrade': 'повернення на попередню версію web2py',
|
'web2py downgrade': 'повернення на попередню версію web2py',
|
||||||
|
|||||||
@@ -78,5 +78,3 @@ PLUGINS_APP = 'http://web2py.com/plugins'
|
|||||||
# set the language
|
# set the language
|
||||||
if 'adminLanguage' in request.cookies and not (request.cookies['adminLanguage'] is None):
|
if 'adminLanguage' in request.cookies and not (request.cookies['adminLanguage'] is None):
|
||||||
T.force(request.cookies['adminLanguage'].value)
|
T.force(request.cookies['adminLanguage'].value)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -28,5 +28,3 @@ from gluon.languages import findT, update_all_languages
|
|||||||
from gluon.myregex import *
|
from gluon.myregex import *
|
||||||
from gluon.restricted import *
|
from gluon.restricted import *
|
||||||
from gluon.compileapp import compile_application, remove_compiled_application
|
from gluon.compileapp import compile_application, remove_compiled_application
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import base64, os, time
|
import base64
|
||||||
|
import os
|
||||||
|
import time
|
||||||
from gluon import portalocker
|
from gluon import portalocker
|
||||||
from gluon.admin import apath
|
from gluon.admin import apath
|
||||||
from gluon.fileutils import read_file
|
from gluon.fileutils import read_file
|
||||||
@@ -24,7 +26,8 @@ elif not request.is_local and not DEMO_MODE:
|
|||||||
try:
|
try:
|
||||||
_config = {}
|
_config = {}
|
||||||
port = int(request.env.server_port or 0)
|
port = int(request.env.server_port or 0)
|
||||||
restricted(read_file(apath('../parameters_%i.py' % port, request)), _config)
|
restricted(
|
||||||
|
read_file(apath('../parameters_%i.py' % port, request)), _config)
|
||||||
|
|
||||||
if not 'password' in _config or not _config['password']:
|
if not 'password' in _config or not _config['password']:
|
||||||
raise HTTP(200, T('admin disabled because no admin password'))
|
raise HTTP(200, T('admin disabled because no admin password'))
|
||||||
@@ -38,7 +41,8 @@ except IOError:
|
|||||||
raise HTTP(200,
|
raise HTTP(200,
|
||||||
T('admin disabled because not supported on google app engine'))
|
T('admin disabled because not supported on google app engine'))
|
||||||
else:
|
else:
|
||||||
raise HTTP(200, T('admin disabled because unable to access password file'))
|
raise HTTP(
|
||||||
|
200, T('admin disabled because unable to access password file'))
|
||||||
|
|
||||||
|
|
||||||
def verify_password(password):
|
def verify_password(password):
|
||||||
@@ -63,6 +67,7 @@ deny_file = os.path.join(request.folder, 'private', 'hosts.deny')
|
|||||||
allowed_number_of_attempts = 5
|
allowed_number_of_attempts = 5
|
||||||
expiration_failed_logins = 3600
|
expiration_failed_logins = 3600
|
||||||
|
|
||||||
|
|
||||||
def read_hosts_deny():
|
def read_hosts_deny():
|
||||||
import datetime
|
import datetime
|
||||||
hosts = {}
|
hosts = {}
|
||||||
@@ -83,6 +88,7 @@ def read_hosts_deny():
|
|||||||
f.close()
|
f.close()
|
||||||
return hosts
|
return hosts
|
||||||
|
|
||||||
|
|
||||||
def write_hosts_deny(denied_hosts):
|
def write_hosts_deny(denied_hosts):
|
||||||
f = open(deny_file, 'w')
|
f = open(deny_file, 'w')
|
||||||
portalocker.lock(f, portalocker.LOCK_EX)
|
portalocker.lock(f, portalocker.LOCK_EX)
|
||||||
@@ -93,6 +99,7 @@ def write_hosts_deny(denied_hosts):
|
|||||||
portalocker.unlock(f)
|
portalocker.unlock(f)
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
|
|
||||||
def login_record(success=True):
|
def login_record(success=True):
|
||||||
denied_hosts = read_hosts_deny()
|
denied_hosts = read_hosts_deny()
|
||||||
val = (0, 0)
|
val = (0, 0)
|
||||||
@@ -168,4 +175,3 @@ elif session.authorized and \
|
|||||||
if request.controller == 'appadmin' and DEMO_MODE:
|
if request.controller == 'appadmin' and DEMO_MODE:
|
||||||
session.flash = 'Appadmin disabled in demo mode'
|
session.flash = 'Appadmin disabled in demo mode'
|
||||||
redirect(URL('default', 'sites'))
|
redirect(URL('default', 'sites'))
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
def A_button(*a, **b):
|
def A_button(*a, **b):
|
||||||
b['_data-role'] = 'button'
|
b['_data-role'] = 'button'
|
||||||
b['_data-inline'] = 'true'
|
b['_data-inline'] = 'true'
|
||||||
return A(*a, **b)
|
return A(*a, **b)
|
||||||
|
|
||||||
|
|
||||||
def button(href, label):
|
def button(href, label):
|
||||||
if is_mobile:
|
if is_mobile:
|
||||||
ret = A_button(SPAN(label), _href=href)
|
ret = A_button(SPAN(label), _href=href)
|
||||||
@@ -14,6 +16,7 @@ def button(href, label):
|
|||||||
ret = A(SPAN(label), _class='button', _href=href)
|
ret = A(SPAN(label), _class='button', _href=href)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
def button_enable(href, app):
|
def button_enable(href, app):
|
||||||
if os.path.exists(os.path.join(apath(app, r=request), 'DISABLED')):
|
if os.path.exists(os.path.join(apath(app, r=request), 'DISABLED')):
|
||||||
label = SPAN(T('Enable'), _style='color:red')
|
label = SPAN(T('Enable'), _style='color:red')
|
||||||
@@ -22,6 +25,7 @@ def button_enable(href, app):
|
|||||||
id = 'enable_' + app
|
id = 'enable_' + app
|
||||||
return A(label, _class='button', _id=id, callback=href, target=id)
|
return A(label, _class='button', _id=id, callback=href, target=id)
|
||||||
|
|
||||||
|
|
||||||
def sp_button(href, label):
|
def sp_button(href, label):
|
||||||
if request.user_agent().is_mobile:
|
if request.user_agent().is_mobile:
|
||||||
ret = A_button(SPAN(label), _href=href)
|
ret = A_button(SPAN(label), _href=href)
|
||||||
@@ -29,10 +33,10 @@ def sp_button(href, label):
|
|||||||
ret = A(SPAN(label), _class='button special', _href=href)
|
ret = A(SPAN(label), _class='button special', _href=href)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
def helpicon():
|
def helpicon():
|
||||||
return IMG(_src=URL('static', 'images/help.png'), _alt='help')
|
return IMG(_src=URL('static', 'images/help.png'), _alt='help')
|
||||||
|
|
||||||
|
|
||||||
def searchbox(elementid):
|
def searchbox(elementid):
|
||||||
return TAG[''](LABEL(IMG(_id="search_start", _src=URL('static', 'images/search.png'), _alt=T('filter')), _class='icon', _for=elementid), ' ', INPUT(_id=elementid, _type='text', _size=12))
|
return TAG[''](LABEL(IMG(_id="search_start", _src=URL('static', 'images/search.png'), _alt=T('filter')), _class='icon', _for=elementid), ' ', INPUT(_id=elementid, _type='text', _size=12))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,12 @@
|
|||||||
if MULTI_USER_MODE:
|
if MULTI_USER_MODE:
|
||||||
db = DAL('sqlite://storage.sqlite') # if not, use SQLite or other DB
|
db = DAL('sqlite://storage.sqlite') # if not, use SQLite or other DB
|
||||||
from gluon.tools import *
|
from gluon.tools import *
|
||||||
auth = Auth(globals(),db) # authentication/authorization
|
auth = Auth(
|
||||||
crud = Crud(globals(),db) # for CRUD helpers using auth
|
globals(), db) # authentication/authorization
|
||||||
service = Service(globals()) # for json, xml, jsonrpc, xmlrpc, amfrpc
|
crud = Crud(
|
||||||
|
globals(), db) # for CRUD helpers using auth
|
||||||
|
service = Service(
|
||||||
|
globals()) # for json, xml, jsonrpc, xmlrpc, amfrpc
|
||||||
plugins = PluginManager()
|
plugins = PluginManager()
|
||||||
|
|
||||||
mail = auth.settings.mailer
|
mail = auth.settings.mailer
|
||||||
@@ -29,6 +32,7 @@ if not session.authorized and MULTI_USER_MODE:
|
|||||||
elif not request.function == 'user':
|
elif not request.function == 'user':
|
||||||
redirect(URL('default', 'user/login'))
|
redirect(URL('default', 'user/login'))
|
||||||
|
|
||||||
|
|
||||||
def is_manager():
|
def is_manager():
|
||||||
if not MULTI_USER_MODE:
|
if not MULTI_USER_MODE:
|
||||||
return True
|
return True
|
||||||
@@ -36,5 +40,3 @@ def is_manager():
|
|||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -30,8 +30,7 @@ else:
|
|||||||
URL(_a, 'debug', 'interact')))
|
URL(_a, 'debug', 'interact')))
|
||||||
|
|
||||||
if os.path.exists('applications/examples'):
|
if os.path.exists('applications/examples'):
|
||||||
response.menu.append((T('Help'), False, URL('examples','default','index')))
|
response.menu.append(
|
||||||
|
(T('Help'), False, URL('examples', 'default', 'index')))
|
||||||
else:
|
else:
|
||||||
response.menu.append((T('Help'), False, 'http://web2py.com/examples'))
|
response.menu.append((T('Help'), False, 'http://web2py.com/examples'))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
response.files.append(URL('static','plugin_multiselect/jquery.multi-select.js'))
|
response.files.append(
|
||||||
|
URL('static', 'plugin_multiselect/jquery.multi-select.js'))
|
||||||
response.files.append(URL('static', 'plugin_multiselect/multi-select.css'))
|
response.files.append(URL('static', 'plugin_multiselect/multi-select.css'))
|
||||||
response.files.append(URL('static', 'plugin_multiselect/start.js'))
|
response.files.append(URL('static', 'plugin_multiselect/start.js'))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,2 +1 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ input[type=text],input[type=password],select{width:300px; margin-right:5px}
|
|||||||
border-top:1px #DEDEDE solid;
|
border-top:1px #DEDEDE solid;
|
||||||
}
|
}
|
||||||
.header {
|
.header {
|
||||||
// background:<fill here for header image>;
|
/* background:<fill here for header image>; */
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -115,6 +115,10 @@ div.flash {
|
|||||||
z-index:2000;
|
z-index:2000;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
div.flash #closeflash{color:inherit; float:right; margin-left:15px;}
|
||||||
|
.ie-lte7 div.flash #closeflash
|
||||||
|
{color:expression(this.parentNode.currentStyle['color']);float:none;position:absolute;right:4px;}
|
||||||
|
|
||||||
div.flash:hover { opacity:0.25; }
|
div.flash:hover { opacity:0.25; }
|
||||||
|
|
||||||
div.error_wrapper {display:block}
|
div.error_wrapper {display:block}
|
||||||
@@ -182,7 +186,7 @@ div.error {
|
|||||||
* will look better with the declarations below
|
* will look better with the declarations below
|
||||||
* if needed to remove base.css consider keeping these following lines in some css file.
|
* if needed to remove base.css consider keeping these following lines in some css file.
|
||||||
*/
|
*/
|
||||||
// .web2py_table {border:1px solid #ccc}
|
/* .web2py_table {border:1px solid #ccc} */
|
||||||
.web2py_paginator {}
|
.web2py_paginator {}
|
||||||
.web2py_grid {width:100%}
|
.web2py_grid {width:100%}
|
||||||
.web2py_grid table {width:100%}
|
.web2py_grid table {width:100%}
|
||||||
|
|||||||
+2
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -55,7 +55,7 @@ function web2py_event_handlers() {
|
|||||||
jQuery(function() {
|
jQuery(function() {
|
||||||
var flash = jQuery('.flash');
|
var flash = jQuery('.flash');
|
||||||
flash.hide();
|
flash.hide();
|
||||||
if(flash.html()) flash.append('<span style="float:right;">×</span>').slideDown();
|
if(flash.html()) flash.append('<span id="closeflash">×</span>').slideDown();
|
||||||
web2py_ajax_init(document);
|
web2py_ajax_init(document);
|
||||||
web2py_event_handlers();
|
web2py_event_handlers();
|
||||||
});
|
});
|
||||||
@@ -102,15 +102,20 @@ function web2py_ajax_page(method, action, data, target) {
|
|||||||
web2py_ajax_init('#'+target);
|
web2py_ajax_init('#'+target);
|
||||||
if(command)
|
if(command)
|
||||||
eval(decodeURIComponent(command));
|
eval(decodeURIComponent(command));
|
||||||
if(flash)
|
if(flash) {
|
||||||
jQuery('.flash').html(decodeURIComponent(flash)).slideDown();
|
jQuery('.flash')
|
||||||
|
.html(decodeURIComponent(flash))
|
||||||
|
.append('<span id="closeflash">×</span>')
|
||||||
|
.slideDown();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function web2py_component(action, target, timeout, times){
|
function web2py_component(action, target, timeout, times){
|
||||||
jQuery(function(){
|
jQuery(function(){
|
||||||
var element = jQuery("#" + target).get(0);
|
var jelement = jQuery("#" + target);
|
||||||
|
var element = jelement.get(0);
|
||||||
var statement = "jQuery('#" + target + "').get(0).reload();";
|
var statement = "jQuery('#" + target + "').get(0).reload();";
|
||||||
element.reload = function (){
|
element.reload = function (){
|
||||||
// Continue if times is Infinity or
|
// Continue if times is Infinity or
|
||||||
@@ -119,6 +124,7 @@ function web2py_component(action, target, timeout, times){
|
|||||||
web2py_ajax_page('get', action, null, target);} }; // reload
|
web2py_ajax_page('get', action, null, target);} }; // reload
|
||||||
// Method to check timing limit
|
// Method to check timing limit
|
||||||
element.reload_check = function (){
|
element.reload_check = function (){
|
||||||
|
if (jelement.hasClass('w2p_component_stop')) {return false;}
|
||||||
if (this.reload_counter == Infinity){return true;}
|
if (this.reload_counter == Infinity){return true;}
|
||||||
else {
|
else {
|
||||||
if (!isNaN(this.reload_counter)){
|
if (!isNaN(this.reload_counter)){
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
{{extend 'layout.html'}}
|
||||||
|
|
||||||
|
{{block sectionclass}}debug{{end}}
|
||||||
|
<style type="text/css">
|
||||||
|
|
||||||
|
.prompt, #output {
|
||||||
|
width: 45em;
|
||||||
|
height: 1em;
|
||||||
|
border: 1px solid #CCCCCC;
|
||||||
|
font-size: 10pt;
|
||||||
|
margin: 0.5em;
|
||||||
|
padding: 0.5em;
|
||||||
|
padding-right: 0em;
|
||||||
|
overflow: auto;
|
||||||
|
wrap: hard;
|
||||||
|
}
|
||||||
|
|
||||||
|
#output {
|
||||||
|
height:150px;overflow:auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toolbar {
|
||||||
|
margin-left: 0.5em;
|
||||||
|
padding-left: 0.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#caret {
|
||||||
|
width: 2.5em;
|
||||||
|
margin-right: 0px;
|
||||||
|
padding-right: 0px;
|
||||||
|
border-right: 0px;
|
||||||
|
float: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
#statement {
|
||||||
|
width: 43em;
|
||||||
|
margin-left: 1em;
|
||||||
|
padding-left: 0px;
|
||||||
|
border-left: 0px;
|
||||||
|
background-position: top right;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
.processing {
|
||||||
|
background-image: url("{{=URL('static','images/spinner.gif')}}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#ajax-status {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
color: #8AD;
|
||||||
|
font-weight: bold;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #F44;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
</style>
|
||||||
|
<script src="{{=URL('static', 'js/autoscroll.js')}}"></script>
|
||||||
|
|
||||||
|
<div class="applist f60">
|
||||||
|
<div class="applist_inner">
|
||||||
|
<h2>{{=T("web2py online debugger")}}</h2>
|
||||||
|
|
||||||
|
{{if filename:}}
|
||||||
|
<h3>{{=T("Interaction at %s line %s") % (filename, lineno)}}</h3>
|
||||||
|
|
||||||
|
{{if exception:}}
|
||||||
|
<h3 class="exception">{{=T("Exception %s", exception['title'])}}</h3>
|
||||||
|
{{pass}}
|
||||||
|
|
||||||
|
<h5>{{=T("Code listing")}}</h5>
|
||||||
|
{{if lines:}}
|
||||||
|
<pre>{{=CODE('\n'.join([x[1] for x in sorted(lines.items(),key=lambda x: x[0])]),
|
||||||
|
language='python', link=None, counter=min(lines.keys()),
|
||||||
|
highlight_line=lineno, context_lines=10)}}</pre>
|
||||||
|
{{pass}}
|
||||||
|
|
||||||
|
<div class="help">
|
||||||
|
<ul>
|
||||||
|
<li>{{=T("Your application will be blocked until you click an action button (next, step, continue, etc.)")}}</li>
|
||||||
|
<li>{{=T("Your can inspect variables using the console bellow")}}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<h3>{{=T("Interactive console")}}</h3>
|
||||||
|
<textarea id="output" readonly="readonly">{{=data}}</textarea>
|
||||||
|
|
||||||
|
<form id="form" action="{{=URL(r=request,f='execute',args=app)}}" method="get">
|
||||||
|
<div id="shellwrapper">
|
||||||
|
<div id="caret">>>></div>
|
||||||
|
<div id="autoscroll" style="cursor:pointer;float:right;">autoscroll</div>
|
||||||
|
<div class="tooltip">
|
||||||
|
<textarea class="prompt" name="statement" id="statement"></textarea>
|
||||||
|
<span>{{=T("Type python statement in here and hit Return (Enter) to execute it.")}}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{{elif request.env.get('wsgi_multiprocess') or not request.env.get('wsgi_multithread'):}}
|
||||||
|
<h3 class="not_paused">{{=T("Unsupported webserver working mode: %s", request.env.get('server_software', ''))}}</h3>
|
||||||
|
<div class="help">
|
||||||
|
<li><b>{{=T("WARNING:")}} </b>{{=T("This debugger may not work properly if you don't have a threaded webserver or you're using multiple daemon processes.")}}</li>
|
||||||
|
<li>{{=T("In development, use the default Rocket webserver that is currently supported by this debugger.")}}</li>
|
||||||
|
<li>{{=T("On production, you'll have to configure your webserver to use one process and multiple threads to use this debugger.")}}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{{#=BEAUTIFY(request.env)}}
|
||||||
|
{{else:}}
|
||||||
|
<h3 class="not_paused">{{=T("No Interaction yet")}}</h3>
|
||||||
|
<div class="help">
|
||||||
|
<ul>
|
||||||
|
<li>{{=T("You need to set up and reach a")}} {{=A(T("breakpoint"), _href=URL('breakpoints'))}} {{=T('to use the debugger!')}}</li>
|
||||||
|
<li>{{=T('To emulate a breakpoint programatically, write:')}}
|
||||||
|
{{=CODE("from gluon.debug import dbg\n"
|
||||||
|
"dbg.set_trace() # stop here!\n",
|
||||||
|
counter=None)}}</li>
|
||||||
|
<li>{{=T('Please')}} {{=A(T("refresh"), _href=URL('interact'))}} {{=T('this page to see if a breakpoint was hit and debug interaction is required.')}}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{{pass}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div class="sidebar fl60">
|
||||||
|
<div class="sidebar_inner controls">
|
||||||
|
<span class="pwdchange">
|
||||||
|
{{if filename:}}
|
||||||
|
{{=sp_button(URL('step'), T("step"))}}
|
||||||
|
{{=sp_button(URL('next'), T("next"))}}
|
||||||
|
{{=sp_button(URL('ret'), T("return"))}}
|
||||||
|
{{=sp_button(URL('cont'), T("continue"))}}
|
||||||
|
{{=sp_button(URL('stop'), T("stop"))}}
|
||||||
|
{{pass}}
|
||||||
|
{{=button(URL('breakpoints'), T("breakpoints"))}}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{{if exception:}}
|
||||||
|
<div class="box">
|
||||||
|
<h3>{{=T('Exception %(extype)s: %(exvalue)s', dict(extype=exception['extype'], exvalue=exception['exvalue']))}}</h3>
|
||||||
|
<div class="formfield">
|
||||||
|
{{=CODE((exception['request']), counter=None)}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{pass}}
|
||||||
|
|
||||||
|
<div class="box">
|
||||||
|
<h3>{{=T('Locals##debug')}}</h3>
|
||||||
|
<div class="formfield">
|
||||||
|
{{=BEAUTIFY(f_locals)}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="box">
|
||||||
|
<h3>{{=T('Globals##debug')}}</h3>
|
||||||
|
<div class="formfield">
|
||||||
|
{{=BEAUTIFY(f_globals)}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<script type="text/javascript">
|
||||||
|
var bShellScrolling=0
|
||||||
|
jQuery(document).ready(function(){
|
||||||
|
jQuery('#statement').focus();
|
||||||
|
|
||||||
|
jQuery('#statement').keyup(function(event){
|
||||||
|
var t=jQuery(this),
|
||||||
|
s=t.val(),
|
||||||
|
o=jQuery('#output'),
|
||||||
|
RETURN = 38;
|
||||||
|
if(s=='\n') t.val('');
|
||||||
|
if(s.length>1 && s.substr(s.length-1,1)=='\n' && s.substr(s.length-2,1)!=':' &&
|
||||||
|
(s.indexOf(':\n ')<0 || s.substr(s.length-2,1)=='\n')) {
|
||||||
|
t.val('');
|
||||||
|
jQuery.post("{{=URL(r=request,f='execute',args=app)}}",
|
||||||
|
{statement:s},function(data){o.html(o.html()+data).attr('scrollTop',o.attr('scrollHeight'));});
|
||||||
|
} else { };
|
||||||
|
if(event.keyCode==RETURN){
|
||||||
|
var i=s.length
|
||||||
|
if(i==0){
|
||||||
|
var s=o.find('table:last pre:first').text();
|
||||||
|
bShellScrolling=o.find('table').length;
|
||||||
|
}else if(bShellScrolling){
|
||||||
|
var i=bShellScrolling
|
||||||
|
if(i<1){
|
||||||
|
return
|
||||||
|
}else{
|
||||||
|
i--
|
||||||
|
var s=o.find('table:nth-child('+(i)+') pre:first').text();
|
||||||
|
bShellScrolling=i
|
||||||
|
}
|
||||||
|
}else if(s.indexOf('\n')<0){
|
||||||
|
var oo=o.find('tr:first-child pre:contains("'+s+'")')
|
||||||
|
if(oo.length==0){
|
||||||
|
return
|
||||||
|
}else if(oo.length==1){
|
||||||
|
s=oo.text();
|
||||||
|
}else{
|
||||||
|
sVar=oo.text();
|
||||||
|
o.html(o.html()+'<dd>'+s+' ?</dd><dt>'+sVar+'</dt>').attr('scrollTop',o.attr('scrollHeight'))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//multistring expr
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// if(s.slice(s.length-1)=='\n'){
|
||||||
|
s=s.slice(0,s.length-1)
|
||||||
|
// }
|
||||||
|
t.val(s);
|
||||||
|
}
|
||||||
|
if(bShellScrolling && event.keyCode==40){
|
||||||
|
var i=bShellScrolling
|
||||||
|
i++
|
||||||
|
var s=o.find('table:nth-child('+i+') tr:first-child pre').text();
|
||||||
|
if(s){
|
||||||
|
s=s.slice(0,s.length-1)
|
||||||
|
t.val(s);
|
||||||
|
bShellScrolling=i
|
||||||
|
}else{
|
||||||
|
bShellScrolling=0
|
||||||
|
t.val('')
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if(bShellScrolling && (event.keyCode==37 || event.keyCode==39)){
|
||||||
|
bShellScrolling=0;
|
||||||
|
};
|
||||||
|
if(event.keyCode==27){
|
||||||
|
bShellScrolling=0;
|
||||||
|
t.val('');
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
@@ -134,7 +134,7 @@ jQuery(document).ready(function(){
|
|||||||
<textarea style="width: auto; height:400px;direction:ltr;" rows="58" cols="100" -amy-enabled="true" id="body" name="data">{{=data}}</textarea>
|
<textarea style="width: auto; height:400px;direction:ltr;" rows="58" cols="100" -amy-enabled="true" id="body" name="data">{{=data}}</textarea>
|
||||||
<script>window.eamy = eamy;</script>
|
<script>window.eamy = eamy;</script>
|
||||||
{{elif TEXT_EDITOR == 'codemirror':}}
|
{{elif TEXT_EDITOR == 'codemirror':}}
|
||||||
<textarea style="width: auto; height:400px;direction:ltr;" id="body" name="data">{{=data}}</textarea>
|
<textarea style="width: auto; height:auto; direction:ltr;" id="body" name="data">{{=data}}</textarea>
|
||||||
<script>
|
<script>
|
||||||
function isFullScreen(instance) {
|
function isFullScreen(instance) {
|
||||||
return /\bCodeMirror-fullscreen\b/.test(instance.getWrapperElement().className);
|
return /\bCodeMirror-fullscreen\b/.test(instance.getWrapperElement().className);
|
||||||
@@ -197,6 +197,7 @@ jQuery(document).ready(function(){
|
|||||||
document.getElementById("body"),cm_opts);
|
document.getElementById("body"),cm_opts);
|
||||||
var hlLine = editor.setLineClass(0, "activeline");
|
var hlLine = editor.setLineClass(0, "activeline");
|
||||||
window.mirror = editor;
|
window.mirror = editor;
|
||||||
|
jQuery(function(){jQuery('.CodeMirror-scroll').css("height","auto").css("overflow-x","auto");});
|
||||||
</script>
|
</script>
|
||||||
{{elif TEXT_EDITOR == 'ace':}}
|
{{elif TEXT_EDITOR == 'ace':}}
|
||||||
<div id="editor" style="height: 500px; width: auto; position: relative">{{=data}}</div>
|
<div id="editor" style="height: 500px; width: auto; position: relative">{{=data}}</div>
|
||||||
|
|||||||
@@ -9,6 +9,13 @@
|
|||||||
body {
|
body {
|
||||||
background: url('{{=URL('static','plugin_jqmobile/images/iphone.jpg')}}') no-repeat white;
|
background: url('{{=URL('static','plugin_jqmobile/images/iphone.jpg')}}') no-repeat white;
|
||||||
}
|
}
|
||||||
|
#back {
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 10px;
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
iframe {
|
iframe {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
margin-left: 320px;
|
margin-left: 320px;
|
||||||
@@ -35,6 +42,7 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<iframe src="{{=URL('default','index',vars=dict(is_mobile='true'))}}"></iframe>
|
<iframe src="{{=URL('default','index',vars=dict(is_mobile='true'))}}"></iframe>
|
||||||
|
<div id="back"><a href="{{=URL('default','index',vars=dict(is_mobile='false'))}}">Back</a></div>
|
||||||
<div id="about">
|
<div id="about">
|
||||||
<h1><a href="http://web2py.com">web2py</a> plugin</h1>
|
<h1><a href="http://web2py.com">web2py</a> plugin</h1>
|
||||||
<h2>for <a href="http://jquerymobile.com/">jQuery Mobile</a></h2>
|
<h2>for <a href="http://jquerymobile.com/">jQuery Mobile</a></h2>
|
||||||
|
|||||||
@@ -66,7 +66,7 @@
|
|||||||
<div id="wrapper">
|
<div id="wrapper">
|
||||||
<textarea id="output" readonly="readonly">web2py Shell {{=request.env.web2py_version}}</textarea>
|
<textarea id="output" readonly="readonly">web2py Shell {{=request.env.web2py_version}}</textarea>
|
||||||
|
|
||||||
<form id="form" action="{{=URL(r=request,f='callback',args=app)}}" method="get">
|
<form id="form" action="{{=URL('callback',args=app)}}" method="get">
|
||||||
<div id="shellwrapper">
|
<div id="shellwrapper">
|
||||||
<div id="caret">>>></div>
|
<div id="caret">>>></div>
|
||||||
<div class="tooltip">
|
<div class="tooltip">
|
||||||
@@ -103,7 +103,7 @@ jQuery(document).ready(function(){
|
|||||||
if(s.length>1 && s.substr(s.length-1,1)=='\n' && s.substr(s.length-2,1)!=':' &&
|
if(s.length>1 && s.substr(s.length-1,1)=='\n' && s.substr(s.length-2,1)!=':' &&
|
||||||
(s.indexOf(':\n ')<0 || s.substr(s.length-2,1)=='\n')) {
|
(s.indexOf(':\n ')<0 || s.substr(s.length-2,1)=='\n')) {
|
||||||
t.val('');
|
t.val('');
|
||||||
jQuery.post("{{=URL(r=request,f='callback',args=app)}}",
|
jQuery.post("{{=URL('callback',args=app)}}",
|
||||||
{statement:s},function(data){o.html(o.html()+data).attr('scrollTop',o.attr('scrollHeight'));});
|
{statement:s},function(data){o.html(o.html()+data).attr('scrollTop',o.attr('scrollHeight'));});
|
||||||
} else { };
|
} else { };
|
||||||
if(event.keyCode==RETURN){
|
if(event.keyCode==RETURN){
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,3 @@ def flash():
|
|||||||
|
|
||||||
def fade():
|
def fade():
|
||||||
return dict()
|
return dict()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -102,17 +102,16 @@ def query_by_table_type(tablename,db,request=request):
|
|||||||
cond = '>0'
|
cond = '>0'
|
||||||
if firstkey.type in ['string', 'text']:
|
if firstkey.type in ['string', 'text']:
|
||||||
cond = '!=""'
|
cond = '!=""'
|
||||||
qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond)
|
qry = '%s.%s.%s%s' % (
|
||||||
|
request.args[0], request.args[1], firstkey.name, cond)
|
||||||
else:
|
else:
|
||||||
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
||||||
return qry
|
return qry
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# ##########################################################
|
# ##########################################################
|
||||||
# ## list all databases and tables
|
# ## list all databases and tables
|
||||||
# ###########################################################
|
# ###########################################################
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
return dict(databases=databases)
|
return dict(databases=databases)
|
||||||
|
|
||||||
@@ -140,6 +139,7 @@ def download():
|
|||||||
db = get_database(request)
|
db = get_database(request)
|
||||||
return response.download(request, db)
|
return response.download(request, db)
|
||||||
|
|
||||||
|
|
||||||
def csv():
|
def csv():
|
||||||
import gluon.contenttype
|
import gluon.contenttype
|
||||||
response.headers['Content-Type'] = \
|
response.headers['Content-Type'] = \
|
||||||
@@ -156,6 +156,7 @@ def csv():
|
|||||||
def import_csv(table, file):
|
def import_csv(table, file):
|
||||||
table.import_from_csv_file(file)
|
table.import_from_csv_file(file)
|
||||||
|
|
||||||
|
|
||||||
def select():
|
def select():
|
||||||
import re
|
import re
|
||||||
db = get_database(request)
|
db = get_database(request)
|
||||||
@@ -192,7 +193,8 @@ def select():
|
|||||||
session.last_query = request.vars.query
|
session.last_query = request.vars.query
|
||||||
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
||||||
_name='query', _value=request.vars.query or '',
|
_name='query', _value=request.vars.query or '',
|
||||||
requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'),
|
requires=IS_NOT_EMPTY(
|
||||||
|
error_message=T("Cannot be empty")))), TR(T('Update:'),
|
||||||
INPUT(_name='update_check', _type='checkbox',
|
INPUT(_name='update_check', _type='checkbox',
|
||||||
value=False), INPUT(_style='width:400px',
|
value=False), INPUT(_style='width:400px',
|
||||||
_name='update_fields', _value=request.vars.update_fields
|
_name='update_fields', _value=request.vars.update_fields
|
||||||
@@ -200,13 +202,14 @@ def select():
|
|||||||
_class='delete', _type='checkbox', value=False), ''),
|
_class='delete', _type='checkbox', value=False), ''),
|
||||||
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
||||||
_action=URL(r=request, args=request.args))
|
_action=URL(r=request, args=request.args))
|
||||||
|
|
||||||
|
tb = None
|
||||||
if form.accepts(request.vars, formname=None):
|
if form.accepts(request.vars, formname=None):
|
||||||
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
||||||
match = regex.match(form.vars.query.strip())
|
match = regex.match(form.vars.query.strip())
|
||||||
if match:
|
if match:
|
||||||
table = match.group('table')
|
table = match.group('table')
|
||||||
try:
|
try:
|
||||||
tb = None
|
|
||||||
nrows = db(query).count()
|
nrows = db(query).count()
|
||||||
if form.vars.update_check and form.vars.update_fields:
|
if form.vars.update_check and form.vars.update_fields:
|
||||||
db(query).update(**eval_in_global_env('dict(%s)'
|
db(query).update(**eval_in_global_env('dict(%s)'
|
||||||
@@ -217,9 +220,11 @@ def select():
|
|||||||
response.flash = T('%s %%{row} deleted', nrows)
|
response.flash = T('%s %%{row} deleted', nrows)
|
||||||
nrows = db(query).count()
|
nrows = db(query).count()
|
||||||
if orderby:
|
if orderby:
|
||||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop), orderby=eval_in_global_env(orderby))
|
rows = db(query, ignore_common_filters=True).select(limitby=(
|
||||||
|
start, stop), orderby=eval_in_global_env(orderby))
|
||||||
else:
|
else:
|
||||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop))
|
rows = db(query, ignore_common_filters=True).select(
|
||||||
|
limitby=(start, stop))
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
import traceback
|
import traceback
|
||||||
tb = traceback.format_exc()
|
tb = traceback.format_exc()
|
||||||
@@ -268,9 +273,11 @@ def update():
|
|||||||
if keyed:
|
if keyed:
|
||||||
key = [f for f in request.vars if f in db[table]._primarykey]
|
key = [f for f in request.vars if f in db[table]._primarykey]
|
||||||
if key:
|
if key:
|
||||||
record = db(db[table][key[0]] == request.vars[key[0]], ignore_common_filters=True).select().first()
|
record = db(db[table][key[0]] == request.vars[key[
|
||||||
|
0]], ignore_common_filters=True).select().first()
|
||||||
else:
|
else:
|
||||||
record = db(db[table].id == request.args(2),ignore_common_filters=True).select().first()
|
record = db(db[table].id == request.args(
|
||||||
|
2), ignore_common_filters=True).select().first()
|
||||||
|
|
||||||
if not record:
|
if not record:
|
||||||
qry = query_by_table_type(table, db)
|
qry = query_by_table_type(table, db)
|
||||||
@@ -282,7 +289,8 @@ def update():
|
|||||||
for k in db[table]._primarykey:
|
for k in db[table]._primarykey:
|
||||||
db[table][k].writable = False
|
db[table][k].writable = False
|
||||||
|
|
||||||
form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'),
|
form = SQLFORM(
|
||||||
|
db[table], record, deletable=True, delete_label=T('Check to delete'),
|
||||||
ignore_rw=ignore_rw and not keyed,
|
ignore_rw=ignore_rw and not keyed,
|
||||||
linkto=URL('select',
|
linkto=URL('select',
|
||||||
args=request.args[:1]), upload=URL(r=request,
|
args=request.args[:1]), upload=URL(r=request,
|
||||||
@@ -304,11 +312,15 @@ def update():
|
|||||||
def state():
|
def state():
|
||||||
return dict()
|
return dict()
|
||||||
|
|
||||||
|
|
||||||
def ccache():
|
def ccache():
|
||||||
form = FORM(
|
form = FORM(
|
||||||
P(TAG.BUTTON(T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
P(TAG.BUTTON(
|
||||||
P(TAG.BUTTON(T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||||
P(TAG.BUTTON(T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
P(TAG.BUTTON(
|
||||||
|
T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||||
|
P(TAG.BUTTON(
|
||||||
|
T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||||
)
|
)
|
||||||
|
|
||||||
if form.accepts(request.vars, session):
|
if form.accepts(request.vars, session):
|
||||||
@@ -332,11 +344,16 @@ def ccache():
|
|||||||
redirect(URL(r=request))
|
redirect(URL(r=request))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from guppy import hpy; hp=hpy()
|
from guppy import hpy
|
||||||
|
hp = hpy()
|
||||||
except ImportError:
|
except ImportError:
|
||||||
hp = False
|
hp = False
|
||||||
|
|
||||||
import shelve, os, copy, time, math
|
import shelve
|
||||||
|
import os
|
||||||
|
import copy
|
||||||
|
import time
|
||||||
|
import math
|
||||||
from gluon import portalocker
|
from gluon import portalocker
|
||||||
|
|
||||||
ram = {
|
ram = {
|
||||||
@@ -379,11 +396,13 @@ def ccache():
|
|||||||
if value[0] < ram['oldest']:
|
if value[0] < ram['oldest']:
|
||||||
ram['oldest'] = value[0]
|
ram['oldest'] = value[0]
|
||||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||||
|
folder = os.path.join(request.folder,'cache')
|
||||||
locker = open(os.path.join(request.folder,
|
if not os.path.exists(folder):
|
||||||
'cache/cache.lock'), 'a')
|
os.mkdir(folder)
|
||||||
|
locker = open(os.path.join(folder, 'cache.lock'), 'a')
|
||||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||||
disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve'))
|
disk_storage = shelve.open(
|
||||||
|
os.path.join(folder, 'cache.shelve'))
|
||||||
try:
|
try:
|
||||||
for key, value in disk_storage.items():
|
for key, value in disk_storage.items():
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
@@ -414,7 +433,8 @@ def ccache():
|
|||||||
total['misses'] = ram['misses'] + disk['misses']
|
total['misses'] = ram['misses'] + disk['misses']
|
||||||
total['keys'] = ram['keys'] + disk['keys']
|
total['keys'] = ram['keys'] + disk['keys']
|
||||||
try:
|
try:
|
||||||
total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses'])
|
total['ratio'] = total['hits'] * 100 / (total['hits'] +
|
||||||
|
total['misses'])
|
||||||
except (KeyError, ZeroDivisionError):
|
except (KeyError, ZeroDivisionError):
|
||||||
total['ratio'] = 0
|
total['ratio'] = 0
|
||||||
|
|
||||||
@@ -440,6 +460,3 @@ def ccache():
|
|||||||
|
|
||||||
return dict(form=form, total=total,
|
return dict(form=form, total=total,
|
||||||
ram=ram, disk=disk, object_stats=hp != False)
|
ram=ram, disk=disk, object_stats=hp != False)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
@@ -19,7 +18,7 @@ def cache_on_disk():
|
|||||||
def cache_in_ram_and_disk():
|
def cache_in_ram_and_disk():
|
||||||
"""cache the output of the lambda function on disk and in ram"""
|
"""cache the output of the lambda function on disk and in ram"""
|
||||||
|
|
||||||
t = cache.ram('time', lambda : cache.disk('time', lambda : \
|
t = cache.ram('time', lambda: cache.disk('time', lambda:
|
||||||
time.ctime(), time_expire=5), time_expire=5)
|
time.ctime(), time_expire=5), time_expire=5)
|
||||||
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||||
|
|
||||||
@@ -47,5 +46,3 @@ def cache_controller_and_view():
|
|||||||
t = time.ctime()
|
t = time.ctime()
|
||||||
d = dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
d = dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||||
return response.render(d)
|
return response.render(d)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,68 +9,83 @@ response.description = T('web2py Web Framework')
|
|||||||
session.forget()
|
session.forget()
|
||||||
cache_expire = not request.is_local and 300 or 0
|
cache_expire = not request.is_local and 300 or 0
|
||||||
|
|
||||||
|
|
||||||
@cache('index', time_expire=cache_expire)
|
@cache('index', time_expire=cache_expire)
|
||||||
def index():
|
def index():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
@cache('what', time_expire=cache_expire)
|
@cache('what', time_expire=cache_expire)
|
||||||
def what():
|
def what():
|
||||||
import urllib;
|
import urllib
|
||||||
try:
|
try:
|
||||||
images = XML(urllib.urlopen('http://web2py.com/poweredby/default/images').read())
|
images = XML(urllib.urlopen(
|
||||||
|
'http://web2py.com/poweredby/default/images').read())
|
||||||
except:
|
except:
|
||||||
images = []
|
images = []
|
||||||
return response.render(images=images)
|
return response.render(images=images)
|
||||||
|
|
||||||
|
|
||||||
@cache('download', time_expire=cache_expire)
|
@cache('download', time_expire=cache_expire)
|
||||||
def download():
|
def download():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
@cache('who', time_expire=cache_expire)
|
@cache('who', time_expire=cache_expire)
|
||||||
def who():
|
def who():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
@cache('support', time_expire=cache_expire)
|
@cache('support', time_expire=cache_expire)
|
||||||
def support():
|
def support():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
@cache('documentation', time_expire=cache_expire)
|
@cache('documentation', time_expire=cache_expire)
|
||||||
def documentation():
|
def documentation():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
@cache('usergroups', time_expire=cache_expire)
|
@cache('usergroups', time_expire=cache_expire)
|
||||||
def usergroups():
|
def usergroups():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
def contact():
|
def contact():
|
||||||
redirect(URL('default', 'usergroups'))
|
redirect(URL('default', 'usergroups'))
|
||||||
|
|
||||||
|
|
||||||
@cache('videos', time_expire=cache_expire)
|
@cache('videos', time_expire=cache_expire)
|
||||||
def videos():
|
def videos():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
def security():
|
def security():
|
||||||
redirect('http://www.web2py.com/book/default/chapter/01#security')
|
redirect('http://www.web2py.com/book/default/chapter/01#security')
|
||||||
|
|
||||||
|
|
||||||
def api():
|
def api():
|
||||||
redirect('http://web2py.com/book/default/chapter/04#API')
|
redirect('http://web2py.com/book/default/chapter/04#API')
|
||||||
|
|
||||||
|
|
||||||
@cache('license', time_expire=cache_expire)
|
@cache('license', time_expire=cache_expire)
|
||||||
def license():
|
def license():
|
||||||
import os
|
import os
|
||||||
filename = os.path.join(request.env.gluon_parent, 'LICENSE')
|
filename = os.path.join(request.env.gluon_parent, 'LICENSE')
|
||||||
return response.render(dict(license=MARKMIN(read_file(filename))))
|
return response.render(dict(license=MARKMIN(read_file(filename))))
|
||||||
|
|
||||||
|
|
||||||
def version():
|
def version():
|
||||||
return 'Version %s.%s.%s (%s) %s' % request.env.web2py_version
|
return 'Version %s.%s.%s (%s) %s' % request.env.web2py_version
|
||||||
|
|
||||||
|
|
||||||
@cache('examples', time_expire=cache_expire)
|
@cache('examples', time_expire=cache_expire)
|
||||||
def examples():
|
def examples():
|
||||||
return response.render()
|
return response.render()
|
||||||
|
|
||||||
|
|
||||||
@cache('changelog', time_expire=cache_expire)
|
@cache('changelog', time_expire=cache_expire)
|
||||||
def changelog():
|
def changelog():
|
||||||
import os
|
import os
|
||||||
filename = os.path.join(request.env.gluon_parent, 'CHANGELOG')
|
filename = os.path.join(request.env.gluon_parent, 'CHANGELOG')
|
||||||
return response.render(dict(changelog=MARKMIN(read_file(filename))))
|
return response.render(dict(changelog=MARKMIN(read_file(filename))))
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def form():
|
def form():
|
||||||
""" a simple entry form with various types of objects """
|
""" a simple entry form with various types of objects """
|
||||||
|
|
||||||
@@ -23,6 +20,3 @@ def form():
|
|||||||
else:
|
else:
|
||||||
response.flash = 'please fill the form'
|
response.flash = 'please fill the form'
|
||||||
return dict(form=form, vars=form.vars)
|
return dict(form=form, vars=form.vars)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
session.forget()
|
session.forget()
|
||||||
|
|
||||||
response.menu = [['home', False, '/%s/default/index'
|
response.menu = [['home', False, '/%s/default/index'
|
||||||
@@ -77,6 +76,3 @@ def vars():
|
|||||||
doc=doc,
|
doc=doc,
|
||||||
attributes=attributes,
|
attributes=attributes,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,3 @@ def basic():
|
|||||||
['basic', True, URL('basic')]]
|
['basic', True, URL('basic')]]
|
||||||
response.flash = 'you clicked on basic'
|
response.flash = 'you clicked on basic'
|
||||||
return dict(message='you clicked on basic')
|
return dict(message='you clicked on basic')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def counter():
|
def counter():
|
||||||
""" every time you reload, it increases the session.counter """
|
""" every time you reload, it increases the session.counter """
|
||||||
|
|
||||||
@@ -8,6 +5,3 @@ def counter():
|
|||||||
session.counter = 0
|
session.counter = 0
|
||||||
session.counter += 1
|
session.counter += 1
|
||||||
return dict(counter=session.counter)
|
return dict(counter=session.counter)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
def hello1():
|
def hello1():
|
||||||
""" simple page without template """
|
""" simple page without template """
|
||||||
|
|
||||||
@@ -99,8 +100,7 @@ def rss_aggregator():
|
|||||||
pubDate=datetime.datetime.now()) for entry in
|
pubDate=datetime.datetime.now()) for entry in
|
||||||
d.entries])
|
d.entries])
|
||||||
response.headers['Content-Type'] = 'application/rss+xml'
|
response.headers['Content-Type'] = 'application/rss+xml'
|
||||||
return rss2.dumps(rss)
|
return rss.to_xml(encoding='utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def ajaxwiki():
|
def ajaxwiki():
|
||||||
@@ -135,6 +135,6 @@ Quoted text
|
|||||||
_onclick="ajax('ajaxwiki_onclick',['text'],'html')"))
|
_onclick="ajax('ajaxwiki_onclick',['text'],'html')"))
|
||||||
return dict(form=form, html=DIV(_id='html'))
|
return dict(form=form, html=DIV(_id='html'))
|
||||||
|
|
||||||
|
|
||||||
def ajaxwiki_onclick():
|
def ajaxwiki_onclick():
|
||||||
return MARKMIN(request.vars.text).xml()
|
return MARKMIN(request.vars.text).xml()
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
from gluon.contrib.spreadsheet import Sheet
|
from gluon.contrib.spreadsheet import Sheet
|
||||||
|
|
||||||
|
|
||||||
def callback():
|
def callback():
|
||||||
return cache.ram('sheet1', lambda: None, None).process(request)
|
return cache.ram('sheet1', lambda: None, None).process(request)
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
sheet = cache.ram('sheet1', lambda: Sheet(10, 10, URL('callback')), 0)
|
sheet = cache.ram('sheet1', lambda: Sheet(10, 10, URL('callback')), 0)
|
||||||
#sheet.cell('r0c3',value='=r0c0+r0c1+r0c2',readonly=True)
|
#sheet.cell('r0c3',value='=r0c0+r0c1+r0c2',readonly=True)
|
||||||
return dict(sheet=sheet)
|
return dict(sheet=sheet)
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def variables():
|
def variables():
|
||||||
return dict(a=10, b=20)
|
return dict(a=10, b=20)
|
||||||
|
|
||||||
@@ -31,6 +28,3 @@ def xml():
|
|||||||
|
|
||||||
def beautify():
|
def beautify():
|
||||||
return dict(message=BEAUTIFY(request))
|
return dict(message=BEAUTIFY(request))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
def group_feed_reader(group, mode='div', counter='5'):
|
def group_feed_reader(group, mode='div', counter='5'):
|
||||||
"""parse group feeds"""
|
"""parse group feeds"""
|
||||||
|
|
||||||
@@ -8,17 +7,18 @@ def group_feed_reader(group,mode='div',counter='5'):
|
|||||||
g = feedparser.parse(url)
|
g = feedparser.parse(url)
|
||||||
|
|
||||||
if mode == 'div':
|
if mode == 'div':
|
||||||
html = XML(TAG.BLOCKQUOTE(UL(*[LI(A(entry['title']+' - ' +\
|
html = XML(TAG.BLOCKQUOTE(UL(*[LI(A(entry['title'] + ' - ' +
|
||||||
entry['author'][entry['author'].rfind('('):],\
|
entry['author'][
|
||||||
_href=entry['link'],_target='_blank'))\
|
entry['author'].rfind('('):],
|
||||||
for entry in g['entries'] ]),\
|
_href=entry['link'], _target='_blank'))
|
||||||
_class="boxInfo",\
|
for entry in g['entries']]),
|
||||||
|
_class="boxInfo",
|
||||||
_style="padding-bottom:5px;"))
|
_style="padding-bottom:5px;"))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
html = XML(UL(*[LI(A(entry['title']+' - ' +\
|
html = XML(UL(*[LI(A(entry['title'] + ' - ' +
|
||||||
entry['author'][entry['author'].rfind('('):],\
|
entry['author'][entry['author'].rfind('('):],
|
||||||
_href=entry['link'],_target='_blank'))\
|
_href=entry['link'], _target='_blank'))
|
||||||
for entry in g['entries']]))
|
for entry in g['entries']]))
|
||||||
|
|
||||||
return html
|
return html
|
||||||
@@ -31,19 +31,14 @@ def code_feed_reader(project,mode='div'):
|
|||||||
from gluon.contrib import feedparser
|
from gluon.contrib import feedparser
|
||||||
g = feedparser.parse(url)
|
g = feedparser.parse(url)
|
||||||
if mode == 'div':
|
if mode == 'div':
|
||||||
html = XML(DIV(UL(*[LI(A(entry['title'],_href=entry['link'],\
|
html = XML(DIV(UL(*[LI(A(entry['title'], _href=entry['link'],
|
||||||
_target='_blank'))\
|
_target='_blank'))
|
||||||
for entry in g['entries'][0:5]]),\
|
for entry in g['entries'][0:5]]),
|
||||||
_class="boxInfo",\
|
_class="boxInfo",
|
||||||
_style="padding-bottom:5px;"))
|
_style="padding-bottom:5px;"))
|
||||||
else:
|
else:
|
||||||
html = XML(UL(*[LI(A(entry['title'],_href=entry['link'],\
|
html = XML(UL(*[LI(A(entry['title'], _href=entry['link'],
|
||||||
_target='_blank'))\
|
_target='_blank'))
|
||||||
for entry in g['entries'][0:5]]))
|
for entry in g['entries'][0:5]]))
|
||||||
|
|
||||||
|
|
||||||
return html
|
return html
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,18 +2,19 @@ import gluon.template
|
|||||||
|
|
||||||
markmin_dict = dict(
|
markmin_dict = dict(
|
||||||
code_python=lambda code: str(CODE(code)),
|
code_python=lambda code: str(CODE(code)),
|
||||||
template=lambda \
|
template=lambda
|
||||||
code: gluon.template.render(code, context=globals()),
|
code: gluon.template.render(code, context=globals()),
|
||||||
sup=lambda \
|
sup=lambda
|
||||||
code: '<sup style="font-size:0.5em;">%s</sup>' % code,
|
code: '<sup style="font-size:0.5em;">%s</sup>' % code,
|
||||||
br=lambda n: '<br>' * int(n),
|
br=lambda n: '<br>' * int(n),
|
||||||
groupdates=lambda group: group_feed_reader(group),
|
groupdates=lambda group: group_feed_reader(group),
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_content(b=None,\
|
|
||||||
c=request.controller,\
|
def get_content(b=None,
|
||||||
f=request.function,\
|
c=request.controller,
|
||||||
l='en',\
|
f=request.function,
|
||||||
|
l='en',
|
||||||
format='markmin'):
|
format='markmin'):
|
||||||
"""Gets and renders the file in
|
"""Gets and renders the file in
|
||||||
<app>/private/content/<lang>/<controller>/<function>/<block>.<format>
|
<app>/private/content/<lang>/<controller>/<function>/<block>.<format>
|
||||||
@@ -21,7 +22,8 @@ def get_content(b=None,\
|
|||||||
|
|
||||||
def openfile():
|
def openfile():
|
||||||
import os
|
import os
|
||||||
path = os.path.join(request.folder,'private','content',l,c,f,b+'.'+format)
|
path = os.path.join(
|
||||||
|
request.folder, 'private', 'content', l, c, f, b + '.' + format)
|
||||||
return open(path)
|
return open(path)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -37,4 +39,3 @@ def get_content(b=None,\
|
|||||||
openedfile.close()
|
openedfile.close()
|
||||||
|
|
||||||
return html
|
return html
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ response.menu = [
|
|||||||
#########################################################################
|
#########################################################################
|
||||||
## Changes the menu active item
|
## Changes the menu active item
|
||||||
#########################################################################
|
#########################################################################
|
||||||
|
|
||||||
|
|
||||||
def toggle_menuclass(cssclass='pressed', menuid='headermenu'):
|
def toggle_menuclass(cssclass='pressed', menuid='headermenu'):
|
||||||
"""This function changes the menu class to put pressed appearance"""
|
"""This function changes the menu class to put pressed appearance"""
|
||||||
|
|
||||||
@@ -23,7 +25,6 @@ def toggle_menuclass(cssclass='pressed',menuid='headermenu'):
|
|||||||
documentation='-520px -115px'
|
documentation='-520px -115px'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
if request.function in positions.keys():
|
if request.function in positions.keys():
|
||||||
jscript = """
|
jscript = """
|
||||||
<script>
|
<script>
|
||||||
@@ -42,4 +43,3 @@ def toggle_menuclass(cssclass='pressed',menuid='headermenu'):
|
|||||||
return XML(jscript)
|
return XML(jscript)
|
||||||
else:
|
else:
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
- [[User Voice http://web2py.uservoice.com/ popup]]
|
- [[User Voice http://web2py.uservoice.com/ popup]]
|
||||||
|
|
||||||
#### Learning and Demos
|
#### Learning and Demos
|
||||||
|
- [[Intro video http://www.youtube.com/watch?v=BXzqmHx6edY]] and [[code examples https://github.com/mjhea0/web2py]]
|
||||||
- [[Killer Web Development Tutorial http://killer-web-development.com/]]
|
- [[Killer Web Development Tutorial http://killer-web-development.com/]]
|
||||||
- [[Admin Demo http://www.web2py.com/demo_admin popup]] (web-based IDE)
|
- [[Admin Demo http://www.web2py.com/demo_admin popup]] (web-based IDE)
|
||||||
- [[Welcome App Demo http://www.web2py.com/welcome]] (scaffolding application)
|
- [[Welcome App Demo http://www.web2py.com/welcome]] (scaffolding application)
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ input[type=text],input[type=password],select{width:300px; margin-right:5px}
|
|||||||
border-top:1px #DEDEDE solid;
|
border-top:1px #DEDEDE solid;
|
||||||
}
|
}
|
||||||
.header {
|
.header {
|
||||||
// background:<fill here for header image>;
|
/* background:<fill here for header image>; */
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -115,6 +115,10 @@ div.flash {
|
|||||||
z-index:2000;
|
z-index:2000;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
div.flash #closeflash{color:inherit; float:right; margin-left:15px;}
|
||||||
|
.ie-lte7 div.flash #closeflash
|
||||||
|
{color:expression(this.parentNode.currentStyle['color']);float:none;position:absolute;right:4px;}
|
||||||
|
|
||||||
div.flash:hover { opacity:0.25; }
|
div.flash:hover { opacity:0.25; }
|
||||||
|
|
||||||
div.error_wrapper {display:block}
|
div.error_wrapper {display:block}
|
||||||
@@ -182,7 +186,7 @@ div.error {
|
|||||||
* will look better with the declarations below
|
* will look better with the declarations below
|
||||||
* if needed to remove base.css consider keeping these following lines in some css file.
|
* if needed to remove base.css consider keeping these following lines in some css file.
|
||||||
*/
|
*/
|
||||||
// .web2py_table {border:1px solid #ccc}
|
/* .web2py_table {border:1px solid #ccc} */
|
||||||
.web2py_paginator {}
|
.web2py_paginator {}
|
||||||
.web2py_grid {width:100%}
|
.web2py_grid {width:100%}
|
||||||
.web2py_grid table {width:100%}
|
.web2py_grid table {width:100%}
|
||||||
|
|||||||
+2
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -55,7 +55,7 @@ function web2py_event_handlers() {
|
|||||||
jQuery(function() {
|
jQuery(function() {
|
||||||
var flash = jQuery('.flash');
|
var flash = jQuery('.flash');
|
||||||
flash.hide();
|
flash.hide();
|
||||||
if(flash.html()) flash.append('<span style="float:right;">×</span>').slideDown();
|
if(flash.html()) flash.append('<span id="closeflash">×</span>').slideDown();
|
||||||
web2py_ajax_init(document);
|
web2py_ajax_init(document);
|
||||||
web2py_event_handlers();
|
web2py_event_handlers();
|
||||||
});
|
});
|
||||||
@@ -102,15 +102,20 @@ function web2py_ajax_page(method, action, data, target) {
|
|||||||
web2py_ajax_init('#'+target);
|
web2py_ajax_init('#'+target);
|
||||||
if(command)
|
if(command)
|
||||||
eval(decodeURIComponent(command));
|
eval(decodeURIComponent(command));
|
||||||
if(flash)
|
if(flash) {
|
||||||
jQuery('.flash').html(decodeURIComponent(flash)).slideDown();
|
jQuery('.flash')
|
||||||
|
.html(decodeURIComponent(flash))
|
||||||
|
.append('<span id="closeflash">×</span>')
|
||||||
|
.slideDown();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function web2py_component(action, target, timeout, times){
|
function web2py_component(action, target, timeout, times){
|
||||||
jQuery(function(){
|
jQuery(function(){
|
||||||
var element = jQuery("#" + target).get(0);
|
var jelement = jQuery("#" + target);
|
||||||
|
var element = jelement.get(0);
|
||||||
var statement = "jQuery('#" + target + "').get(0).reload();";
|
var statement = "jQuery('#" + target + "').get(0).reload();";
|
||||||
element.reload = function (){
|
element.reload = function (){
|
||||||
// Continue if times is Infinity or
|
// Continue if times is Infinity or
|
||||||
@@ -119,6 +124,7 @@ function web2py_component(action, target, timeout, times){
|
|||||||
web2py_ajax_page('get', action, null, target);} }; // reload
|
web2py_ajax_page('get', action, null, target);} }; // reload
|
||||||
// Method to check timing limit
|
// Method to check timing limit
|
||||||
element.reload_check = function (){
|
element.reload_check = function (){
|
||||||
|
if (jelement.hasClass('w2p_component_stop')) {return false;}
|
||||||
if (this.reload_counter == Infinity){return true;}
|
if (this.reload_counter == Infinity){return true;}
|
||||||
else {
|
else {
|
||||||
if (!isNaN(this.reload_counter)){
|
if (!isNaN(this.reload_counter)){
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
</li><li>Alvaro Justen (dynamical translations)
|
</li><li>Alvaro Justen (dynamical translations)
|
||||||
</li><li>Anders Roos (file locking)
|
</li><li>Anders Roos (file locking)
|
||||||
</li><li>Andrew Willimott (documentation, TeraData support)
|
</li><li>Andrew Willimott (documentation, TeraData support)
|
||||||
|
</li><li>Andriy Kornatskyy (benchmarks and profiling)
|
||||||
</li><li>Angelo Compagnucci (mobile devices)
|
</li><li>Angelo Compagnucci (mobile devices)
|
||||||
</li><li>Anthony Bastardi (book, poweredby site, multiple contributions)
|
</li><li>Anthony Bastardi (book, poweredby site, multiple contributions)
|
||||||
</li><li>Arun K. Rajeevan (plugin_wiki)
|
</li><li>Arun K. Rajeevan (plugin_wiki)
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{{extend 'layout.html'}}
|
||||||
|
|
||||||
|
<h2>form.vars</h2>
|
||||||
|
<pre>{{=vars}}</pre>
|
||||||
|
|
||||||
|
<h2>form</h2>
|
||||||
|
|
||||||
|
{{=form}}
|
||||||
|
|
||||||
@@ -1,15 +1 @@
|
|||||||
{{
|
{{from gluon.serializers import xml}}{{=XML(xml(response._vars,quote=False))}}
|
||||||
###
|
|
||||||
# response._vars contains the dictionary returned by thecontroller action
|
|
||||||
###
|
|
||||||
try:
|
|
||||||
from gluon.serializers import xml
|
|
||||||
response.write(xml(response._vars), escape=False)
|
|
||||||
response.headers['Content-Type'] = 'text/xml'
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
raise HTTP(405, 'XML serialization error')
|
|
||||||
except ImportError:
|
|
||||||
raise HTTP(405, 'XML not available')
|
|
||||||
except:
|
|
||||||
raise HTTP(405, 'XML error')
|
|
||||||
}}
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
{{extend 'layout.html'}}
|
||||||
|
|
||||||
|
{{=toolbar}}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
|
|||||||
@@ -102,17 +102,16 @@ def query_by_table_type(tablename,db,request=request):
|
|||||||
cond = '>0'
|
cond = '>0'
|
||||||
if firstkey.type in ['string', 'text']:
|
if firstkey.type in ['string', 'text']:
|
||||||
cond = '!=""'
|
cond = '!=""'
|
||||||
qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond)
|
qry = '%s.%s.%s%s' % (
|
||||||
|
request.args[0], request.args[1], firstkey.name, cond)
|
||||||
else:
|
else:
|
||||||
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
||||||
return qry
|
return qry
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# ##########################################################
|
# ##########################################################
|
||||||
# ## list all databases and tables
|
# ## list all databases and tables
|
||||||
# ###########################################################
|
# ###########################################################
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
return dict(databases=databases)
|
return dict(databases=databases)
|
||||||
|
|
||||||
@@ -140,6 +139,7 @@ def download():
|
|||||||
db = get_database(request)
|
db = get_database(request)
|
||||||
return response.download(request, db)
|
return response.download(request, db)
|
||||||
|
|
||||||
|
|
||||||
def csv():
|
def csv():
|
||||||
import gluon.contenttype
|
import gluon.contenttype
|
||||||
response.headers['Content-Type'] = \
|
response.headers['Content-Type'] = \
|
||||||
@@ -156,6 +156,7 @@ def csv():
|
|||||||
def import_csv(table, file):
|
def import_csv(table, file):
|
||||||
table.import_from_csv_file(file)
|
table.import_from_csv_file(file)
|
||||||
|
|
||||||
|
|
||||||
def select():
|
def select():
|
||||||
import re
|
import re
|
||||||
db = get_database(request)
|
db = get_database(request)
|
||||||
@@ -192,7 +193,8 @@ def select():
|
|||||||
session.last_query = request.vars.query
|
session.last_query = request.vars.query
|
||||||
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
||||||
_name='query', _value=request.vars.query or '',
|
_name='query', _value=request.vars.query or '',
|
||||||
requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'),
|
requires=IS_NOT_EMPTY(
|
||||||
|
error_message=T("Cannot be empty")))), TR(T('Update:'),
|
||||||
INPUT(_name='update_check', _type='checkbox',
|
INPUT(_name='update_check', _type='checkbox',
|
||||||
value=False), INPUT(_style='width:400px',
|
value=False), INPUT(_style='width:400px',
|
||||||
_name='update_fields', _value=request.vars.update_fields
|
_name='update_fields', _value=request.vars.update_fields
|
||||||
@@ -200,13 +202,14 @@ def select():
|
|||||||
_class='delete', _type='checkbox', value=False), ''),
|
_class='delete', _type='checkbox', value=False), ''),
|
||||||
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
||||||
_action=URL(r=request, args=request.args))
|
_action=URL(r=request, args=request.args))
|
||||||
|
|
||||||
|
tb = None
|
||||||
if form.accepts(request.vars, formname=None):
|
if form.accepts(request.vars, formname=None):
|
||||||
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
||||||
match = regex.match(form.vars.query.strip())
|
match = regex.match(form.vars.query.strip())
|
||||||
if match:
|
if match:
|
||||||
table = match.group('table')
|
table = match.group('table')
|
||||||
try:
|
try:
|
||||||
tb = None
|
|
||||||
nrows = db(query).count()
|
nrows = db(query).count()
|
||||||
if form.vars.update_check and form.vars.update_fields:
|
if form.vars.update_check and form.vars.update_fields:
|
||||||
db(query).update(**eval_in_global_env('dict(%s)'
|
db(query).update(**eval_in_global_env('dict(%s)'
|
||||||
@@ -217,9 +220,11 @@ def select():
|
|||||||
response.flash = T('%s %%{row} deleted', nrows)
|
response.flash = T('%s %%{row} deleted', nrows)
|
||||||
nrows = db(query).count()
|
nrows = db(query).count()
|
||||||
if orderby:
|
if orderby:
|
||||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop), orderby=eval_in_global_env(orderby))
|
rows = db(query, ignore_common_filters=True).select(limitby=(
|
||||||
|
start, stop), orderby=eval_in_global_env(orderby))
|
||||||
else:
|
else:
|
||||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop))
|
rows = db(query, ignore_common_filters=True).select(
|
||||||
|
limitby=(start, stop))
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
import traceback
|
import traceback
|
||||||
tb = traceback.format_exc()
|
tb = traceback.format_exc()
|
||||||
@@ -268,9 +273,11 @@ def update():
|
|||||||
if keyed:
|
if keyed:
|
||||||
key = [f for f in request.vars if f in db[table]._primarykey]
|
key = [f for f in request.vars if f in db[table]._primarykey]
|
||||||
if key:
|
if key:
|
||||||
record = db(db[table][key[0]] == request.vars[key[0]], ignore_common_filters=True).select().first()
|
record = db(db[table][key[0]] == request.vars[key[
|
||||||
|
0]], ignore_common_filters=True).select().first()
|
||||||
else:
|
else:
|
||||||
record = db(db[table].id == request.args(2),ignore_common_filters=True).select().first()
|
record = db(db[table].id == request.args(
|
||||||
|
2), ignore_common_filters=True).select().first()
|
||||||
|
|
||||||
if not record:
|
if not record:
|
||||||
qry = query_by_table_type(table, db)
|
qry = query_by_table_type(table, db)
|
||||||
@@ -282,7 +289,8 @@ def update():
|
|||||||
for k in db[table]._primarykey:
|
for k in db[table]._primarykey:
|
||||||
db[table][k].writable = False
|
db[table][k].writable = False
|
||||||
|
|
||||||
form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'),
|
form = SQLFORM(
|
||||||
|
db[table], record, deletable=True, delete_label=T('Check to delete'),
|
||||||
ignore_rw=ignore_rw and not keyed,
|
ignore_rw=ignore_rw and not keyed,
|
||||||
linkto=URL('select',
|
linkto=URL('select',
|
||||||
args=request.args[:1]), upload=URL(r=request,
|
args=request.args[:1]), upload=URL(r=request,
|
||||||
@@ -304,11 +312,15 @@ def update():
|
|||||||
def state():
|
def state():
|
||||||
return dict()
|
return dict()
|
||||||
|
|
||||||
|
|
||||||
def ccache():
|
def ccache():
|
||||||
form = FORM(
|
form = FORM(
|
||||||
P(TAG.BUTTON(T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
P(TAG.BUTTON(
|
||||||
P(TAG.BUTTON(T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||||
P(TAG.BUTTON(T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
P(TAG.BUTTON(
|
||||||
|
T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||||
|
P(TAG.BUTTON(
|
||||||
|
T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||||
)
|
)
|
||||||
|
|
||||||
if form.accepts(request.vars, session):
|
if form.accepts(request.vars, session):
|
||||||
@@ -332,11 +344,16 @@ def ccache():
|
|||||||
redirect(URL(r=request))
|
redirect(URL(r=request))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from guppy import hpy; hp=hpy()
|
from guppy import hpy
|
||||||
|
hp = hpy()
|
||||||
except ImportError:
|
except ImportError:
|
||||||
hp = False
|
hp = False
|
||||||
|
|
||||||
import shelve, os, copy, time, math
|
import shelve
|
||||||
|
import os
|
||||||
|
import copy
|
||||||
|
import time
|
||||||
|
import math
|
||||||
from gluon import portalocker
|
from gluon import portalocker
|
||||||
|
|
||||||
ram = {
|
ram = {
|
||||||
@@ -379,11 +396,13 @@ def ccache():
|
|||||||
if value[0] < ram['oldest']:
|
if value[0] < ram['oldest']:
|
||||||
ram['oldest'] = value[0]
|
ram['oldest'] = value[0]
|
||||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||||
|
folder = os.path.join(request.folder,'cache')
|
||||||
locker = open(os.path.join(request.folder,
|
if not os.path.exists(folder):
|
||||||
'cache/cache.lock'), 'a')
|
os.mkdir(folder)
|
||||||
|
locker = open(os.path.join(folder, 'cache.lock'), 'a')
|
||||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||||
disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve'))
|
disk_storage = shelve.open(
|
||||||
|
os.path.join(folder, 'cache.shelve'))
|
||||||
try:
|
try:
|
||||||
for key, value in disk_storage.items():
|
for key, value in disk_storage.items():
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
@@ -414,7 +433,8 @@ def ccache():
|
|||||||
total['misses'] = ram['misses'] + disk['misses']
|
total['misses'] = ram['misses'] + disk['misses']
|
||||||
total['keys'] = ram['keys'] + disk['keys']
|
total['keys'] = ram['keys'] + disk['keys']
|
||||||
try:
|
try:
|
||||||
total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses'])
|
total['ratio'] = total['hits'] * 100 / (total['hits'] +
|
||||||
|
total['misses'])
|
||||||
except (KeyError, ZeroDivisionError):
|
except (KeyError, ZeroDivisionError):
|
||||||
total['ratio'] = 0
|
total['ratio'] = 0
|
||||||
|
|
||||||
@@ -440,6 +460,3 @@ def ccache():
|
|||||||
|
|
||||||
return dict(form=form, total=total,
|
return dict(form=form, total=total,
|
||||||
ram=ram, disk=disk, object_stats=hp != False)
|
ram=ram, disk=disk, object_stats=hp != False)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
## - call exposes all registered services (none by default)
|
## - call exposes all registered services (none by default)
|
||||||
#########################################################################
|
#########################################################################
|
||||||
|
|
||||||
|
|
||||||
def index():
|
def index():
|
||||||
"""
|
"""
|
||||||
example action using the internationalization operator T and flash
|
example action using the internationalization operator T and flash
|
||||||
@@ -20,6 +21,7 @@ def index():
|
|||||||
response.flash = T("Welcome to web2py!")
|
response.flash = T("Welcome to web2py!")
|
||||||
return dict(message=T('Hello World'))
|
return dict(message=T('Hello World'))
|
||||||
|
|
||||||
|
|
||||||
def user():
|
def user():
|
||||||
"""
|
"""
|
||||||
exposes:
|
exposes:
|
||||||
|
|||||||
@@ -89,6 +89,7 @@
|
|||||||
'export as csv file': 'експортувати як файл csv',
|
'export as csv file': 'експортувати як файл csv',
|
||||||
'FAQ': 'ЧаПи (FAQ)',
|
'FAQ': 'ЧаПи (FAQ)',
|
||||||
'First name': "Ім'я",
|
'First name': "Ім'я",
|
||||||
|
'Forgot username?': "Забули ім'я користувача?",
|
||||||
'Forms and Validators': 'Форми та коректність даних',
|
'Forms and Validators': 'Форми та коректність даних',
|
||||||
'Free Applications': 'Вільні додатки',
|
'Free Applications': 'Вільні додатки',
|
||||||
'Group %(group_id)s created': 'Групу %(group_id)s створено',
|
'Group %(group_id)s created': 'Групу %(group_id)s створено',
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
|
|
||||||
if not request.env.web2py_runtime_gae:
|
if not request.env.web2py_runtime_gae:
|
||||||
## if NOT running on Google App Engine use SQLite or other DB
|
## if NOT running on Google App Engine use SQLite or other DB
|
||||||
db = DAL('sqlite://storage.sqlite')
|
db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all'])
|
||||||
else:
|
else:
|
||||||
## connect to Google BigTable (optional 'google:datastore://namespace')
|
## connect to Google BigTable (optional 'google:datastore://namespace')
|
||||||
db = DAL('google:datastore')
|
db = DAL('google:datastore')
|
||||||
|
|||||||
@@ -5,7 +5,10 @@
|
|||||||
## Customize your APP title, subtitle and menus here
|
## Customize your APP title, subtitle and menus here
|
||||||
#########################################################################
|
#########################################################################
|
||||||
|
|
||||||
response.title = ' '.join(word.capitalize() for word in request.application.split('_'))
|
response.logo = A(B('web',SPAN(2),'py'),XML('™ '),
|
||||||
|
_class="brand",_href="http://www.web2py.com/")
|
||||||
|
response.title = ' '.join(
|
||||||
|
word.capitalize() for word in request.application.split('_'))
|
||||||
response.subtitle = T('customize me!')
|
response.subtitle = T('customize me!')
|
||||||
|
|
||||||
## read more at http://dev.w3.org/html5/markup/meta.name.html
|
## read more at http://dev.w3.org/html5/markup/meta.name.html
|
||||||
@@ -25,6 +28,8 @@ response.menu = [
|
|||||||
(T('Home'), False, URL('default', 'index'), [])
|
(T('Home'), False, URL('default', 'index'), [])
|
||||||
]
|
]
|
||||||
|
|
||||||
|
DEVELOPMENT_MENU = True
|
||||||
|
|
||||||
#########################################################################
|
#########################################################################
|
||||||
## provide shortcuts for development. remove in production
|
## provide shortcuts for development. remove in production
|
||||||
#########################################################################
|
#########################################################################
|
||||||
@@ -39,63 +44,96 @@ def _():
|
|||||||
(T('My Sites'), False, URL('admin', 'default', 'site')),
|
(T('My Sites'), False, URL('admin', 'default', 'site')),
|
||||||
(T('This App'), False, URL('admin', 'default', 'design/%s' % app), [
|
(T('This App'), False, URL('admin', 'default', 'design/%s' % app), [
|
||||||
(T('Controller'), False,
|
(T('Controller'), False,
|
||||||
URL('admin','default','edit/%s/controllers/%s.py' % (app,ctr))),
|
URL(
|
||||||
|
'admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))),
|
||||||
(T('View'), False,
|
(T('View'), False,
|
||||||
URL('admin','default','edit/%s/views/%s' % (app,response.view))),
|
URL(
|
||||||
|
'admin', 'default', 'edit/%s/views/%s' % (app, response.view))),
|
||||||
(T('Layout'), False,
|
(T('Layout'), False,
|
||||||
URL('admin','default','edit/%s/views/layout.html' % app)),
|
URL(
|
||||||
|
'admin', 'default', 'edit/%s/views/layout.html' % app)),
|
||||||
(T('Stylesheet'), False,
|
(T('Stylesheet'), False,
|
||||||
URL('admin','default','edit/%s/static/css/web2py.css' % app)),
|
URL(
|
||||||
|
'admin', 'default', 'edit/%s/static/css/web2py.css' % app)),
|
||||||
(T('DB Model'), False,
|
(T('DB Model'), False,
|
||||||
URL('admin','default','edit/%s/models/db.py' % app)),
|
URL(
|
||||||
|
'admin', 'default', 'edit/%s/models/db.py' % app)),
|
||||||
(T('Menu Model'), False,
|
(T('Menu Model'), False,
|
||||||
URL('admin','default','edit/%s/models/menu.py' % app)),
|
URL(
|
||||||
|
'admin', 'default', 'edit/%s/models/menu.py' % app)),
|
||||||
(T('Database'), False, URL(app, 'appadmin', 'index')),
|
(T('Database'), False, URL(app, 'appadmin', 'index')),
|
||||||
(T('Errors'),False, URL('admin','default','errors/' + app)),
|
(T('Errors'), False, URL(
|
||||||
(T('About'),False, URL('admin','default','about/' + app)),
|
'admin', 'default', 'errors/' + app)),
|
||||||
|
(T('About'), False, URL(
|
||||||
|
'admin', 'default', 'about/' + app)),
|
||||||
]),
|
]),
|
||||||
('web2py.com', False, 'http://www.web2py.com', [
|
('web2py.com', False, 'http://www.web2py.com', [
|
||||||
(T('Download'),False,'http://www.web2py.com/examples/default/download'),
|
(T('Download'), False,
|
||||||
(T('Support'),False,'http://www.web2py.com/examples/default/support'),
|
'http://www.web2py.com/examples/default/download'),
|
||||||
|
(T('Support'), False,
|
||||||
|
'http://www.web2py.com/examples/default/support'),
|
||||||
(T('Demo'), False, 'http://web2py.com/demo_admin'),
|
(T('Demo'), False, 'http://web2py.com/demo_admin'),
|
||||||
(T('Quick Examples'),False,'http://web2py.com/examples/default/examples'),
|
(T('Quick Examples'), False,
|
||||||
|
'http://web2py.com/examples/default/examples'),
|
||||||
(T('FAQ'), False, 'http://web2py.com/AlterEgo'),
|
(T('FAQ'), False, 'http://web2py.com/AlterEgo'),
|
||||||
(T('Videos'),False,'http://www.web2py.com/examples/default/videos/'),
|
(T('Videos'), False,
|
||||||
(T('Free Applications'),False,'http://web2py.com/appliances'),
|
'http://www.web2py.com/examples/default/videos/'),
|
||||||
|
(T('Free Applications'),
|
||||||
|
False, 'http://web2py.com/appliances'),
|
||||||
(T('Plugins'), False, 'http://web2py.com/plugins'),
|
(T('Plugins'), False, 'http://web2py.com/plugins'),
|
||||||
(T('Layouts'), False, 'http://web2py.com/layouts'),
|
(T('Layouts'), False, 'http://web2py.com/layouts'),
|
||||||
(T('Recipes'), False, 'http://web2pyslices.com/'),
|
(T('Recipes'), False, 'http://web2pyslices.com/'),
|
||||||
(T('Semantic'), False, 'http://web2py.com/semantic'),
|
(T('Semantic'), False, 'http://web2py.com/semantic'),
|
||||||
]),
|
]),
|
||||||
(T('Documentation'), False, 'http://www.web2py.com/book', [
|
(T('Documentation'), False, 'http://www.web2py.com/book', [
|
||||||
(T('Preface'),False,'http://www.web2py.com/book/default/chapter/00'),
|
(T('Preface'), False,
|
||||||
(T('Introduction'),False,'http://www.web2py.com/book/default/chapter/01'),
|
'http://www.web2py.com/book/default/chapter/00'),
|
||||||
(T('Python'),False,'http://www.web2py.com/book/default/chapter/02'),
|
(T('Introduction'), False,
|
||||||
(T('Overview'),False,'http://www.web2py.com/book/default/chapter/03'),
|
'http://www.web2py.com/book/default/chapter/01'),
|
||||||
(T('The Core'),False,'http://www.web2py.com/book/default/chapter/04'),
|
(T('Python'), False,
|
||||||
(T('The Views'),False,'http://www.web2py.com/book/default/chapter/05'),
|
'http://www.web2py.com/book/default/chapter/02'),
|
||||||
(T('Database'),False,'http://www.web2py.com/book/default/chapter/06'),
|
(T('Overview'), False,
|
||||||
(T('Forms and Validators'),False,'http://www.web2py.com/book/default/chapter/07'),
|
'http://www.web2py.com/book/default/chapter/03'),
|
||||||
(T('Email and SMS'),False,'http://www.web2py.com/book/default/chapter/08'),
|
(T('The Core'), False,
|
||||||
(T('Access Control'),False,'http://www.web2py.com/book/default/chapter/09'),
|
'http://www.web2py.com/book/default/chapter/04'),
|
||||||
(T('Services'),False,'http://www.web2py.com/book/default/chapter/10'),
|
(T('The Views'), False,
|
||||||
(T('Ajax Recipes'),False,'http://www.web2py.com/book/default/chapter/11'),
|
'http://www.web2py.com/book/default/chapter/05'),
|
||||||
(T('Components and Plugins'),False,'http://www.web2py.com/book/default/chapter/12'),
|
(T('Database'), False,
|
||||||
(T('Deployment Recipes'),False,'http://www.web2py.com/book/default/chapter/13'),
|
'http://www.web2py.com/book/default/chapter/06'),
|
||||||
(T('Other Recipes'),False,'http://www.web2py.com/book/default/chapter/14'),
|
(T('Forms and Validators'), False,
|
||||||
(T('Buy this book'),False,'http://stores.lulu.com/web2py'),
|
'http://www.web2py.com/book/default/chapter/07'),
|
||||||
|
(T('Email and SMS'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/08'),
|
||||||
|
(T('Access Control'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/09'),
|
||||||
|
(T('Services'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/10'),
|
||||||
|
(T('Ajax Recipes'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/11'),
|
||||||
|
(T('Components and Plugins'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/12'),
|
||||||
|
(T('Deployment Recipes'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/13'),
|
||||||
|
(T('Other Recipes'), False,
|
||||||
|
'http://www.web2py.com/book/default/chapter/14'),
|
||||||
|
(T('Buy this book'), False,
|
||||||
|
'http://stores.lulu.com/web2py'),
|
||||||
]),
|
]),
|
||||||
(T('Community'), False, None, [
|
(T('Community'), False, None, [
|
||||||
(T('Groups'),False,'http://www.web2py.com/examples/default/usergroups'),
|
(T('Groups'), False,
|
||||||
|
'http://www.web2py.com/examples/default/usergroups'),
|
||||||
(T('Twitter'), False, 'http://twitter.com/web2py'),
|
(T('Twitter'), False, 'http://twitter.com/web2py'),
|
||||||
(T('Live Chat'),False,'http://webchat.freenode.net/?channels=web2py'),
|
(T('Live Chat'), False,
|
||||||
|
'http://webchat.freenode.net/?channels=web2py'),
|
||||||
]),
|
]),
|
||||||
(T('Plugins'), False, None, [
|
(T('Plugins'), False, None, [
|
||||||
('plugin_wiki',False,'http://web2py.com/examples/default/download'),
|
('plugin_wiki', False,
|
||||||
(T('Other Plugins'),False,'http://web2py.com/plugins'),
|
'http://web2py.com/examples/default/download'),
|
||||||
(T('Layout Plugins'),False,'http://web2py.com/layouts'),
|
(T('Other Plugins'), False,
|
||||||
|
'http://web2py.com/plugins'),
|
||||||
|
(T('Layout Plugins'),
|
||||||
|
False, 'http://web2py.com/layouts'),
|
||||||
])
|
])
|
||||||
]
|
]
|
||||||
)]
|
)]
|
||||||
_()
|
if DEVELOPMENT_MENU: _()
|
||||||
|
|
||||||
|
|||||||
@@ -37,4 +37,3 @@ routers = {
|
|||||||
#NOTE! To change language in your application using these rules add this line
|
#NOTE! To change language in your application using these rules add this line
|
||||||
#in one of your models files:
|
#in one of your models files:
|
||||||
# if request.uri_language: T.force(request.uri_language)
|
# if request.uri_language: T.force(request.uri_language)
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
+2
-2
File diff suppressed because one or more lines are too long
@@ -115,6 +115,10 @@ div.flash {
|
|||||||
z-index:2000;
|
z-index:2000;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
div.flash #closeflash{color:inherit; float:right; margin-left:15px;}
|
||||||
|
.ie-lte7 div.flash #closeflash
|
||||||
|
{color:expression(this.parentNode.currentStyle['color']);float:none;position:absolute;right:4px;}
|
||||||
|
|
||||||
div.flash:hover { opacity:0.25; }
|
div.flash:hover { opacity:0.25; }
|
||||||
|
|
||||||
div.error_wrapper {display:block}
|
div.error_wrapper {display:block}
|
||||||
|
|||||||
@@ -67,10 +67,13 @@ div.controls .error{
|
|||||||
border:none;
|
border:none;
|
||||||
padding:0;
|
padding:0;
|
||||||
margin:0;
|
margin:0;
|
||||||
//display:inline; /* uncommenting this, the animation effect is lost */
|
/*display:inline;*/ /* uncommenting this, the animation effect is lost */
|
||||||
}
|
}
|
||||||
div.controls .inline-help{color:#3A87AD;}
|
div.controls .help-inline{color:#3A87AD;}
|
||||||
div.controls .error_wrapper+.inline-help{margin-left:-99999px;}
|
div.controls .error_wrapper +.help-inline {margin-left:-99999px;}
|
||||||
|
div.controls select +.error_wrapper {margin-left:5px;}
|
||||||
|
.ie-lte7 div.error{color:#fff;}
|
||||||
|
|
||||||
/* beautify brand */
|
/* beautify brand */
|
||||||
.navbar-inverse .brand{color:#c6cecc;}
|
.navbar-inverse .brand{color:#c6cecc;}
|
||||||
.navbar-inverse .brand b{display:inline-block;margin-top:-1px;}
|
.navbar-inverse .brand b{display:inline-block;margin-top:-1px;}
|
||||||
@@ -175,9 +178,6 @@ background-repeat:repeat;
|
|||||||
OTHER RULES
|
OTHER RULES
|
||||||
==============================================================*/
|
==============================================================*/
|
||||||
|
|
||||||
.navbar-inner{
|
|
||||||
position:relative; /*unnecessary ??*/
|
|
||||||
}
|
|
||||||
/* Massimo Di Pierro fixed alignment in forms with list:string */
|
/* Massimo Di Pierro fixed alignment in forms with list:string */
|
||||||
form table tr{margin-bottom:9px;}
|
form table tr{margin-bottom:9px;}
|
||||||
td.w2p_fw ul{margin-left:0px;}
|
td.w2p_fw ul{margin-left:0px;}
|
||||||
@@ -212,7 +212,7 @@ td.w2p_fw ul{margin-left:0px;}
|
|||||||
|
|
||||||
@media only screen and (max-width:979px){
|
@media only screen and (max-width:979px){
|
||||||
body{padding-top:0px;}
|
body{padding-top:0px;}
|
||||||
#navbar{bottom:-10px;left:4px;}
|
#navbar{top:5px;}
|
||||||
div.flash{right:5px;}
|
div.flash{right:5px;}
|
||||||
.dropdown-menu ul{visibility:visible;}
|
.dropdown-menu ul{visibility:visible;}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
+2
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -16,7 +16,7 @@ jQuery(function(){
|
|||||||
return match && decodeURIComponent(match[1].replace(/\+/g, ' '))||default_value;
|
return match && decodeURIComponent(match[1].replace(/\+/g, ' '))||default_value;
|
||||||
}
|
}
|
||||||
var path = params('static','social');
|
var path = params('static','social');
|
||||||
var url = window.location.href;
|
var url = encodeURIComponent(window.location.href);
|
||||||
var host = window.location.hostname;
|
var host = window.location.hostname;
|
||||||
var title = escape(jQuery('title').text());
|
var title = escape(jQuery('title').text());
|
||||||
var twit = 'http://twitter.com/home?status='+title+'%20'+url;
|
var twit = 'http://twitter.com/home?status='+title+'%20'+url;
|
||||||
@@ -27,7 +27,7 @@ jQuery(function(){
|
|||||||
jQuery('body').append(tbar);
|
jQuery('body').append(tbar);
|
||||||
var st = jQuery('#socialdrawer');
|
var st = jQuery('#socialdrawer');
|
||||||
st.css({'opacity':'.7','z-index':'3000','background':'#FFF','border':'solid 1px #666','border-width':' 1px 0 0 1px','height':'20px','width':'40px','position':'fixed','bottom':'0','right':'0','padding':'2px 5px','overflow':'hidden','-webkit-border-top-left-radius':' 12px','-moz-border-radius-topleft':' 12px','border-top-left-radius':' 12px','-moz-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','-webkit-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)'});
|
st.css({'opacity':'.7','z-index':'3000','background':'#FFF','border':'solid 1px #666','border-width':' 1px 0 0 1px','height':'20px','width':'40px','position':'fixed','bottom':'0','right':'0','padding':'2px 5px','overflow':'hidden','-webkit-border-top-left-radius':' 12px','-moz-border-radius-topleft':' 12px','border-top-left-radius':' 12px','-moz-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','-webkit-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)'});
|
||||||
jQuery('#socialdrawer a').css({'float':'left','width':'32px','margin':'3px 2px 2px 2px','padding':'0'});
|
jQuery('#socialdrawer a').css({'float':'left','width':'32px','margin':'3px 2px 2px 2px','padding':'0','cursor':'pointer'});
|
||||||
jQuery('#socialdrawer span').css({'float':'left','margin':'2px 3px','text-shadow':' 1px 1px 1px #FFF','color':'#444','font-size':'12px','line-height':'1em'});
|
jQuery('#socialdrawer span').css({'float':'left','margin':'2px 3px','text-shadow':' 1px 1px 1px #FFF','color':'#444','font-size':'12px','line-height':'1em'});
|
||||||
jQuery('#socialdrawer img').hide();
|
jQuery('#socialdrawer img').hide();
|
||||||
// hover
|
// hover
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ function web2py_event_handlers() {
|
|||||||
jQuery(function() {
|
jQuery(function() {
|
||||||
var flash = jQuery('.flash');
|
var flash = jQuery('.flash');
|
||||||
flash.hide();
|
flash.hide();
|
||||||
if(flash.html()) flash.append('<span style="float:right;">×</span>').slideDown();
|
if(flash.html()) flash.append('<span id="closeflash">×</span>').slideDown();
|
||||||
web2py_ajax_init(document);
|
web2py_ajax_init(document);
|
||||||
web2py_event_handlers();
|
web2py_event_handlers();
|
||||||
});
|
});
|
||||||
@@ -102,15 +102,20 @@ function web2py_ajax_page(method, action, data, target) {
|
|||||||
web2py_ajax_init('#'+target);
|
web2py_ajax_init('#'+target);
|
||||||
if(command)
|
if(command)
|
||||||
eval(decodeURIComponent(command));
|
eval(decodeURIComponent(command));
|
||||||
if(flash)
|
if(flash) {
|
||||||
jQuery('.flash').html(decodeURIComponent(flash)).slideDown();
|
jQuery('.flash')
|
||||||
|
.html(decodeURIComponent(flash))
|
||||||
|
.append('<span id="closeflash">×</span>')
|
||||||
|
.slideDown();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function web2py_component(action, target, timeout, times){
|
function web2py_component(action, target, timeout, times){
|
||||||
jQuery(function(){
|
jQuery(function(){
|
||||||
var element = jQuery("#" + target).get(0);
|
var jelement = jQuery("#" + target);
|
||||||
|
var element = jelement.get(0);
|
||||||
var statement = "jQuery('#" + target + "').get(0).reload();";
|
var statement = "jQuery('#" + target + "').get(0).reload();";
|
||||||
element.reload = function (){
|
element.reload = function (){
|
||||||
// Continue if times is Infinity or
|
// Continue if times is Infinity or
|
||||||
@@ -119,6 +124,7 @@ function web2py_component(action, target, timeout, times){
|
|||||||
web2py_ajax_page('get', action, null, target);} }; // reload
|
web2py_ajax_page('get', action, null, target);} }; // reload
|
||||||
// Method to check timing limit
|
// Method to check timing limit
|
||||||
element.reload_check = function (){
|
element.reload_check = function (){
|
||||||
|
if (jelement.hasClass('w2p_component_stop')) {return false;}
|
||||||
if (this.reload_counter == Infinity){return true;}
|
if (this.reload_counter == Infinity){return true;}
|
||||||
else {
|
else {
|
||||||
if (!isNaN(this.reload_counter)){
|
if (!isNaN(this.reload_counter)){
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
<?xml version="1.0" encoding="ISO-8859-1"?>{{from gluon.serializers import xml}}{{=XML(xml(response._vars,quote=False))}}
|
{{from gluon.serializers import xml}}{{=XML(xml(response._vars,quote=False))}}
|
||||||
|
|||||||
@@ -29,7 +29,7 @@
|
|||||||
device-width: Occupy full width of the screen in its current orientation
|
device-width: Occupy full width of the screen in its current orientation
|
||||||
initial-scale = 1.0 retains dimensions instead of zooming out if page height > device height
|
initial-scale = 1.0 retains dimensions instead of zooming out if page height > device height
|
||||||
user-scalable = yes allows the user to zoom in -->
|
user-scalable = yes allows the user to zoom in -->
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
|
||||||
<link rel="shortcut icon" href="{{=URL('static','images/favicon.ico')}}" type="image/x-icon">
|
<link rel="shortcut icon" href="{{=URL('static','images/favicon.ico')}}" type="image/x-icon">
|
||||||
<link rel="apple-touch-icon" href="{{=URL('static','images/favicon.png')}}">
|
<link rel="apple-touch-icon" href="{{=URL('static','images/favicon.png')}}">
|
||||||
@@ -76,7 +76,7 @@
|
|||||||
<span class="icon-bar"></span>
|
<span class="icon-bar"></span>
|
||||||
<span class="icon-bar"></span>
|
<span class="icon-bar"></span>
|
||||||
</button>
|
</button>
|
||||||
<a class="brand" href="http://www.web2py.com/"><b>web<span>2</span>py</b>™ </a>
|
{{=response.logo or ''}}
|
||||||
<ul id="navbar" class="nav pull-right">{{='auth' in globals() and auth.navbar(mode="dropdown") or ''}}</ul>
|
<ul id="navbar" class="nav pull-right">{{='auth' in globals() and auth.navbar(mode="dropdown") or ''}}</ul>
|
||||||
<div class="nav-collapse">
|
<div class="nav-collapse">
|
||||||
{{is_mobile=request.user_agent().is_mobile}}
|
{{is_mobile=request.user_agent().is_mobile}}
|
||||||
@@ -152,7 +152,14 @@
|
|||||||
<script src="{{=URL('static','js/dd_belatedpng.js')}}"></script>
|
<script src="{{=URL('static','js/dd_belatedpng.js')}}"></script>
|
||||||
<script> DD_belatedPNG.fix('img, .png_bg'); //fix any <img> or .png_bg background-images </script>
|
<script> DD_belatedPNG.fix('img, .png_bg'); //fix any <img> or .png_bg background-images </script>
|
||||||
<![endif]-->
|
<![endif]-->
|
||||||
{{if response.google_analytics_id:}}<script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '{{=response.google_analytics_id}}']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> {{pass}}
|
|
||||||
|
{{if response.google_analytics_id:}}
|
||||||
|
<script src="{{=URL('static','js/analytics.js')}}"></script>
|
||||||
|
<script type="text/javascript">
|
||||||
|
analytics.initialize({
|
||||||
|
'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
|
||||||
|
});</script>
|
||||||
|
{{pass}}
|
||||||
<script src="{{=URL('static','js/share.js',vars=dict(static=URL('static','images')))}}"></script>
|
<script src="{{=URL('static','js/share.js',vars=dict(static=URL('static','images')))}}"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -61,8 +61,3 @@ sys.path = [path]+[p for p in sys.path if not p==path]
|
|||||||
import gluon.main
|
import gluon.main
|
||||||
|
|
||||||
wsgiref.handlers.CGIHandler().run(gluon.main.wsgibase)
|
wsgiref.handlers.CGIHandler().run(gluon.main.wsgibase)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -51,8 +51,3 @@ if SOFTCRON:
|
|||||||
global_settings.web2py_crontype = 'soft'
|
global_settings.web2py_crontype = 'soft'
|
||||||
|
|
||||||
fcgi.WSGIServer(application, bindAddress='/tmp/fcgi.sock').run()
|
fcgi.WSGIServer(application, bindAddress='/tmp/fcgi.sock').run()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+7
-5
@@ -78,6 +78,12 @@ def wsgiapp(env, res):
|
|||||||
"""Return the wsgiapp"""
|
"""Return the wsgiapp"""
|
||||||
env['PATH_INFO'] = env['PATH_INFO'].decode('latin1').encode('utf8')
|
env['PATH_INFO'] = env['PATH_INFO'].decode('latin1').encode('utf8')
|
||||||
|
|
||||||
|
#when using the blobstore image uploader GAE dev SDK passes these as unicode
|
||||||
|
# they should be regular strings as they are parts of URLs
|
||||||
|
env['wsgi.url_scheme'] = str(env['wsgi.url_scheme'])
|
||||||
|
env['QUERY_STRING'] = str(env['QUERY_STRING'])
|
||||||
|
env['SERVER_NAME'] = str(env['SERVER_NAME'])
|
||||||
|
|
||||||
#this deals with a problem where GAE development server seems to forget
|
#this deals with a problem where GAE development server seems to forget
|
||||||
# the path between requests
|
# the path between requests
|
||||||
if global_settings.web2py_runtime == 'gae:development':
|
if global_settings.web2py_runtime == 'gae:development':
|
||||||
@@ -91,14 +97,10 @@ def wsgiapp(env, res):
|
|||||||
if LOG_STATS or DEBUG:
|
if LOG_STATS or DEBUG:
|
||||||
wsgiapp = log_stats(wsgiapp)
|
wsgiapp = log_stats(wsgiapp)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Run the wsgi app"""
|
"""Run the wsgi app"""
|
||||||
run_wsgi_app(wsgiapp)
|
run_wsgi_app(wsgiapp)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -42,14 +42,3 @@ if 0:
|
|||||||
mail = Mail()
|
mail = Mail()
|
||||||
service = Service()
|
service = Service()
|
||||||
plugins = PluginManager()
|
plugins = PluginManager()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+20
-13
@@ -23,6 +23,7 @@ from http import HTTP
|
|||||||
if not global_settings.web2py_runtime_gae:
|
if not global_settings.web2py_runtime_gae:
|
||||||
import site
|
import site
|
||||||
|
|
||||||
|
|
||||||
def apath(path='', r=None):
|
def apath(path='', r=None):
|
||||||
"""
|
"""
|
||||||
Builds a path inside an application folder
|
Builds a path inside an application folder
|
||||||
@@ -95,6 +96,7 @@ def app_pack_compiled(app, request, raise_ex=False):
|
|||||||
raise
|
raise
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def app_cleanup(app, request):
|
def app_cleanup(app, request):
|
||||||
"""
|
"""
|
||||||
Removes session, cache and error files
|
Removes session, cache and error files
|
||||||
@@ -158,6 +160,7 @@ def app_compile(app, request):
|
|||||||
remove_compiled_application(folder)
|
remove_compiled_application(folder)
|
||||||
return tb
|
return tb
|
||||||
|
|
||||||
|
|
||||||
def app_create(app, request, force=False, key=None, info=False):
|
def app_create(app, request, force=False, key=None, info=False):
|
||||||
"""
|
"""
|
||||||
Create a copy of welcome.w2p (scaffolding) app
|
Create a copy of welcome.w2p (scaffolding) app
|
||||||
@@ -186,8 +189,9 @@ def app_create(app, request,force=False,key=None,info=False):
|
|||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
w2p_unpack('welcome.w2p', path)
|
w2p_unpack('welcome.w2p', path)
|
||||||
for subfolder in ['models','views','controllers', 'databases',
|
for subfolder in [
|
||||||
'modules','cron','errors','sessions',
|
'models', 'views', 'controllers', 'databases',
|
||||||
|
'modules', 'cron', 'errors', 'sessions', 'cache',
|
||||||
'languages', 'static', 'private', 'uploads']:
|
'languages', 'static', 'private', 'uploads']:
|
||||||
subpath = os.path.join(path, subfolder)
|
subpath = os.path.join(path, subfolder)
|
||||||
if not os.path.exists(subpath):
|
if not os.path.exists(subpath):
|
||||||
@@ -283,6 +287,7 @@ def app_uninstall(app, request):
|
|||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def plugin_pack(app, plugin_name, request):
|
def plugin_pack(app, plugin_name, request):
|
||||||
"""
|
"""
|
||||||
Builds a w2p package for the application
|
Builds a w2p package for the application
|
||||||
@@ -302,12 +307,14 @@ def plugin_pack(app, plugin_name, request):
|
|||||||
filename of the w2p file or None on error
|
filename of the w2p file or None on error
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
filename = apath('../deposit/web2py.plugin.%s.w2p' % plugin_name, request)
|
filename = apath(
|
||||||
|
'../deposit/web2py.plugin.%s.w2p' % plugin_name, request)
|
||||||
w2p_pack_plugin(filename, apath(app, request), plugin_name)
|
w2p_pack_plugin(filename, apath(app, request), plugin_name)
|
||||||
return filename
|
return filename
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def plugin_install(app, fobj, request, filename):
|
def plugin_install(app, fobj, request, filename):
|
||||||
"""
|
"""
|
||||||
Installs an application:
|
Installs an application:
|
||||||
@@ -345,6 +352,7 @@ def plugin_install(app, fobj, request, filename):
|
|||||||
os.unlink(upname)
|
os.unlink(upname)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def check_new_version(myversion, version_URL):
|
def check_new_version(myversion, version_URL):
|
||||||
"""
|
"""
|
||||||
Compares current web2py's version with the latest stable web2py version.
|
Compares current web2py's version with the latest stable web2py version.
|
||||||
@@ -375,6 +383,7 @@ def check_new_version(myversion, version_URL):
|
|||||||
else:
|
else:
|
||||||
return False, version
|
return False, version
|
||||||
|
|
||||||
|
|
||||||
def unzip(filename, dir, subfolder=''):
|
def unzip(filename, dir, subfolder=''):
|
||||||
"""
|
"""
|
||||||
Unzips filename into dir (.zip only, no .gz etc)
|
Unzips filename into dir (.zip only, no .gz etc)
|
||||||
@@ -382,7 +391,7 @@ def unzip(filename, dir, subfolder=''):
|
|||||||
"""
|
"""
|
||||||
filename = abspath(filename)
|
filename = abspath(filename)
|
||||||
if not zipfile.is_zipfile(filename):
|
if not zipfile.is_zipfile(filename):
|
||||||
raise RuntimeError, 'Not a valid zipfile'
|
raise RuntimeError('Not a valid zipfile')
|
||||||
zf = zipfile.ZipFile(filename)
|
zf = zipfile.ZipFile(filename)
|
||||||
if not subfolder.endswith('/'):
|
if not subfolder.endswith('/'):
|
||||||
subfolder = subfolder + '/'
|
subfolder = subfolder + '/'
|
||||||
@@ -450,20 +459,25 @@ def upgrade(request, url='http://web2py.com'):
|
|||||||
except Exception, e:
|
except Exception, e:
|
||||||
return False, e
|
return False, e
|
||||||
|
|
||||||
|
|
||||||
def add_path_first(path):
|
def add_path_first(path):
|
||||||
sys.path = [path]+[p for p in sys.path if (not p==path and not p==(path+'/'))]
|
sys.path = [path] + [p for p in sys.path if (
|
||||||
|
not p == path and not p == (path + '/'))]
|
||||||
if not global_settings.web2py_runtime_gae:
|
if not global_settings.web2py_runtime_gae:
|
||||||
site.addsitedir(path)
|
site.addsitedir(path)
|
||||||
|
|
||||||
|
|
||||||
def create_missing_folders():
|
def create_missing_folders():
|
||||||
if not global_settings.web2py_runtime_gae:
|
if not global_settings.web2py_runtime_gae:
|
||||||
for path in ('applications', 'deposit', 'site-packages', 'logs'):
|
for path in ('applications', 'deposit', 'site-packages', 'logs'):
|
||||||
path = abspath(path, gluon=True)
|
path = abspath(path, gluon=True)
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
os.mkdir(path)
|
os.mkdir(path)
|
||||||
paths = (global_settings.gluon_parent, abspath('site-packages', gluon=True), abspath('gluon', gluon=True), '')
|
paths = (global_settings.gluon_parent, abspath(
|
||||||
|
'site-packages', gluon=True), abspath('gluon', gluon=True), '')
|
||||||
[add_path_first(path) for path in paths]
|
[add_path_first(path) for path in paths]
|
||||||
|
|
||||||
|
|
||||||
def create_missing_app_folders(request):
|
def create_missing_app_folders(request):
|
||||||
if not global_settings.web2py_runtime_gae:
|
if not global_settings.web2py_runtime_gae:
|
||||||
if request.folder not in global_settings.app_folders:
|
if request.folder not in global_settings.app_folders:
|
||||||
@@ -474,10 +488,3 @@ def create_missing_app_folders(request):
|
|||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
os.mkdir(path)
|
os.mkdir(path)
|
||||||
global_settings.app_folders.add(request.folder)
|
global_settings.app_folders.add(request.folder)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+22
-11
@@ -40,6 +40,7 @@ __all__ = ['Cache', 'lazy_cache']
|
|||||||
|
|
||||||
DEFAULT_TIME_EXPIRE = 300
|
DEFAULT_TIME_EXPIRE = 300
|
||||||
|
|
||||||
|
|
||||||
class CacheAbstract(object):
|
class CacheAbstract(object):
|
||||||
"""
|
"""
|
||||||
Abstract class for cache implementations.
|
Abstract class for cache implementations.
|
||||||
@@ -130,6 +131,7 @@ class CacheAbstract(object):
|
|||||||
if r.match(str(key)):
|
if r.match(str(key)):
|
||||||
del storage[key]
|
del storage[key]
|
||||||
|
|
||||||
|
|
||||||
class CacheInRam(CacheAbstract):
|
class CacheInRam(CacheAbstract):
|
||||||
"""
|
"""
|
||||||
Ram based caching
|
Ram based caching
|
||||||
@@ -145,10 +147,13 @@ class CacheInRam(CacheAbstract):
|
|||||||
def __init__(self, request=None):
|
def __init__(self, request=None):
|
||||||
self.initialized = False
|
self.initialized = False
|
||||||
self.request = request
|
self.request = request
|
||||||
|
self.storage = {}
|
||||||
|
|
||||||
def initialize(self):
|
def initialize(self):
|
||||||
if self.initialized: return
|
if self.initialized:
|
||||||
else: self.initialized = True
|
return
|
||||||
|
else:
|
||||||
|
self.initialized = True
|
||||||
self.locker.acquire()
|
self.locker.acquire()
|
||||||
request = self.request
|
request = self.request
|
||||||
if request:
|
if request:
|
||||||
@@ -172,7 +177,8 @@ class CacheInRam(CacheAbstract):
|
|||||||
self._clear(storage, regex)
|
self._clear(storage, regex)
|
||||||
|
|
||||||
if not CacheAbstract.cache_stats_name in storage.keys():
|
if not CacheAbstract.cache_stats_name in storage.keys():
|
||||||
storage[CacheAbstract.cache_stats_name] = {'hit_total': 0,'misses': 0}
|
storage[CacheAbstract.cache_stats_name] = {
|
||||||
|
'hit_total': 0, 'misses': 0}
|
||||||
|
|
||||||
self.locker.release()
|
self.locker.release()
|
||||||
|
|
||||||
@@ -269,14 +275,15 @@ class CacheOnDisk(CacheAbstract):
|
|||||||
try:
|
try:
|
||||||
storage = shelve.open(self.shelve_name)
|
storage = shelve.open(self.shelve_name)
|
||||||
except:
|
except:
|
||||||
logger.error('corrupted cache file %s, will try rebuild it' \
|
logger.error('corrupted cache file %s, will try rebuild it'
|
||||||
% (self.shelve_name))
|
% (self.shelve_name))
|
||||||
storage = None
|
storage = None
|
||||||
if not storage and os.path.exists(self.shelve_name):
|
if not storage and os.path.exists(self.shelve_name):
|
||||||
os.unlink(self.shelve_name)
|
os.unlink(self.shelve_name)
|
||||||
storage = shelve.open(self.shelve_name)
|
storage = shelve.open(self.shelve_name)
|
||||||
if not CacheAbstract.cache_stats_name in storage.keys():
|
if not CacheAbstract.cache_stats_name in storage.keys():
|
||||||
storage[CacheAbstract.cache_stats_name] = {'hit_total':0, 'misses': 0}
|
storage[CacheAbstract.cache_stats_name] = {
|
||||||
|
'hit_total': 0, 'misses': 0}
|
||||||
storage.sync()
|
storage.sync()
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
if storage:
|
if storage:
|
||||||
@@ -286,7 +293,8 @@ class CacheOnDisk(CacheAbstract):
|
|||||||
portalocker.unlock(locker)
|
portalocker.unlock(locker)
|
||||||
locker.close()
|
locker.close()
|
||||||
locked = False
|
locked = False
|
||||||
raise RuntimeError, 'unable to create/re-create cache file %s' % self.shelve_name
|
raise RuntimeError(
|
||||||
|
'unable to create/re-create cache file %s' % self.shelve_name)
|
||||||
self.locker = locker
|
self.locker = locker
|
||||||
self.locked = locked
|
self.locked = locked
|
||||||
self.storage = storage
|
self.storage = storage
|
||||||
@@ -296,10 +304,13 @@ class CacheOnDisk(CacheAbstract):
|
|||||||
self.initialized = False
|
self.initialized = False
|
||||||
self.request = request
|
self.request = request
|
||||||
self.folder = folder
|
self.folder = folder
|
||||||
|
self.storage = {}
|
||||||
|
|
||||||
def initialize(self):
|
def initialize(self):
|
||||||
if self.initialized: return
|
if self.initialized:
|
||||||
else: self.initialized = True
|
return
|
||||||
|
else:
|
||||||
|
self.initialized = True
|
||||||
folder = self.folder
|
folder = self.folder
|
||||||
request = self.request
|
request = self.request
|
||||||
|
|
||||||
@@ -365,6 +376,7 @@ class CacheOnDisk(CacheAbstract):
|
|||||||
self._close_shelve_and_unlock()
|
self._close_shelve_and_unlock()
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
class CacheAction(object):
|
class CacheAction(object):
|
||||||
def __init__(self, func, key, time_expire, cache, cache_model):
|
def __init__(self, func, key, time_expire, cache, cache_model):
|
||||||
self.__name__ = func.__name__
|
self.__name__ = func.__name__
|
||||||
@@ -374,6 +386,7 @@ class CacheAction(object):
|
|||||||
self.time_expire = time_expire
|
self.time_expire = time_expire
|
||||||
self.cache = cache
|
self.cache = cache
|
||||||
self.cache_model = cache_model
|
self.cache_model = cache_model
|
||||||
|
|
||||||
def __call__(self, *a, **b):
|
def __call__(self, *a, **b):
|
||||||
if not self.key:
|
if not self.key:
|
||||||
key2 = self.__name__ + ':' + repr(a) + ':' + repr(b)
|
key2 = self.__name__ + ':' + repr(a) + ':' + repr(b)
|
||||||
@@ -483,12 +496,10 @@ def lazy_cache(key=None,time_expire=None,cache_model='ram'):
|
|||||||
"""
|
"""
|
||||||
def decorator(f, key=key, time_expire=time_expire, cache_model=cache_model):
|
def decorator(f, key=key, time_expire=time_expire, cache_model=cache_model):
|
||||||
key = key or repr(f)
|
key = key or repr(f)
|
||||||
|
|
||||||
def g(*c, **d):
|
def g(*c, **d):
|
||||||
from gluon import current
|
from gluon import current
|
||||||
return current.cache(key, time_expire, cache_model)(f)(*c, **d)
|
return current.cache(key, time_expire, cache_model)(f)(*c, **d)
|
||||||
g.__name__ = f.__name__
|
g.__name__ = f.__name__
|
||||||
return g
|
return g
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -51,10 +51,3 @@ def getcfs(key, filename, filter=None):
|
|||||||
cfs[key] = (t, data)
|
cfs[key] = (t, data)
|
||||||
cfs_lock.release()
|
cfs_lock.release()
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+35
-24
@@ -95,6 +95,7 @@ _TEST()
|
|||||||
CACHED_REGEXES = {}
|
CACHED_REGEXES = {}
|
||||||
CACHED_REGEXES_MAX_SIZE = 1000
|
CACHED_REGEXES_MAX_SIZE = 1000
|
||||||
|
|
||||||
|
|
||||||
def re_compile(regex):
|
def re_compile(regex):
|
||||||
try:
|
try:
|
||||||
return CACHED_REGEXES[regex]
|
return CACHED_REGEXES[regex]
|
||||||
@@ -104,6 +105,7 @@ def re_compile(regex):
|
|||||||
compiled_regex = CACHED_REGEXES[regex] = re.compile(regex)
|
compiled_regex = CACHED_REGEXES[regex] = re.compile(regex)
|
||||||
return compiled_regex
|
return compiled_regex
|
||||||
|
|
||||||
|
|
||||||
class mybuiltin(object):
|
class mybuiltin(object):
|
||||||
"""
|
"""
|
||||||
NOTE could simple use a dict and populate it,
|
NOTE could simple use a dict and populate it,
|
||||||
@@ -114,10 +116,12 @@ class mybuiltin(object):
|
|||||||
try:
|
try:
|
||||||
return getattr(__builtin__, key)
|
return getattr(__builtin__, key)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
|
|
||||||
def __setitem__(self, key, value):
|
def __setitem__(self, key, value):
|
||||||
setattr(self, key, value)
|
setattr(self, key, value)
|
||||||
|
|
||||||
|
|
||||||
def LOAD(c=None, f='index', args=None, vars=None,
|
def LOAD(c=None, f='index', args=None, vars=None,
|
||||||
extension=None, target=None, ajax=False, ajax_trap=False,
|
extension=None, target=None, ajax=False, ajax_trap=False,
|
||||||
url=None, user_signature=False, timeout=None, times=1,
|
url=None, user_signature=False, timeout=None, times=1,
|
||||||
@@ -134,7 +138,8 @@ def LOAD(c=None, f='index', args=None, vars=None,
|
|||||||
is added on page loading without delay.
|
is added on page loading without delay.
|
||||||
"""
|
"""
|
||||||
from html import TAG, DIV, URL, SCRIPT, XML
|
from html import TAG, DIV, URL, SCRIPT, XML
|
||||||
if args is None: args = []
|
if args is None:
|
||||||
|
args = []
|
||||||
vars = Storage(vars or {})
|
vars = Storage(vars or {})
|
||||||
target = target or 'c' + str(random.random())[2:]
|
target = target or 'c' + str(random.random())[2:]
|
||||||
attr['_id'] = target
|
attr['_id'] = target
|
||||||
@@ -160,7 +165,8 @@ def LOAD(c=None, f='index', args=None, vars=None,
|
|||||||
if not isinstance(timeout, (int, long)):
|
if not isinstance(timeout, (int, long)):
|
||||||
raise ValueError("Timeout argument must be an integer or None")
|
raise ValueError("Timeout argument must be an integer or None")
|
||||||
elif timeout <= 0:
|
elif timeout <= 0:
|
||||||
raise ValueError("Timeout argument must be greater than zero or None")
|
raise ValueError(
|
||||||
|
"Timeout argument must be greater than zero or None")
|
||||||
statement = "web2py_component('%s','%s', %s, %s);" \
|
statement = "web2py_component('%s','%s', %s, %s);" \
|
||||||
% (url, target, timeout, times)
|
% (url, target, timeout, times)
|
||||||
else:
|
else:
|
||||||
@@ -186,7 +192,7 @@ def LOAD(c=None, f='index', args=None, vars=None,
|
|||||||
other_request.post_vars = Storage()
|
other_request.post_vars = Storage()
|
||||||
other_response = Response()
|
other_response = Response()
|
||||||
other_request.env.path_info = '/' + \
|
other_request.env.path_info = '/' + \
|
||||||
'/'.join([request.application,c,f] + \
|
'/'.join([request.application, c, f] +
|
||||||
map(str, other_request.args))
|
map(str, other_request.args))
|
||||||
other_request.env.query_string = \
|
other_request.env.query_string = \
|
||||||
vars and URL(vars=vars).split('?')[1] or ''
|
vars and URL(vars=vars).split('?')[1] or ''
|
||||||
@@ -196,7 +202,7 @@ def LOAD(c=None, f='index', args=None, vars=None,
|
|||||||
other_request.env.http_web2py_component_element = target
|
other_request.env.http_web2py_component_element = target
|
||||||
other_response.view = '%s/%s.%s' % (c, f, other_request.extension)
|
other_response.view = '%s/%s.%s' % (c, f, other_request.extension)
|
||||||
|
|
||||||
other_environment = copy.copy(current.globalenv) ### NASTY
|
other_environment = copy.copy(current.globalenv) # NASTY
|
||||||
|
|
||||||
other_response._view_environment = other_environment
|
other_response._view_environment = other_environment
|
||||||
other_response.generic_patterns = \
|
other_response.generic_patterns = \
|
||||||
@@ -225,17 +231,18 @@ def LOAD(c=None, f='index', args=None, vars=None,
|
|||||||
return TAG[''](DIV(XML(page), **attr), script)
|
return TAG[''](DIV(XML(page), **attr), script)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LoadFactory(object):
|
class LoadFactory(object):
|
||||||
"""
|
"""
|
||||||
Attention: this helper is new and experimental
|
Attention: this helper is new and experimental
|
||||||
"""
|
"""
|
||||||
def __init__(self, environment):
|
def __init__(self, environment):
|
||||||
self.environment = environment
|
self.environment = environment
|
||||||
|
|
||||||
def __call__(self, c=None, f='index', args=None, vars=None,
|
def __call__(self, c=None, f='index', args=None, vars=None,
|
||||||
extension=None, target=None, ajax=False, ajax_trap=False,
|
extension=None, target=None, ajax=False, ajax_trap=False,
|
||||||
url=None, user_signature=False, content='loading...', **attr):
|
url=None, user_signature=False, content='loading...', **attr):
|
||||||
if args is None: args = []
|
if args is None:
|
||||||
|
args = []
|
||||||
vars = Storage(vars or {})
|
vars = Storage(vars or {})
|
||||||
import globals
|
import globals
|
||||||
target = target or 'c' + str(random.random())[2:]
|
target = target or 'c' + str(random.random())[2:]
|
||||||
@@ -266,7 +273,7 @@ class LoadFactory(object):
|
|||||||
other_request.post_vars = Storage()
|
other_request.post_vars = Storage()
|
||||||
other_response = globals.Response()
|
other_response = globals.Response()
|
||||||
other_request.env.path_info = '/' + \
|
other_request.env.path_info = '/' + \
|
||||||
'/'.join([request.application,c,f] + \
|
'/'.join([request.application, c, f] +
|
||||||
map(str, other_request.args))
|
map(str, other_request.args))
|
||||||
other_request.env.query_string = \
|
other_request.env.query_string = \
|
||||||
vars and html.URL(vars=vars).split('?')[1] or ''
|
vars and html.URL(vars=vars).split('?')[1] or ''
|
||||||
@@ -355,12 +362,14 @@ OLD IMPLEMENTATION:
|
|||||||
file.close()
|
file.close()
|
||||||
imp.release_lock()
|
imp.release_lock()
|
||||||
if not module:
|
if not module:
|
||||||
raise ImportError, "cannot find module %s in %s" % (filename, modulepath)
|
raise ImportError, "cannot find module %s in %s" % (
|
||||||
|
filename, modulepath)
|
||||||
return module
|
return module
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_base_environment_ = dict((k, getattr(html, k)) for k in html.__all__)
|
_base_environment_ = dict((k, getattr(html, k)) for k in html.__all__)
|
||||||
_base_environment_.update((k,getattr(validators,k)) for k in validators.__all__)
|
_base_environment_.update(
|
||||||
|
(k, getattr(validators, k)) for k in validators.__all__)
|
||||||
_base_environment_['__builtins__'] = __builtins__
|
_base_environment_['__builtins__'] = __builtins__
|
||||||
_base_environment_['HTTP'] = HTTP
|
_base_environment_['HTTP'] = HTTP
|
||||||
_base_environment_['redirect'] = redirect
|
_base_environment_['redirect'] = redirect
|
||||||
@@ -372,6 +381,7 @@ _base_environment_['SQLFORM'] = SQLFORM
|
|||||||
_base_environment_['SQLTABLE'] = SQLTABLE
|
_base_environment_['SQLTABLE'] = SQLTABLE
|
||||||
_base_environment_['LOAD'] = LOAD
|
_base_environment_['LOAD'] = LOAD
|
||||||
|
|
||||||
|
|
||||||
def build_environment(request, response, session, store_current=True):
|
def build_environment(request, response, session, store_current=True):
|
||||||
"""
|
"""
|
||||||
Build the environment dictionary into which web2py files are executed.
|
Build the environment dictionary into which web2py files are executed.
|
||||||
@@ -386,7 +396,8 @@ def build_environment(request, response, session, store_current=True):
|
|||||||
response.models_to_run = [r'^\w+\.py$', r'^%s/\w+\.py$' % request.controller,
|
response.models_to_run = [r'^\w+\.py$', r'^%s/\w+\.py$' % request.controller,
|
||||||
r'^%s/%s/\w+\.py$' % (request.controller, request.function)]
|
r'^%s/%s/\w+\.py$' % (request.controller, request.function)]
|
||||||
|
|
||||||
t = environment['T'] = translator(request)
|
t = environment['T'] = translator(os.path.join(request.folder,'languages'),
|
||||||
|
request.env.http_accept_language)
|
||||||
c = environment['cache'] = Cache(request)
|
c = environment['cache'] = Cache(request)
|
||||||
|
|
||||||
if store_current:
|
if store_current:
|
||||||
@@ -403,7 +414,7 @@ def build_environment(request, response, session, store_current=True):
|
|||||||
elif is_pypy: # apply the same hack to pypy too
|
elif is_pypy: # apply the same hack to pypy too
|
||||||
__builtins__ = mybuiltin()
|
__builtins__ = mybuiltin()
|
||||||
else:
|
else:
|
||||||
__builtins__['__import__'] = __builtin__.__import__ ### WHY?
|
__builtins__['__import__'] = __builtin__.__import__ # WHY?
|
||||||
environment['request'] = request
|
environment['request'] = request
|
||||||
environment['response'] = response
|
environment['response'] = response
|
||||||
environment['session'] = session
|
environment['session'] = session
|
||||||
@@ -415,6 +426,7 @@ def build_environment(request, response, session, store_current=True):
|
|||||||
custom_import_install()
|
custom_import_install()
|
||||||
return environment
|
return environment
|
||||||
|
|
||||||
|
|
||||||
def save_pyc(filename):
|
def save_pyc(filename):
|
||||||
"""
|
"""
|
||||||
Bytecode compiles the file `filename`
|
Bytecode compiles the file `filename`
|
||||||
@@ -431,7 +443,7 @@ def read_pyc(filename):
|
|||||||
"""
|
"""
|
||||||
data = read_file(filename, 'rb')
|
data = read_file(filename, 'rb')
|
||||||
if not is_gae and data[:4] != imp.get_magic():
|
if not is_gae and data[:4] != imp.get_magic():
|
||||||
raise SystemError, 'compiled code is incompatible'
|
raise SystemError('compiled code is incompatible')
|
||||||
return marshal.loads(data[8:])
|
return marshal.loads(data[8:])
|
||||||
|
|
||||||
|
|
||||||
@@ -441,8 +453,11 @@ def compile_views(folder):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
path = pjoin(folder, 'views')
|
path = pjoin(folder, 'views')
|
||||||
for file in listdir(path, '^[\w/\-]+(\.\w+)+$'):
|
for file in listdir(path, '^[\w/\-]+(\.\w+)*$'):
|
||||||
|
try:
|
||||||
data = parse_template(file, path)
|
data = parse_template(file, path)
|
||||||
|
except Exception, e:
|
||||||
|
raise Exception("%s in %s" % (e, file))
|
||||||
filename = ('views/%s.py' % file).replace('/', '_').replace('\\', '_')
|
filename = ('views/%s.py' % file).replace('/', '_').replace('\\', '_')
|
||||||
filename = pjoin(folder, 'compiled', filename)
|
filename = pjoin(folder, 'compiled', filename)
|
||||||
write_file(filename, data)
|
write_file(filename, data)
|
||||||
@@ -500,11 +515,11 @@ def run_models_in(environment):
|
|||||||
for model in listdir(cpath, '^models_\w+\.pyc$', 0):
|
for model in listdir(cpath, '^models_\w+\.pyc$', 0):
|
||||||
restricted(read_pyc(model), environment, layer=model)
|
restricted(read_pyc(model), environment, layer=model)
|
||||||
path = pjoin(cpath, 'models')
|
path = pjoin(cpath, 'models')
|
||||||
models = listdir(path, '^\w+\.pyc$',0,sort=False)
|
models = listdir(path, '^\w+\.pyc$', 0)
|
||||||
compiled = True
|
compiled = True
|
||||||
else:
|
else:
|
||||||
path = pjoin(folder, 'models')
|
path = pjoin(folder, 'models')
|
||||||
models = listdir(path, '^\w+\.py$',0,sort=False)
|
models = listdir(path, '^\w+\.py$', 0)
|
||||||
compiled = False
|
compiled = False
|
||||||
n = len(path) + 1
|
n = len(path) + 1
|
||||||
for model in models:
|
for model in models:
|
||||||
@@ -548,7 +563,8 @@ def run_controller_in(controller, function, environment):
|
|||||||
# TESTING: adjust the path to include site packages
|
# TESTING: adjust the path to include site packages
|
||||||
from settings import global_settings
|
from settings import global_settings
|
||||||
from admin import abspath, add_path_first
|
from admin import abspath, add_path_first
|
||||||
paths = (global_settings.gluon_parent, abspath('site-packages', gluon=True), abspath('gluon', gluon=True), '')
|
paths = (global_settings.gluon_parent, abspath(
|
||||||
|
'site-packages', gluon=True), abspath('gluon', gluon=True), '')
|
||||||
[add_path_first(path) for path in paths]
|
[add_path_first(path) for path in paths]
|
||||||
# TESTING END
|
# TESTING END
|
||||||
|
|
||||||
@@ -590,6 +606,7 @@ def run_controller_in(controller, function, environment):
|
|||||||
vars = vars.xml()
|
vars = vars.xml()
|
||||||
return vars
|
return vars
|
||||||
|
|
||||||
|
|
||||||
def run_view_in(environment):
|
def run_view_in(environment):
|
||||||
"""
|
"""
|
||||||
Executes the view for the requested action.
|
Executes the view for the requested action.
|
||||||
@@ -655,6 +672,7 @@ def run_view_in(environment):
|
|||||||
context=environment)
|
context=environment)
|
||||||
restricted(ccode, environment, layer)
|
restricted(ccode, environment, layer)
|
||||||
|
|
||||||
|
|
||||||
def remove_compiled_application(folder):
|
def remove_compiled_application(folder):
|
||||||
"""
|
"""
|
||||||
Deletes the folder `compiled` containing the compiled application.
|
Deletes the folder `compiled` containing the compiled application.
|
||||||
@@ -700,10 +718,3 @@ def test():
|
|||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import doctest
|
import doctest
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -644,6 +644,7 @@ CONTENT_TYPE = {
|
|||||||
'.wmls': 'text/vnd.wap.wmlscript',
|
'.wmls': 'text/vnd.wap.wmlscript',
|
||||||
'.wmv': 'video/x-ms-wmv',
|
'.wmv': 'video/x-ms-wmv',
|
||||||
'.wmx': 'audio/x-ms-asx',
|
'.wmx': 'audio/x-ms-asx',
|
||||||
|
'.woff': 'application/font-woff',
|
||||||
'.wp': 'application/vnd.wordperfect',
|
'.wp': 'application/vnd.wordperfect',
|
||||||
'.wp4': 'application/vnd.wordperfect',
|
'.wp4': 'application/vnd.wordperfect',
|
||||||
'.wp5': 'application/vnd.wordperfect',
|
'.wp5': 'application/vnd.wordperfect',
|
||||||
@@ -717,10 +718,3 @@ def contenttype(filename, default='text/plain'):
|
|||||||
if default.startswith('text/'):
|
if default.startswith('text/'):
|
||||||
default += '; charset=utf-8'
|
default += '; charset=utf-8'
|
||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import urllib
|
|||||||
|
|
||||||
_known_tuple_types = {}
|
_known_tuple_types = {}
|
||||||
|
|
||||||
|
|
||||||
class NamedTupleBase(tuple):
|
class NamedTupleBase(tuple):
|
||||||
"""Base class for named tuples with the __new__ operator set, named tuples
|
"""Base class for named tuples with the __new__ operator set, named tuples
|
||||||
yielded by the namedtuple() function will subclass this and add
|
yielded by the namedtuple() function will subclass this and add
|
||||||
@@ -37,6 +38,7 @@ class NamedTupleBase(tuple):
|
|||||||
args = tuple(values)
|
args = tuple(values)
|
||||||
return tuple.__new__(cls, args)
|
return tuple.__new__(cls, args)
|
||||||
|
|
||||||
|
|
||||||
def namedtuple(typename, fieldnames):
|
def namedtuple(typename, fieldnames):
|
||||||
"""
|
"""
|
||||||
>>> import namedtuples
|
>>> import namedtuples
|
||||||
@@ -75,24 +77,26 @@ def namedtuple(typename, fieldnames):
|
|||||||
# Done
|
# Done
|
||||||
return new_tuple_type
|
return new_tuple_type
|
||||||
|
|
||||||
|
|
||||||
class AIM:
|
class AIM:
|
||||||
|
|
||||||
class AIMError(Exception):
|
class AIMError(Exception):
|
||||||
def __init__(self, value):
|
def __init__(self, value):
|
||||||
self.parameter = value
|
self.parameter = value
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return str(self.parameter)
|
return str(self.parameter)
|
||||||
|
|
||||||
def __init__(self, login, transkey, testmode=False):
|
def __init__(self, login, transkey, testmode=False):
|
||||||
if str(login).strip() == '' or login == None:
|
if str(login).strip() == '' or login is None:
|
||||||
raise AIM.AIMError('No login name provided')
|
raise AIM.AIMError('No login name provided')
|
||||||
if str(transkey).strip() == '' or transkey == None:
|
if str(transkey).strip() == '' or transkey is None:
|
||||||
raise AIM.AIMError('No transaction key provided')
|
raise AIM.AIMError('No transaction key provided')
|
||||||
if testmode != True and testmode != False:
|
if testmode != True and testmode != False:
|
||||||
raise AIM.AIMError('Invalid value for testmode. Must be True or False. "{0}" given.'.format(testmode))
|
raise AIM.AIMError('Invalid value for testmode. Must be True or False. "{0}" given.'.format(testmode))
|
||||||
|
|
||||||
self.testmode = testmode
|
self.testmode = testmode
|
||||||
self.proxy = None;
|
self.proxy = None
|
||||||
self.delimiter = '|'
|
self.delimiter = '|'
|
||||||
self.results = []
|
self.results = []
|
||||||
self.error = True
|
self.error = True
|
||||||
@@ -117,8 +121,9 @@ class AIM:
|
|||||||
else:
|
else:
|
||||||
url = 'https://secure.authorize.net/gateway/transact.dll'
|
url = 'https://secure.authorize.net/gateway/transact.dll'
|
||||||
|
|
||||||
if self.proxy == None:
|
if self.proxy is None:
|
||||||
self.results += str(urllib.urlopen(url, encoded_args).read()).split(self.delimiter)
|
self.results += str(urllib.urlopen(
|
||||||
|
url, encoded_args).read()).split(self.delimiter)
|
||||||
else:
|
else:
|
||||||
opener = urllib.FancyURLopener(self.proxy)
|
opener = urllib.FancyURLopener(self.proxy)
|
||||||
opened = opener.open(url, encoded_args)
|
opened = opener.open(url, encoded_args)
|
||||||
@@ -147,36 +152,37 @@ class AIM:
|
|||||||
raise AIM.AIMError(self.response.ResponseText)
|
raise AIM.AIMError(self.response.ResponseText)
|
||||||
|
|
||||||
def setTransaction(self, creditcard, expiration, total, cvv=None, tax=None, invoice=None):
|
def setTransaction(self, creditcard, expiration, total, cvv=None, tax=None, invoice=None):
|
||||||
if str(creditcard).strip() == '' or creditcard == None:
|
if str(creditcard).strip() == '' or creditcard is None:
|
||||||
raise AIM.AIMError('No credit card number passed to setTransaction(): {0}'.format(creditcard))
|
raise AIM.AIMError('No credit card number passed to setTransaction(): {0}'.format(creditcard))
|
||||||
if str(expiration).strip() == '' or expiration == None:
|
if str(expiration).strip() == '' or expiration is None:
|
||||||
raise AIM.AIMError('No expiration number to setTransaction(): {0}'.format(expiration))
|
raise AIM.AIMError('No expiration number to setTransaction(): {0}'.format(expiration))
|
||||||
if str(total).strip() == '' or total == None:
|
if str(total).strip() == '' or total is None:
|
||||||
raise AIM.AIMError('No total amount passed to setTransaction(): {0}'.format(total))
|
raise AIM.AIMError('No total amount passed to setTransaction(): {0}'.format(total))
|
||||||
|
|
||||||
self.setParameter('x_card_num', creditcard)
|
self.setParameter('x_card_num', creditcard)
|
||||||
self.setParameter('x_exp_date', expiration)
|
self.setParameter('x_exp_date', expiration)
|
||||||
self.setParameter('x_amount', total)
|
self.setParameter('x_amount', total)
|
||||||
if cvv != None:
|
if cvv is not None:
|
||||||
self.setParameter('x_card_code', cvv)
|
self.setParameter('x_card_code', cvv)
|
||||||
if tax != None:
|
if tax is not None:
|
||||||
self.setParameter('x_tax', tax)
|
self.setParameter('x_tax', tax)
|
||||||
if invoice != None:
|
if invoice is not None:
|
||||||
self.setParameter('x_invoice_num', invoice)
|
self.setParameter('x_invoice_num', invoice)
|
||||||
|
|
||||||
def setTransactionType(self, transtype=None):
|
def setTransactionType(self, transtype=None):
|
||||||
types = ['AUTH_CAPTURE', 'AUTH_ONLY', 'PRIOR_AUTH_CAPTURE', 'CREDIT', 'CAPTURE_ONLY', 'VOID']
|
types = ['AUTH_CAPTURE', 'AUTH_ONLY', 'PRIOR_AUTH_CAPTURE',
|
||||||
|
'CREDIT', 'CAPTURE_ONLY', 'VOID']
|
||||||
if transtype.upper() not in types:
|
if transtype.upper() not in types:
|
||||||
raise AIM.AIMError('Incorrect Transaction Type passed to setTransactionType(): {0}'.format(transtype))
|
raise AIM.AIMError('Incorrect Transaction Type passed to setTransactionType(): {0}'.format(transtype))
|
||||||
self.setParameter('x_type', transtype.upper())
|
self.setParameter('x_type', transtype.upper())
|
||||||
|
|
||||||
def setProxy(self, proxy=None):
|
def setProxy(self, proxy=None):
|
||||||
if str(proxy).strip() == '' or proxy == None:
|
if str(proxy).strip() == '' or proxy is None:
|
||||||
raise AIM.AIMError('No proxy passed to setProxy()')
|
raise AIM.AIMError('No proxy passed to setProxy()')
|
||||||
self.proxy = {'http': str(proxy).strip()}
|
self.proxy = {'http': str(proxy).strip()}
|
||||||
|
|
||||||
def setParameter(self, key=None, value=None):
|
def setParameter(self, key=None, value=None):
|
||||||
if key != None and value != None and str(key).strip() != '' and str(value).strip() != '':
|
if key is not None and value is not None and str(key).strip() != '' and str(value).strip() != '':
|
||||||
self.parameters[key] = str(value).strip()
|
self.parameters[key] = str(value).strip()
|
||||||
else:
|
else:
|
||||||
raise AIM.AIMError('Incorrect parameters passed to setParameter(): {0}:{1}'.format(key, value))
|
raise AIM.AIMError('Incorrect parameters passed to setParameter(): {0}:{1}'.format(key, value))
|
||||||
@@ -194,6 +200,7 @@ class AIM:
|
|||||||
responses = ['', 'Approved', 'Declined', 'Error']
|
responses = ['', 'Approved', 'Declined', 'Error']
|
||||||
return responses[int(self.results[0])]
|
return responses[int(self.results[0])]
|
||||||
|
|
||||||
|
|
||||||
def process(creditcard, expiration, total, cvv=None, tax=None, invoice=None,
|
def process(creditcard, expiration, total, cvv=None, tax=None, invoice=None,
|
||||||
login='cnpdev4289', transkey='SR2P8g4jdEn7vFLQ', testmode=True):
|
login='cnpdev4289', transkey='SR2P8g4jdEn7vFLQ', testmode=True):
|
||||||
payment = AIM(login, transkey, testmode)
|
payment = AIM(login, transkey, testmode)
|
||||||
@@ -205,6 +212,7 @@ def process(creditcard,expiration,total,cvv=None,tax=None,invoice=None,
|
|||||||
except AIM.AIMError:
|
except AIM.AIMError:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def test():
|
def test():
|
||||||
import socket
|
import socket
|
||||||
import sys
|
import sys
|
||||||
@@ -219,8 +227,10 @@ def test():
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
payment = AIM('cnpdev4289', 'SR2P8g4jdEn7vFLQ', True)
|
payment = AIM('cnpdev4289', 'SR2P8g4jdEn7vFLQ', True)
|
||||||
payment.setTransaction(creditcard, expiration, total, cvv, tax, invoice)
|
payment.setTransaction(
|
||||||
payment.setParameter('x_duplicate_window', 180) # three minutes duplicate windows
|
creditcard, expiration, total, cvv, tax, invoice)
|
||||||
|
payment.setParameter(
|
||||||
|
'x_duplicate_window', 180) # three minutes duplicate windows
|
||||||
payment.setParameter('x_cust_id', '1324') # customer ID
|
payment.setParameter('x_cust_id', '1324') # customer ID
|
||||||
payment.setParameter('x_first_name', 'John')
|
payment.setParameter('x_first_name', 'John')
|
||||||
payment.setParameter('x_last_name', 'Conde')
|
payment.setParameter('x_last_name', 'Conde')
|
||||||
@@ -232,7 +242,8 @@ def test():
|
|||||||
payment.setParameter('x_country', 'US')
|
payment.setParameter('x_country', 'US')
|
||||||
payment.setParameter('x_phone', '800-555-1234')
|
payment.setParameter('x_phone', '800-555-1234')
|
||||||
payment.setParameter('x_description', 'Test Transaction')
|
payment.setParameter('x_description', 'Test Transaction')
|
||||||
payment.setParameter('x_customer_ip', socket.gethostbyname(socket.gethostname()))
|
payment.setParameter(
|
||||||
|
'x_customer_ip', socket.gethostbyname(socket.gethostname()))
|
||||||
payment.setParameter('x_email', 'john@example.com')
|
payment.setParameter('x_email', 'john@example.com')
|
||||||
payment.setParameter('x_email_customer', False)
|
payment.setParameter('x_email_customer', False)
|
||||||
payment.process()
|
payment.process()
|
||||||
@@ -257,10 +268,3 @@ def test():
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
test()
|
test()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -15,25 +15,27 @@ __all__ = ['DowCommerce']
|
|||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
import urllib
|
import urllib
|
||||||
|
|
||||||
|
|
||||||
class DowCommerce:
|
class DowCommerce:
|
||||||
|
|
||||||
class DowCommerceError(Exception):
|
class DowCommerceError(Exception):
|
||||||
def __init__(self, value):
|
def __init__(self, value):
|
||||||
self.parameter = value
|
self.parameter = value
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return str(self.parameter)
|
return str(self.parameter)
|
||||||
|
|
||||||
def __init__(self, username=None, password=None, demomode=False):
|
def __init__(self, username=None, password=None, demomode=False):
|
||||||
if not demomode:
|
if not demomode:
|
||||||
if str(username).strip() == '' or username == None:
|
if str(username).strip() == '' or username is None:
|
||||||
raise DowCommerce.DowCommerceError('No username provided')
|
raise DowCommerce.DowCommerceError('No username provided')
|
||||||
if str(password).strip() == '' or password == None:
|
if str(password).strip() == '' or password is None:
|
||||||
raise DowCommerce.DowCommerceError('No password provided')
|
raise DowCommerce.DowCommerceError('No password provided')
|
||||||
else:
|
else:
|
||||||
username = 'demo'
|
username = 'demo'
|
||||||
password = 'password'
|
password = 'password'
|
||||||
|
|
||||||
self.proxy = None;
|
self.proxy = None
|
||||||
self.delimiter = '&'
|
self.delimiter = '&'
|
||||||
self.results = {}
|
self.results = {}
|
||||||
self.error = True
|
self.error = True
|
||||||
@@ -45,11 +47,11 @@ class DowCommerce:
|
|||||||
self.setParameter('username', username)
|
self.setParameter('username', username)
|
||||||
self.setParameter('password', password)
|
self.setParameter('password', password)
|
||||||
|
|
||||||
|
|
||||||
def process(self):
|
def process(self):
|
||||||
encoded_args = urllib.urlencode(self.parameters)
|
encoded_args = urllib.urlencode(self.parameters)
|
||||||
if self.proxy == None:
|
if self.proxy is None:
|
||||||
results = str(urllib.urlopen(self.url, encoded_args).read()).split(self.delimiter)
|
results = str(urllib.urlopen(
|
||||||
|
self.url, encoded_args).read()).split(self.delimiter)
|
||||||
else:
|
else:
|
||||||
opener = urllib.FancyURLopener(self.proxy)
|
opener = urllib.FancyURLopener(self.proxy)
|
||||||
opened = opener.open(self.url, encoded_args)
|
opened = opener.open(self.url, encoded_args)
|
||||||
@@ -80,17 +82,18 @@ class DowCommerce:
|
|||||||
self.declined = False
|
self.declined = False
|
||||||
raise DowCommerce.DowCommerceError(self.results)
|
raise DowCommerce.DowCommerceError(self.results)
|
||||||
|
|
||||||
def setTransaction(self, creditcard, expiration, total, cvv=None, orderid=None, orderdescription=None,
|
def setTransaction(
|
||||||
|
self, creditcard, expiration, total, cvv=None, orderid=None, orderdescription=None,
|
||||||
ipaddress=None, tax=None, shipping=None,
|
ipaddress=None, tax=None, shipping=None,
|
||||||
firstname=None, lastname=None, company=None, address1=None, address2=None, city=None, state=None, zipcode=None,
|
firstname=None, lastname=None, company=None, address1=None, address2=None, city=None, state=None, zipcode=None,
|
||||||
country=None, phone=None, fax=None, emailaddress=None, website=None,
|
country=None, phone=None, fax=None, emailaddress=None, website=None,
|
||||||
shipping_firstname=None, shipping_lastname=None, shipping_company=None, shipping_address1=None, shipping_address2=None,
|
shipping_firstname=None, shipping_lastname=None, shipping_company=None, shipping_address1=None, shipping_address2=None,
|
||||||
shipping_city=None, shipping_state=None, shipping_zipcode=None, shipping_country=None, shipping_emailaddress=None):
|
shipping_city=None, shipping_state=None, shipping_zipcode=None, shipping_country=None, shipping_emailaddress=None):
|
||||||
if str(creditcard).strip() == '' or creditcard == None:
|
if str(creditcard).strip() == '' or creditcard is None:
|
||||||
raise DowCommerce.DowCommerceError('No credit card number passed to setTransaction(): {0}'.format(creditcard))
|
raise DowCommerce.DowCommerceError('No credit card number passed to setTransaction(): {0}'.format(creditcard))
|
||||||
if str(expiration).strip() == '' or expiration == None:
|
if str(expiration).strip() == '' or expiration is None:
|
||||||
raise DowCommerce.DowCommerceError('No expiration number passed to setTransaction(): {0}'.format(expiration))
|
raise DowCommerce.DowCommerceError('No expiration number passed to setTransaction(): {0}'.format(expiration))
|
||||||
if str(total).strip() == '' or total == None:
|
if str(total).strip() == '' or total is None:
|
||||||
raise DowCommerce.DowCommerceError('No total amount passed to setTransaction(): {0}'.format(total))
|
raise DowCommerce.DowCommerceError('No total amount passed to setTransaction(): {0}'.format(total))
|
||||||
|
|
||||||
self.setParameter('ccnumber', creditcard)
|
self.setParameter('ccnumber', creditcard)
|
||||||
@@ -165,12 +168,12 @@ class DowCommerce:
|
|||||||
self.setParameter('type', transtype.lower())
|
self.setParameter('type', transtype.lower())
|
||||||
|
|
||||||
def setProxy(self, proxy=None):
|
def setProxy(self, proxy=None):
|
||||||
if str(proxy).strip() == '' or proxy == None:
|
if str(proxy).strip() == '' or proxy is None:
|
||||||
raise DowCommerce.DowCommerceError('No proxy passed to setProxy()')
|
raise DowCommerce.DowCommerceError('No proxy passed to setProxy()')
|
||||||
self.proxy = {'http': str(proxy).strip()}
|
self.proxy = {'http': str(proxy).strip()}
|
||||||
|
|
||||||
def setParameter(self, key=None, value=None):
|
def setParameter(self, key=None, value=None):
|
||||||
if key != None and value != None and str(key).strip() != '' and str(value).strip() != '':
|
if key is not None and value is not None and str(key).strip() != '' and str(value).strip() != '':
|
||||||
self.parameters[key] = str(value).strip()
|
self.parameters[key] = str(value).strip()
|
||||||
else:
|
else:
|
||||||
raise DowCommerce.DowCommerceError('Incorrect parameters passed to setParameter(): {0}:{1}'.format(key, value))
|
raise DowCommerce.DowCommerceError('Incorrect parameters passed to setParameter(): {0}:{1}'.format(key, value))
|
||||||
@@ -194,6 +197,7 @@ class DowCommerce:
|
|||||||
def getResponseText(self):
|
def getResponseText(self):
|
||||||
return self.results['responsetext']
|
return self.results['responsetext']
|
||||||
|
|
||||||
|
|
||||||
def test():
|
def test():
|
||||||
import socket
|
import socket
|
||||||
import sys
|
import sys
|
||||||
@@ -216,7 +220,8 @@ def test():
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
payment = DowCommerce(demomode=True)
|
payment = DowCommerce(demomode=True)
|
||||||
payment.setTransaction(creditcard, expiration, total, cvv=cvv, tax=tax, orderid=orderid, orderdescription='Test Transaction',
|
payment.setTransaction(
|
||||||
|
creditcard, expiration, total, cvv=cvv, tax=tax, orderid=orderid, orderdescription='Test Transaction',
|
||||||
firstname='John', lastname='Doe', company='Acme', address1='123 Min Street', city='Hometown', state='VA',
|
firstname='John', lastname='Doe', company='Acme', address1='123 Min Street', city='Hometown', state='VA',
|
||||||
zipcode='12345', country='US', phone='888-555-1212', emailaddress='john@noemail.local', ipaddress='192.168.1.1')
|
zipcode='12345', country='US', phone='888-555-1212', emailaddress='john@noemail.local', ipaddress='192.168.1.1')
|
||||||
|
|
||||||
@@ -237,10 +242,3 @@ def test():
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
test()
|
test()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ def new(key, mode=MODE_CBC, IV=None):
|
|||||||
return ECBMode(AES(key))
|
return ECBMode(AES(key))
|
||||||
elif mode == MODE_CBC:
|
elif mode == MODE_CBC:
|
||||||
if IV is None:
|
if IV is None:
|
||||||
raise ValueError, "CBC mode needs an IV value!"
|
raise ValueError("CBC mode needs an IV value!")
|
||||||
|
|
||||||
return CBCMode(AES(key), IV)
|
return CBCMode(AES(key), IV)
|
||||||
else:
|
else:
|
||||||
@@ -91,7 +91,7 @@ class AES(object):
|
|||||||
elif self.key_size == 32:
|
elif self.key_size == 32:
|
||||||
self.rounds = 14
|
self.rounds = 14
|
||||||
else:
|
else:
|
||||||
raise ValueError, "Key length must be 16, 24 or 32 bytes"
|
raise ValueError("Key length must be 16, 24 or 32 bytes")
|
||||||
|
|
||||||
self.expand_key()
|
self.expand_key()
|
||||||
|
|
||||||
@@ -313,7 +313,7 @@ class ECBMode(object):
|
|||||||
"""Perform ECB mode with the given function"""
|
"""Perform ECB mode with the given function"""
|
||||||
|
|
||||||
if len(data) % self.block_size != 0:
|
if len(data) % self.block_size != 0:
|
||||||
raise ValueError, "Plaintext length must be multiple of 16"
|
raise ValueError("Plaintext length must be multiple of 16")
|
||||||
|
|
||||||
block_size = self.block_size
|
block_size = self.block_size
|
||||||
data = array('B', data)
|
data = array('B', data)
|
||||||
@@ -357,7 +357,7 @@ class CBCMode(object):
|
|||||||
|
|
||||||
block_size = self.block_size
|
block_size = self.block_size
|
||||||
if len(data) % block_size != 0:
|
if len(data) % block_size != 0:
|
||||||
raise ValueError, "Plaintext length must be multiple of 16"
|
raise ValueError("Plaintext length must be multiple of 16")
|
||||||
|
|
||||||
data = array('B', data)
|
data = array('B', data)
|
||||||
IV = self.IV
|
IV = self.IV
|
||||||
@@ -381,7 +381,7 @@ class CBCMode(object):
|
|||||||
|
|
||||||
block_size = self.block_size
|
block_size = self.block_size
|
||||||
if len(data) % block_size != 0:
|
if len(data) % block_size != 0:
|
||||||
raise ValueError, "Ciphertext length must be multiple of 16"
|
raise ValueError("Ciphertext length must be multiple of 16")
|
||||||
|
|
||||||
data = array('B', data)
|
data = array('B', data)
|
||||||
IV = self.IV
|
IV = self.IV
|
||||||
@@ -500,5 +500,3 @@ aes_Rcon = array('B',
|
|||||||
'c697356ad4b37dfaefc5913972e4d3bd'
|
'c697356ad4b37dfaefc5913972e4d3bd'
|
||||||
'61c29f254a943366cc831d3a74e8cb'.decode('hex')
|
'61c29f254a943366cc831d3a74e8cb'.decode('hex')
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,9 @@ revision3.com
|
|||||||
viddler.com
|
viddler.com
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import re, cgi, sys
|
import re
|
||||||
|
import cgi
|
||||||
|
import sys
|
||||||
from simplejson import loads
|
from simplejson import loads
|
||||||
import urllib
|
import urllib
|
||||||
import uuid
|
import uuid
|
||||||
@@ -77,18 +79,23 @@ EMBED_MAPS = [
|
|||||||
'http://lab.viddler.com/services/oembed/'),
|
'http://lab.viddler.com/services/oembed/'),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def image(url):
|
def image(url):
|
||||||
return '<img src="%s" style="max-width:100%%"/>' % url
|
return '<img src="%s" style="max-width:100%%"/>' % url
|
||||||
|
|
||||||
|
|
||||||
def audio(url):
|
def audio(url):
|
||||||
return '<audio controls="controls" style="max-width:100%%"><source src="%s" /></audio>' % url
|
return '<audio controls="controls" style="max-width:100%%"><source src="%s" /></audio>' % url
|
||||||
|
|
||||||
|
|
||||||
def video(url):
|
def video(url):
|
||||||
return '<video controls="controls" style="max-width:100%%"><source src="%s" /></video>' % url
|
return '<video controls="controls" style="max-width:100%%"><source src="%s" /></video>' % url
|
||||||
|
|
||||||
|
|
||||||
def googledoc_viewer(url):
|
def googledoc_viewer(url):
|
||||||
return '<iframe src="http://docs.google.com/viewer?url=%s&embedded=true" style="max-width:100%%"></iframe>' % urllib.quote(url)
|
return '<iframe src="http://docs.google.com/viewer?url=%s&embedded=true" style="max-width:100%%"></iframe>' % urllib.quote(url)
|
||||||
|
|
||||||
|
|
||||||
def web2py_component(url):
|
def web2py_component(url):
|
||||||
code = str(uuid.uuid4())
|
code = str(uuid.uuid4())
|
||||||
return '<div id="%s"></div><script>\nweb2py_component("%s","%s");\n</script>' % (code, url, code)
|
return '<div id="%s"></div><script>\nweb2py_component("%s","%s");\n</script>' % (code, url, code)
|
||||||
@@ -126,26 +133,29 @@ EXTENSION_MAPS = {
|
|||||||
'xps': googledoc_viewer,
|
'xps': googledoc_viewer,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class VimeoURLOpener(urllib.FancyURLopener):
|
class VimeoURLOpener(urllib.FancyURLopener):
|
||||||
"Vimeo blocks the urllib user agent for some reason"
|
"Vimeo blocks the urllib user agent for some reason"
|
||||||
version = "Mozilla/4.0"
|
version = "Mozilla/4.0"
|
||||||
urllib._urlopener = VimeoURLOpener()
|
urllib._urlopener = VimeoURLOpener()
|
||||||
|
|
||||||
|
|
||||||
def oembed(url):
|
def oembed(url):
|
||||||
for k, v in EMBED_MAPS:
|
for k, v in EMBED_MAPS:
|
||||||
if k.match(url):
|
if k.match(url):
|
||||||
oembed = v + '?format=json&url=' + cgi.escape(url)
|
oembed = v + '?format=json&url=' + cgi.escape(url)
|
||||||
try:
|
try:
|
||||||
data = urllib.urlopen(oembed).read()
|
data = urllib.urlopen(oembed).read()
|
||||||
print data
|
|
||||||
return loads(data) # json!
|
return loads(data) # json!
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def extension(url):
|
def extension(url):
|
||||||
return url.split('?')[0].split('.')[-1].lower()
|
return url.split('?')[0].split('.')[-1].lower()
|
||||||
|
|
||||||
|
|
||||||
def expand_one(url, cdict):
|
def expand_one(url, cdict):
|
||||||
# try ombed but first check in cache
|
# try ombed but first check in cache
|
||||||
if cdict and url in cdict:
|
if cdict and url in cdict:
|
||||||
@@ -170,9 +180,10 @@ def expand_one(url,cdict):
|
|||||||
# else regular link
|
# else regular link
|
||||||
return '<a href="%(u)s">%(u)s</a>' % dict(u=url)
|
return '<a href="%(u)s">%(u)s</a>' % dict(u=url)
|
||||||
|
|
||||||
|
|
||||||
def expand_html(html, cdict=None):
|
def expand_html(html, cdict=None):
|
||||||
if not have_soup:
|
if not have_soup:
|
||||||
raise RuntimeError, "Missing BeautifulSoup"
|
raise RuntimeError("Missing BeautifulSoup")
|
||||||
soup = BeautifulSoup(html)
|
soup = BeautifulSoup(html)
|
||||||
comments = soup.findAll(text=lambda text: isinstance(text, Comment))
|
comments = soup.findAll(text=lambda text: isinstance(text, Comment))
|
||||||
[comment.extract() for comment in comments]
|
[comment.extract() for comment in comments]
|
||||||
@@ -183,6 +194,7 @@ def expand_html(html,cdict=None):
|
|||||||
txt.replaceWith(BeautifulSoup(ntxt))
|
txt.replaceWith(BeautifulSoup(ntxt))
|
||||||
return str(soup)
|
return str(soup)
|
||||||
|
|
||||||
|
|
||||||
def test():
|
def test():
|
||||||
example = """
|
example = """
|
||||||
<h3>Fringilla nisi parturient nullam</h3>
|
<h3>Fringilla nisi parturient nullam</h3>
|
||||||
@@ -203,5 +215,3 @@ if __name__=="__main__":
|
|||||||
print expand_html(open(sys.argv[1]).read())
|
print expand_html(open(sys.argv[1]).read())
|
||||||
else:
|
else:
|
||||||
print test()
|
print test()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+611
-537
File diff suppressed because it is too large
Load Diff
@@ -26,8 +26,9 @@ def hex2dec(color = "#000000"):
|
|||||||
class HTML2FPDF(HTMLParser):
|
class HTML2FPDF(HTMLParser):
|
||||||
"Render basic HTML to FPDF"
|
"Render basic HTML to FPDF"
|
||||||
|
|
||||||
def __init__(self, pdf):
|
def __init__(self, pdf, image_map = None):
|
||||||
HTMLParser.__init__(self)
|
HTMLParser.__init__(self)
|
||||||
|
self.image_map = image_map or (lambda src: src)
|
||||||
self.style = {}
|
self.style = {}
|
||||||
self.pre = False
|
self.pre = False
|
||||||
self.href = ''
|
self.href = ''
|
||||||
@@ -265,7 +266,8 @@ class HTML2FPDF(HTMLParser):
|
|||||||
h = px2mm(attrs.get('height',0))
|
h = px2mm(attrs.get('height',0))
|
||||||
if self.align and self.align[0].upper() == 'C':
|
if self.align and self.align[0].upper() == 'C':
|
||||||
x = (self.pdf.w-x)/2.0 - w/2.0
|
x = (self.pdf.w-x)/2.0 - w/2.0
|
||||||
self.pdf.image(attrs['src'], x, y, w, h, link=self.href)
|
self.pdf.image(self.image_map(attrs['src']),
|
||||||
|
x, y, w, h, link=self.href)
|
||||||
self.pdf.set_x(x+w)
|
self.pdf.set_x(x+w)
|
||||||
self.pdf.set_y(y+h)
|
self.pdf.set_y(y+h)
|
||||||
if tag=='b' or tag=='i' or tag=='u':
|
if tag=='b' or tag=='i' or tag=='u':
|
||||||
@@ -389,9 +391,9 @@ class HTML2FPDF(HTMLParser):
|
|||||||
self.pdf.ln(3)
|
self.pdf.ln(3)
|
||||||
|
|
||||||
class HTMLMixin(object):
|
class HTMLMixin(object):
|
||||||
def write_html(self, text):
|
def write_html(self, text, image_map=None):
|
||||||
"Parse HTML and convert it to PDF"
|
"Parse HTML and convert it to PDF"
|
||||||
h2p = HTML2FPDF(self)
|
h2p = HTML2FPDF(self, image_map)
|
||||||
h2p.feed(text)
|
h2p.feed(text)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ cache.ram=cache.disk=MemcacheClient(request)
|
|||||||
import time
|
import time
|
||||||
from google.appengine.api.memcache import Client
|
from google.appengine.api.memcache import Client
|
||||||
|
|
||||||
|
|
||||||
class MemcacheClient(object):
|
class MemcacheClient(object):
|
||||||
|
|
||||||
client = Client()
|
client = Client()
|
||||||
@@ -29,7 +30,7 @@ class MemcacheClient(object):
|
|||||||
dt = time_expire
|
dt = time_expire
|
||||||
value = None
|
value = None
|
||||||
obj = self.client.get(key)
|
obj = self.client.get(key)
|
||||||
if obj and (dt == None or obj[0] > time.time() - dt):
|
if obj and (dt is None or obj[0] > time.time() - dt):
|
||||||
value = obj[1]
|
value = obj[1]
|
||||||
elif f is None:
|
elif f is None:
|
||||||
if obj:
|
if obj:
|
||||||
|
|||||||
@@ -51,7 +51,8 @@ def autoretry_datastore_timeouts(attempts=5.0, interval=0.1, exponent=2.0):
|
|||||||
:param exponent: rate of exponential back-off.
|
:param exponent: rate of exponential back-off.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import time, logging
|
import time
|
||||||
|
import logging
|
||||||
from google.appengine.api import apiproxy_stub_map
|
from google.appengine.api import apiproxy_stub_map
|
||||||
from google.appengine.runtime import apiproxy_errors
|
from google.appengine.runtime import apiproxy_errors
|
||||||
from google.appengine.datastore import datastore_pb
|
from google.appengine.datastore import datastore_pb
|
||||||
@@ -70,10 +71,12 @@ def autoretry_datastore_timeouts(attempts=5.0, interval=0.1, exponent=2.0):
|
|||||||
return wrapped(*args, **kwargs)
|
return wrapped(*args, **kwargs)
|
||||||
except apiproxy_errors.ApplicationError, err:
|
except apiproxy_errors.ApplicationError, err:
|
||||||
errno = err.application_error
|
errno = err.application_error
|
||||||
if errno not in errors: raise
|
if errno not in errors:
|
||||||
|
raise
|
||||||
sleep = (exponent ** count) * interval
|
sleep = (exponent ** count) * interval
|
||||||
count += 1.0
|
count += 1.0
|
||||||
if count > attempts: raise
|
if count > attempts:
|
||||||
|
raise
|
||||||
msg = "Datastore %s: retry #%d in %s seconds.\n%s"
|
msg = "Datastore %s: retry #%d in %s seconds.\n%s"
|
||||||
vals = ''
|
vals = ''
|
||||||
if count == 1.0:
|
if count == 1.0:
|
||||||
@@ -84,10 +87,3 @@ def autoretry_datastore_timeouts(attempts=5.0, interval=0.1, exponent=2.0):
|
|||||||
setattr(wrapper, '_autoretry_datastore_timeouts', False)
|
setattr(wrapper, '_autoretry_datastore_timeouts', False)
|
||||||
if getattr(wrapped, '_autoretry_datastore_timeouts', True):
|
if getattr(wrapped, '_autoretry_datastore_timeouts', True):
|
||||||
apiproxy_stub_map.MakeSyncCall = wrapper
|
apiproxy_stub_map.MakeSyncCall = wrapper
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from gluon.sanitizer import sanitize
|
|||||||
from gluon.contrib.markmin.markmin2latex import markmin2latex
|
from gluon.contrib.markmin.markmin2latex import markmin2latex
|
||||||
from gluon.contrib.markmin.markmin2pdf import markmin2pdf
|
from gluon.contrib.markmin.markmin2pdf import markmin2pdf
|
||||||
|
|
||||||
|
|
||||||
def wrapper(f):
|
def wrapper(f):
|
||||||
def g(data):
|
def g(data):
|
||||||
try:
|
try:
|
||||||
@@ -25,10 +26,12 @@ def wrapper(f):
|
|||||||
raise HTTP(405, '%s error' % e)
|
raise HTTP(405, '%s error' % e)
|
||||||
return g
|
return g
|
||||||
|
|
||||||
|
|
||||||
def latex_from_html(html):
|
def latex_from_html(html):
|
||||||
markmin = TAG(html).element('body').flatten(markmin_serializer)
|
markmin = TAG(html).element('body').flatten(markmin_serializer)
|
||||||
return XML(markmin2latex(markmin))
|
return XML(markmin2latex(markmin))
|
||||||
|
|
||||||
|
|
||||||
def pdflatex_from_html(html):
|
def pdflatex_from_html(html):
|
||||||
if os.system('which pdflatex > /dev/null') == 0:
|
if os.system('which pdflatex > /dev/null') == 0:
|
||||||
markmin = TAG(html).element('body').flatten(markmin_serializer)
|
markmin = TAG(html).element('body').flatten(markmin_serializer)
|
||||||
@@ -42,29 +45,28 @@ def pdflatex_from_html(html):
|
|||||||
else:
|
else:
|
||||||
return XML(out)
|
return XML(out)
|
||||||
|
|
||||||
|
|
||||||
def pyfpdf_from_html(html):
|
def pyfpdf_from_html(html):
|
||||||
request = current.request
|
request = current.request
|
||||||
|
|
||||||
def image_map(path):
|
def image_map(path):
|
||||||
if path.startswith('/%s/static/' % request.application):
|
if path.startswith('/%s/static/' % request.application):
|
||||||
return os.path.join(request.folder, path.split('/', 2)[2])
|
return os.path.join(request.folder, path.split('/', 2)[2])
|
||||||
return 'http%s://%s%s' % (request.is_https and 's' or '', request.env.http_host, path)
|
return 'http%s://%s%s' % (request.is_https and 's' or '', request.env.http_host, path)
|
||||||
class MyFPDF(FPDF, HTMLMixin): pass
|
|
||||||
|
class MyFPDF(FPDF, HTMLMixin):
|
||||||
|
pass
|
||||||
pdf = MyFPDF()
|
pdf = MyFPDF()
|
||||||
pdf.add_page()
|
pdf.add_page()
|
||||||
html = sanitize(html, escape=False) #### should have better list of allowed tags
|
html = sanitize(
|
||||||
|
html, escape=False) # should have better list of allowed tags
|
||||||
pdf.write_html(html, image_map=image_map)
|
pdf.write_html(html, image_map=image_map)
|
||||||
return XML(pdf.output(dest='S'))
|
return XML(pdf.output(dest='S'))
|
||||||
|
|
||||||
|
|
||||||
def pdf_from_html(html):
|
def pdf_from_html(html):
|
||||||
# try use latex and pdflatex
|
# try use latex and pdflatex
|
||||||
if os.system('which pdflatex > /dev/null') == 0:
|
if os.system('which pdflatex > /dev/null') == 0:
|
||||||
return pdflatex_from_html(html)
|
return pdflatex_from_html(html)
|
||||||
else:
|
else:
|
||||||
return pyfpdf_from_html(html)
|
return pyfpdf_from_html(html)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user