General Utilities
rstrips(text, remove)- removes the string
removefrom the right oftext lstrips(text, remove)- removes the string
removefrom the left oftext strips(text, remove)- removes the string
removefrom the both sides oftext autoassign(self, locals)-
Automatically assigns local variables to
self. Generally used in__init__methods, as in:def __init__(self, foo, bar, baz=1): autoassign(self, locals()) class Storage(dict)- A Storage object is like a dictionary except
obj.foocan be used instead ofobj['foo']. Create one by doingstorage({'a':1}). storify(mapping, *requireds, **defaults)-
Creates a
storageobject from dictionarymapping, raisingKeyErrorif d doesn't have all of the keys inrequiredsand using the default values for keys found indefaults.For example,
storify({'a':1, 'c':3}, b=2, c=0)will return the equivalent ofstorage({'a':1, 'b':2, 'c':3}). class Memoize- 'Memoizes' a function, caching its return values for each input.
re_subm(pat, repl, string)- Like re.sub, but returns the replacement and the match object.
group(seq, size)-
Returns an iterator over a series of lists of length size from iterable.
For example,
list(group([1,2,3,4], 2))returns[[1,2],[3,4]]. class IterBetter- Returns an object that can be used as an iterator
but can also be used via getitem (although it
cannot go backwards -- that is, you cannot request
iterbetter[0]after requestingiterbetter[1]). dictreverse(mapping)- Takes a dictionary like
{1:2, 3:4}and returns{2:1, 4:3}. dictfind(dictionary, element)- Returns a key whose value in
dictionaryiselementor, if none exists, None. dictfindall(dictionary, element)- Returns the keys whose values in
dictionaryareelementor, if none exists, []. dictincr(dictionary, element)- Increments
elementindictionary, setting it to one if it doesn't exist. dictadd(dict_a, dict_b)- Returns a dictionary consisting of the keys in
aandb. If they share a key, the value from b is used. listget(lst, ind, default=None)- Returns
lst[ind]if it exists,defaultotherwise. intget(integer, default=None)- Returns
integeras an int ordefaultif it can't. upvars(level=2)- Guido van Rossum doesn't want you to use this function.
class CaptureStdout-
Captures everything func prints to stdout and returns it instead.
WARNING: Not threadsafe!
class Profile- Profiles
funcand returns a tuple containing its output and a string with human-readable profiling information. tryall(context, prefix=None)-
Tries a series of functions and prints their results.
contextis a dictionary mapping names to values; the value will only be tried if it's callable.For example, you might have a file
test/stuff.pywith a series of functions testing various things in it. At the bottom, have a line:if __name__ == "__main__": tryall(globals())Then you can run
python test/stuff.pyand get the results of all the tests. class ThreadedDict- Takes a dictionary that maps threads to objects. When a thread tries to get or set an attribute or item of the threadeddict, it passes it on to the object for that thread in dictionary.
IP Utilities
validipaddr(address)- returns True if
addressis a valid IPv4 address validipport(port)- returns True if
portis a valid IPv4 port validip(ip, defaultaddr="0.0.0.0", defaultport=8080)- returns
(ip_address, port)from stringip_addr_port
URL Utilities
prefixurl(base='')- Sorry, this function is really difficult to explain. Maybe some other time.
Formatting
safemarkdown(text)-
Converts text to HTML following the rules of Markdown, but blocking any outside HTML input, so that only the things supported by Markdown can be used. Also converts raw URLs to links.
(requires markdown.py)
Databases
sqlors(left, lst)-
left is a SQL clause liketablename.arg =andlst` is a list of values. Returns a reparam-style pair featuring the SQL that ORs together the clause for each item in the lst.For example:
web.sqlors('foo =', [1,2,3])would result in:
foo = 1 OR foo = 2 OR foo = 3 class UnknownParamstyle(Exception)- raised for unsupported db paramstyles
Currently supported: qmark,numeric, format, pyformat aparam()- Use in a SQL string to make a spot for a db value.
reparam(string_, dictionary)-
Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns a 2-tuple containing the a string with
aparam()s in it and a list of the matching values.You can pass this sort of thing as a clause in any db function. Otherwise, you can pass a dictionary to the keyword argument
varsand the function will call reparam for you. class UnknownDB(Exception)- raised for unsupported dbms
connect(dbn, **keywords)- Connects to the specified database. db currently must be "postgres" or "mysql". If DBUtils is installed, connection pooling will be used.
transact()- Start a transaction.
commit()- Commits a transaction.
rollback()- Rolls back a transaction.
query(sql_query, vars=None, processed=False)- Execute SQL query
sql_queryusing dictionaryvarsto interpolate it. Ifprocessed=True,varsis areparam-style list to use instead of interpolating. sqllist(lst)- If a list, converts it to a comma-separated string. Otherwise, returns the string.
sqlwhere(dictionary)- Converts a
dictionarylike {'cust_id': 2, 'order_id':3} to an SQL WHERE clause like "cust_id = 2 AND order_id = 3". @@untested select(tables, vars=None, what='*', where=None, order=None, group=None, limit=None, offset=None):- Selects
whatfromtableswith clauseswhere,order,group,limit, and `offset. Uses vars to interpolate. Otherwise, each clause can take a reparam-style list. insert(tablename, seqname=None, **values)- Inserts
valuesintotablename. Returns current sequence ID. Setseqnameto the ID if it's not the default, or toFalseif there isn't one. update(tables, where, vars=None, **values)- Update
tableswith clausewhere(interpolated usingvars) and settingvalues. delete(table, where, using=None, vars=None)- Deletes from
tablewith clauseswhereandusing.
Request Handlers
handle(mapping, fvars=None)-
Call the appropriate function based on the url to function mapping in
mapping. If no module for the function is specified, look up the function infvars. Iffvarsis empty, using the caller's context.mappingshould be a tuple of paired regular expressions with function name substitutions.handlewill import modules as necessary. autodelegate(prefix='')-
Returns a method that takes one argument and calls the method named prefix+arg, calling
notfound()if there isn't one. Example:urls = ('/prefs/(.*)', 'prefs') class prefs: GET = autodelegate('GET_') def GET_password(self): pass def GET_privacy(self): passGET_passwordwould get called for/prefs/passwordwhileGET_privacyforGET_privacygets called for/prefs/privacy.If a user visits
/prefs/password/changethenGET_password(self, '/change')is called.
HTTP Functions
httpdate(date_obj)- Formats a datetime object for use in HTTP headers.
parsehttpdate(string_)- Parses an HTTP date into a datetime object.
expires(delta)- Outputs an
Expiresheader fordeltafrom now.deltais atimedeltaobject or a number of seconds. lastmodified(date_obj)- Outputs a
Last-Modifiedheader fordatetime. modified(date=None, etag=None)redirect(url, status='301 Moved Permanently')- Returns a
statusredirect to the new URL.urlis joined with the base URL so that things like `redirect("about") will work properly. found(url)- A
302 Foundredirect. seeother(url)- A
303 See Otherredirect. tempredirect(url)- A
307 Temporary Redirectredirect. badrequest()- Return a
400 Bad Requesterror. notfound()- Returns a
404 Not Founderror. nomethod(cls)- Returns a
405 Method Not Allowederror forcls. gone()- Returns a
410 Goneerror. internalerror()- Returns a
500 Internal Servererror. djangoerror()debugerror()-
A replacement for
internalerrorthat presents a nice page with lots of debug information for the programmer.(Based on the beautiful 500 page from Django, designed by Wilson Miner.)
Requires Cheetah.
Rendering
htmlquote(text)- Encodes
textfor raw use in HTML. websafe(val)-
Converts
valso that it's safe for use in HTML.HTML metacharacters are encoded, None becomes the empty string, and unicode is converted to UTF-8.
render(template, terms=None, asTemplate=False, base=None, isString=False):-
Renders a template, caching where it can.
templateis the name of a file containing the a template in thetemplates/folder, unlessisString, in which case it's the template itself.termsis a dictionary used to fill the template. If it's None, then the caller's local variables are used instead, plus context, if it's not already set, is set tocontext.If asTemplate is False, it
outputs the template directly. Otherwise, it returns the template object.If the template is a potential base template (that is, something other templates) can extend, then base should be a string with the name of the template. The template will be cached and made available for future calls to
render.Requires Cheetah.
Input Forms
input(*requireds, **defaults)- Returns a
storageobject with the GET and POST arguments. Seestorifyfor howrequiredsanddefaultswork. data()- Returns the data sent with the request.
Cookies
setcookie(name, value, expires="", domain=None)- Sets a cookie.
cookies(*requireds, **defaults)- Returns a
storageobject with all the cookies in it. Seestorifyfor howrequiredsanddefaultswork.
WSGI Sugar
header(hdr, value)- Adds the header
hdr: valuewith the response. output(string_)- Appends
string_to the response. write(cgi_response)- Converts a standard CGI-style string response into
headerandoutputcalls. webpyfunc(inp, fvars=None, autoreload=False)- If
inpis a url mapping, returns a function that calls handle. wsgifunc(func, *middleware)- Returns a WSGI-compatible function from a webpy-function.
run(inp, *middleware)-
Starts handling requests. If called in a CGI or FastCGI context, it will follow that protocol. If called from the command line, it will start an HTTP server on the port named in the first command line argument, or, if there is no argument, on port 8080.
inputis a callable, then it's called with no arguments. Otherwise, it's amappingobject to be passed tohandle(...).Caveat: So that
reloaderwill work correctly, input has to be a variable, it can't be a tuple passed in directly.middlewareis a list of WSGI middleware which is applied to the resulting WSGI function. runwsgi(func)- Runs a WSGI-compatible function using FCGI, SCGI, or a simple web server, as appropriate.
runsimple(func, server_address=("0.0.0.0", 8080))-
Runs a simple HTTP server hosting WSGI app
func. The directorystatic/is hosted statically.Based on WsgiServer from Colin Stewart.
makeserver(wsgi_server)- Updates a flup-style WSGIServer with web.py-style error support.
runfcgi(func)- Runs a WSGI-function with a FastCGI server.
runscgi(func)- Runs a WSGI-function with an SCGI server.
Debugging
debug(*args)- Prints a prettyprinted version of
argsto stderr. debugwrite(x)- writes debug data to error stream
class Reloader- Before every request, checks to see if any loaded modules have changed on disk and, if so, reloads them.
profiler(app)- Outputs basic profiling information at the bottom of each response.
Context
load()-
Loads a new context for the thread.
You can ask for a function to be run at loadtime by adding it to the dictionary
loadhooks. unload()-
Unloads the context for the thread.
You can ask for a function to be run at loadtime by adding it ot the dictionary
unloadhooks. ctx-
A
storageobject containing various information about the request:environ(akaenv)- A dictionary containing the standard WSGI environment variables.
host- The domain (
Hostheader) requested by the user. home- The base path for the application.
ip- The IP address of the requester.
method- The HTTP method used.
path- The path request.
fullpath- The full path requested, including query arguments.
Response Data
status(default: "200 OK")- The status code to be used in the response.
headers- A list of 2-tuples to be used in the response.
output- A string to be used as the response.
Comments? Questions? Suggestions? Requests? Email webpy@aaronsw.com.