Skip to content
This repository has been archived by the owner on Jul 24, 2021. It is now read-only.

Commit

Permalink
Merge branch 'reboot'
Browse files Browse the repository at this point in the history
Conflicts:
	app.py
	config.py
	modules/bottle.py
	modules/pystache/template.py
	sitetools.py
	users.py
  • Loading branch information
bricef committed Apr 23, 2012
2 parents 3bcf567 + c186d88 commit e142509
Show file tree
Hide file tree
Showing 33 changed files with 17,407 additions and 71 deletions.
5 changes: 5 additions & 0 deletions README.md
@@ -0,0 +1,5 @@

SiteBase
========

Getting a dynamic website up in less than 20 minutes using bootstrap, pystache, mongodb and bottle.py
56 changes: 51 additions & 5 deletions app.py
@@ -1,11 +1,11 @@
#!/usr/bin/env python

import os
import sys
import os
mypath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0,mypath)
sys.path.insert(0,os.path.join(mypath, "modules"))
os.chdir(mypath)
os.chdir(mypath)import os

# Standard lib modules
import argparse
Expand All @@ -16,7 +16,8 @@

# My modules
from sitetools import *
from config import config
from config import config, SECRET
import users



Expand All @@ -35,9 +36,54 @@
###############################

@route("/")
@route("/home")
def home():
return renderfile("root", {})

return renderfile("home", {})

@app.route("/register")
@app.get("/register")
@app.post("/register")
def register():
username = request.forms.get("username")
password = request.forms.get("password")
password2 = request.forms.get("password2")
data = {"username":username,
"messages":[],
"warnings": []}

if password == password2 and username:
try:
users.add_user(username, password)
except UserNameExistsException as ex:
data["warnings"].append("This username is already taken")
return renderfile("register", data)
return login()
elif not username:
data["warnings"].append( "You can't have an empty name")
elif password != password2:
data["warnings"].append( "Your two passwords don't match")
return renderfile("register", data)

@route('/login')
@get('/login')
@post('/login')
def login():
username = request.get_cookie("account", secret=SECRET)
if not username:
username = request.forms.get('username')
password = request.forms.get('password')
if users.auth_ok(username, password):
response.set_cookie("account", username, secret=SECRET)
redirect("/home")
else:
return renderfile("login", {"warnings":[{"msg":"Wrong username or password."}]})
else:
redirect("/")

@route('/logout')
def logout():
response.delete_cookie("account")
redirect("/")

@route("/fail/<report>/<graph>")
def show_fragment(report, graph):
Expand Down
5 changes: 2 additions & 3 deletions config.py
Expand Up @@ -4,13 +4,12 @@

config = ConfigParser.SafeConfigParser({
"debug":"False",
"production":"True",
"templatepath":"./templates/",
"cache":"False"})

config.read("config.ini")

DEBUG = config.getboolean("app", "debug")
PRODUCTION = config.getboolean("app", "production")
CACHE = config.getboolean("app", "cache")
TEMPLATEPATH = config.get("app", "templatepath")

SECRET = config.get("app", "secret")
100 changes: 45 additions & 55 deletions modules/bottle.py
Expand Up @@ -534,7 +534,7 @@ class Bottle(object):
"""

def __init__(self, catchall=True, autojson=True):
#: If true, most exceptions are catched and returned as :exc:`HTTPError`
#: If true, most exceptions are caught and returned as :exc:`HTTPError`
self.catchall = catchall

#: A :cls:`ResourceManager` for application files
Expand Down Expand Up @@ -597,7 +597,7 @@ def start_response(status, header):
self.route('/' + '/'.join(parts), callback=mountpoint, **options)

def merge(self, routes):
''' Merge the routes of another :cls:`Bottle` application or a list of
''' Merge the routes of another :class:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
Expand Down Expand Up @@ -754,8 +754,8 @@ def wrapper(func):

def handle(self, path, method='GET'):
""" (deprecated) Execute the first matching route callback and return
the result. :exc:`HTTPResponse` exceptions are catched and returned.
If :attr:`Bottle.catchall` is true, other exceptions are catched as
the result. :exc:`HTTPResponse` exceptions are caught and returned.
If :attr:`Bottle.catchall` is true, other exceptions are caught as
well and returned as :exc:`HTTPError` instances (500).
"""
depr("This method will change semantics in 0.10. Try to avoid it.")
Expand Down Expand Up @@ -1908,96 +1908,86 @@ class ResourceManager(object):
''' This class manages a list of search paths and helps to find and open
aplication-bound resources (files).
:param base: path used to resolve relative search paths. It works as a
default for :meth:`add_path`.
:param base: default value for same-named :meth:`add_path` parameter.
:param opener: callable used to open resources.
:param cachemode: controls which lookups are cached. One of 'all',
'found' or 'none'.
'''

def __init__(self, base='./', opener=open, cachemode='all'):

self.opener = open
self.base = './'
self.base = base
self.cachemode = cachemode

#: A list of search paths. See :meth:`add_path` for details.
self.path = []
#: A list of file masks. See :meth:`add_mask` for details.
self.mask = ['%s']
#: A cache for resolved paths. `res.cache.clear()`` clears the cache.
self.cache = {}

def add_path(self, path, base=None, index=None):
''' Add a path to the :attr:`path` list.
The path is turned into an absolute and normalized form. If it
looks like a file (not ending in `/`), the filename is stripped
off. The path is not required to exist.
Relative paths are joined with `base` or :attr:`self.base`, which
defaults to the current working directory. This comes in handy if
you resources live in a sub-folder of your module or package::
def add_path(self, path, base=None, index=None, create=False):
''' Add a new path to the list of search paths. Return False if it does
not exist.
:param path: The new search path. Relative paths are turned into an
absolute and normalized form. If the path looks like a file (not
ending in `/`), the filename is stripped off.
:param base: Path used to absolutize relative search paths.
Defaults to `:attr:base` which defaults to ``./``.
:param index: Position within the list of search paths. Defaults to
last index (appends to the list).
:param create: Create non-existent search paths. Off by default.
The `base` parameter makes it easy to reference files installed
along with a python module or package::
res.add_path('./resources/', __file__)
The :attr:`path` list is searched in order and new paths are
added to the end of the list. The *index* parameter can change
the position (e.g. ``0`` to prepend). Adding a path a second time
moves it to the new position.
'''
base = os.path.abspath(os.path.dirname(base or self.base))
path = os.path.abspath(os.path.join(base, os.path.dirname(path)))
path += os.sep
if path in self.path:
self.path.remove(path)
if create and not os.path.isdir(path):
os.mkdirs(path)
if index is None:
self.path.append(path)
else:
self.path.insert(index, path)
self.cache.clear()

def add_mask(self, mask, index=None):
''' Add a new format string to the :attr:`mask` list.
Masks are used to turn resource names into actual filenames. The
mask string must contain exactly one occurence of ``%s``, which
is replaced by the supplied resource name on lookup. This can be
used to auto-append file extentions (e.g. ``%s.ext``).
'''
if index is None:
self.masks.append(mask)
else:
self.masks.insert(index, mask)
self.cache.clear()
def __iter__(self):
''' Iterate over all existing files in all registered paths. '''
search = self.path[:]
while search:
path = search.pop()
if not os.path.isdir(path): continue
for name in os.listdir(path):
full = os.path.join(path, name)
if os.path.isdir(full): search.append(full)
else: yield full

def lookup(self, name):
''' Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. For each path, the
:attr:`mask` entries are tried in order. The first path that points
to an existing file is returned. Symlinks are followed. The result
is cached to speed up future lookups. '''
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. '''
if name not in self.cache or DEBUG:
for path in self.path:
for mask in self.mask:
fpath = os.path.join(path, mask%name)
if os.path.isfile(fpath):
if self.cachemode in ('all', 'found'):
self.cache[name] = fpath
return fpath
fpath = os.path.join(path, name)
if os.path.isfile(fpath):
if self.cachemode in ('all', 'found'):
self.cache[name] = fpath
return fpath
if self.cachemode == 'all':
self.cache[name] = None
return self.cache[name]

def open(self, name, *args, **kwargs):
''' Find a resource and return an opened file object, or raise IOError.
Additional parameters are passed to the ``open()`` built-in.
'''
def open(self, name, mode='r', *args, **kwargs):
''' Find a resource and return a file object, or raise IOError. '''
fname = self.lookup(name)
if not fname: raise IOError("Resource %r not found." % name)
return self.opener(name, *args, **kwargs)
return self.opener(name, mode=mode, *args, **kwargs)



Expand Down
4 changes: 4 additions & 0 deletions modules/pystache/template.py
Expand Up @@ -96,7 +96,11 @@ def _render_sections(self, template, view):
# Falsey and Negated or Truthy and Not Negated
elif (not it and section[2] == '^') or (it and section[2] != '^'):
replacer = self._render_dictionary(inner, it)
<<<<<<< HEAD

=======

>>>>>>> Initial commit of cleaned-up base site
template = literal(template.replace(section, replacer))

return template
Expand Down
13 changes: 5 additions & 8 deletions sitetools.py
Expand Up @@ -2,14 +2,11 @@
import os
import copy
import logging
from config import config
from config import CACHE, SECRET, TEMPLATEPATH
from functools import *
import pystache

CACHE = config.getboolean("app", "cache")
TEMPLATEPATH = config.get("app", "templatepath")
SECRET = config.get("app", "secret")

logger = logging.getLogger(__name__)

def renderfile(name, data={}):
fnames = filter(
Expand All @@ -19,7 +16,7 @@ def renderfile(name, data={}):
[
"%s.mustache"%name,
"%s.html"%name,
name,
str(name),
"default.mustache",
"default.html",
"default"
Expand All @@ -33,14 +30,14 @@ def timeMe(fun):
def timed(*args, **kwargs):
start = time.time()
spill = fun(*args, **kwargs)
note("%s() took %f seconds to execute"%(fun.__name__, time.time()-start))
logger.info("%s() took %f seconds to execute"%(fun.__name__, time.time()-start))
return spill
return timed

def showMe(fun):
def showed(*args, **kwargs):
spill = fun(*args, **kwargs)
note("%s() returned %s"%(fun.__name__, str(spill)))
logger.info("%s() returned %s"%(fun.__name__, str(spill)))
return spill
return showed

Expand Down

0 comments on commit e142509

Please sign in to comment.