code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
import pygame
import copy
import itertools
from pygame.locals import *
from globals import *
from tile import Tile
from mysprite import MySprite
from snake import BasicSnake
# snake container
class SnakeContainer:
def __init__(self):
self.snakes = []
self.humans = []
self.bots = []
def getAliveSnakes(self):
return filter (lambda snake: snake.isAlive, self.snakes)
def getAliveBots(self):
return filter (lambda bot: bot.isAlive, self.bots)
def getAliveHumans(self):
return filter (lambda human: human.isAlive, self.humans)
def addSnake(self, snake):
self.snakes.append(snake)
if snake.isHuman:
self.humans.append(snake)
else:
self.bots.append(snake)
def removeSnake(self, snake):
self.snakes.remove(snake)
if snake.isHuman:
self.humans.remove(snake)
else:
self.bots.remove(snake)
def noneAlive(self):
return not self.getAliveSnakes()
# Snakes after crash are marked as not alive but not removed from
# snake lists nor grid tiles. Hence, if you iterate over snake list,
# you might want to check if snakes are alive before working with
# them. And if you check for collisions you need to discount segments
# of dead snakes that are on the tile. This holds for BasicGrid as
# well as for GameGrid.
# grid logic
class BasicGrid(SnakeContainer):
# Snakes can be basic or not but this class defines only the basic of them.
def __init__(self, size):
SnakeContainer.__init__(self)
self.gmap = [] # two dimensional array of tiles (lists)
for x in xrange(size[0]): # build default grid
if x == 0 or x == size[0] - 1:
self.gmap.append(
[Tile((x, y), True) for y in xrange(size[1])])
else:
self.gmap.append(
[Tile((x, 0), True)] +
[Tile((x, y)) for y in xrange(1,size[1] - 1)] +
[Tile((x, size[1] - 1), True)])
self.size = size
def dump(self):
for y in xrange(self.size[1]):
for x in xrange(self.size[0]):
print self.gmap[x][y].getSymbol(),
print ""
# check grid for collisions snake&wall or snake&snake&...
def getCrashedSnakes(self):
crashedSnakes = []
for snake in self.snakes:
if not snake.isAlive: continue
x, y = snake.segments[0]
tile = self.gmap[x][y]
# dead snakes might be present on the tile
# do not count them.
aliveSnakes = filter (lambda snake: snake.isAlive, tile.snakes)
if len(aliveSnakes) > 1 or tile.isWall:
crashedSnakes.append(snake)
return set(crashedSnakes) # snake might have hit its own tail
def update(self):
# update segments attribute of grid tiles
for snake in self.snakes:
if not snake.isAlive: continue
newHead, oldTail = BasicSnake.update(snake)
x, y = newHead
self.gmap[x][y].snakes.append(snake)
if oldTail == None:
continue # happens when snake is still growing
x, y = oldTail
self.gmap[x][y].snakes.remove(snake)
# crashed snakes are removed from grid and marked as dead
# BasicGrid keeps them in its snake lists though, which is
# important for its child AIGrid.
crashedSnakes = self.getCrashedSnakes()
for snake in crashedSnakes:
# snake.leaveGrid()
snake.isAlive = False
return crashedSnakes
# grid also handling sprites of its tiles and snakes
class GameGrid(BasicGrid):
def __init__(self, size):
BasicGrid.__init__(self, size)
self.wallSprites = []
for x in xrange(len(self.gmap)):
for y in xrange(len(self.gmap[x])):
if self.gmap[x][y].isWall:
self.wallSprites.append(MySprite(WALLCOLOR, (x, y)))
self.crashedSnakes = []
def isEmpty(self):
return self.noneAlive() and not self.crashedSnakes
def update(self, sprites):
# update snakes attribute of grid tiles
for snake in self.snakes:
if not snake.isAlive: continue
newHead, oldTail = snake.update(sprites)
x, y = newHead
self.gmap[x][y].snakes.append(snake)
if oldTail == None:
continue # happens when snake is still growing
x, y = oldTail
self.gmap[x][y].snakes.remove(snake)
# simple animation after crashing
for snake in self.crashedSnakes:
# may set snake.inHeaven flag
snake.crashAnimation()
# remove snakes that are already in heaven
self.crashedSnakes[:] = [s for s in self.crashedSnakes if not s.inHeaven]
# drunk or owned snakes
for snake in self.getCrashedSnakes():
snake.isAlive = False
snake.leaveGrid(sprites)
self.crashedSnakes.append(snake)
| Python |
import pygame
from globals import *
class Tile:
def __init__(self, position, isWall = False):
self.position = position
self.isWall = isWall
self.snakes = []
def getSymbol(self):
aliveSnakes = filter (lambda snake: snake.isAlive, self.snakes)
if self.isWall:
return WALL
elif aliveSnakes == []:
return EMPTY
else:
return aliveSnakes[0].symbol
def isEmpty(self):
if self.isWall: return False
aliveSnakes = filter (lambda snake: snake.isAlive, self.snakes)
return not aliveSnakes
| Python |
#!/usr/bin/env python
import os
import sys
import pygame
import time
import math
from pygame.locals import *
from globals import *
from grid import GameGrid
from snake import Snake, BasicSnake
from ai import AI, AIGrid, AISnake
# pygame.init() causes delays upon quit due to SDL mixer on my system
# pygame.time.get_ticks will not work like this though
pygame.display.init()
pygame.font.init()
# print 'Warning, sound disabled'
if not pygame.font:
print "Warning, fonts disabled"
# switches
displayVoronoi = False
# resources
bg = "grid-800x800.jpg"
screen = pygame.display.set_mode([XRES, YRES])
# using sprites might be a bit
# overkill but i want to try it out
sprites = pygame.sprite.LayeredDirty()
# initialize grid with snakes
background = pygame.image.load(bg).convert()
grid = GameGrid((DIMX, DIMY))
#grid.addSnake(Snake(grid, True, (255, 255, 255), [[3, DIMY/2+2], [3, DIMY/2+1], [3, DIMY/2], [2, DIMY/2], [1, DIMY/2]], 50, str(0), RIGHT))
grid.addSnake(Snake(grid, True, (255, 255, 255), [(4, DIMY/2)], 10, str(0), RIGHT))
grid.addSnake(Snake(grid, False, (255, 150, 0), [(DIMX-4, DIMY/2)], 10, str(1), LEFT))
#grid.addSnake(Snake(grid, False, (255, 0, 255), [(DIMX-3, DIMY/2+4)], 100, str(2), LEFT))
# initialize wall sprites
for wallSprite in grid.wallSprites:
sprites.add(wallSprite)
# initialize snake sprites
for snake in grid.snakes:
for segmentSprite in snake.segmentSprites:
sprites.add(segmentSprite)
clock = pygame.time.Clock() # not used atm
screen.blit(background, (0, 0))
pygame.display.update()
# initialize AI
walls = [[(0,0), (DIMX-1, 0)],
[(DIMX-1, 0), (DIMX-1, DIMY-1)],
[(DIMX-1, DIMY-1), (0, DIMY-1)],
[(0, DIMY-1), (0, 0)]]
ai = AI(walls, grid)
def gameover():
return grid.isEmpty()
def displayTerritories():
t1 = time.time()
retSizes, gridMap = ai.getTerritories()
t2 = time.time()
colors = []
for snake in grid.snakes:
if snake.isAlive:
colors.append(snake.color)
drawRect = pygame.draw.rect
gmap = grid.gmap
log = math.log
for x in xrange(DIMX):
for y in xrange(DIMY):
topleft = posInPixels ((x, y))
if gridMap[x][y] == 0:
if gmap[x][y].isEmpty():
drawRect(screen, BGTILECOLOR, (topleft, (TILESIZE, TILESIZE)))
continue
n = log(gridMap[x][y], 2)
index = int(n)
if index == n:
c = colors[index]
color = (c[0] / 2, c[1] / 2, c[2] / 2)
drawRect(screen, color, (topleft, (TILESIZE, TILESIZE)))
else:
drawRect(screen, BGTILECOLOR, (topleft, (TILESIZE, TILESIZE)))
t3 = time.time()
#print "time1:", 1000*(t2-t1)
#print "time2:", 1000*(t3-t2)
TIMEPERMOVE = 100
"""
from datetime import datetime
startingTime = datetime.now()
ai.voronoiDebug()
print (datetime.now() - startingTime).microseconds / 1000.0
"""
voronoiSprites = []
while not gameover():
if displayVoronoi:
displayTerritories()
spriteRects = sprites.draw(screen)
if displayVoronoi:
pygame.display.update()
else:
pygame.display.update(spriteRects)
sprites.clear(screen, background)
t1 = time.time()
ai.run(timelimit=TIMEPERMOVE) # timelimit not in use atm
t2 = time.time()
time2wait = int(TIMEPERMOVE-1000*(t2-t1))
pygame.time.delay(time2wait)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if len(grid.snakes) == 0:
continue
if event.key == K_UP:
grid.snakes[0].direction = UP
if event.key == K_DOWN:
grid.snakes[0].direction = DOWN
if event.key == K_RIGHT:
grid.snakes[0].direction = RIGHT
if event.key == K_LEFT:
grid.snakes[0].direction = LEFT
if event.key == K_w:
grid.snakes[1].direction = UP
if event.key == K_d:
grid.snakes[1].direction = RIGHT
if event.key == K_s:
grid.snakes[1].direction = DOWN
if event.key == K_a:
grid.snakes[1].direction = LEFT
ai.moveBots()
grid.update(sprites)
ai.update()
pygame.quit()
sys.exit()
| Python |
from globals import *
from mysprite import MySprite
# basic snake logic
class BasicSnake:
def __init__(self, grid, isHuman, segments, totalLength, symbol, direction):
self.grid = grid
self.isHuman = isHuman
self.length = len(segments)
self.totalLength = totalLength
self.symbol = symbol
self.direction = direction
self.isAlive = True
self.segments = []
for segment in segments:
self.segments.append(segment)
grid.gmap[segment[0]][segment[1]].snakes.append(self) # grid tile update
# this is slow, we rather let dead snakes on the grid (without impact)
def leaveGrid(self):
for segment in self.segments:
x, y = segment
snakes = self.grid.gmap[x][y].snakes
self.grid.gmap[x][y].snakes = filter (lambda snake: snake != self, snakes)
def update(self):
newHead = addZip (self.segments[0]) (MOVEMODS[self.direction])
# add new head
self.segments.insert(0, newHead)
self.length += 1
# remove old tail
oldTail = None
if self.length == self.totalLength + 1:
oldTail = self.segments.pop()
self.length -= 1
return newHead, oldTail
# snake also handling sprites of its segments
class Snake(BasicSnake):
def __init__(self, grid, isHuman, color, segments, totalLength, symbol, direction):
BasicSnake.__init__(self, grid, isHuman, segments, totalLength, symbol, direction)
self.segmentSprites = []
for segment in segments:
self.segmentSprites.append(MySprite(color, segment))
self.color = color
self.inHeaven = False
self.roundsNotAlive = 0
def leaveGrid(self, sprites):
#BasicSnake.leaveGrid(self) <- slow
for segmentSprite in self.segmentSprites:
sprites.move_to_back(segmentSprite) # be overdrawn
def crashAnimation(self):
self.roundsNotAlive += 1
if self.roundsNotAlive > 6:
for segmentSprite in self.segmentSprites:
segmentSprite.kill()
self.inHeaven = True # finally...
return
# blink blink
if self.roundsNotAlive % 2 == 0:
for segmentSprite in self.segmentSprites:
segmentSprite.image.set_alpha(0)
segmentSprite.dirty = 1
else:
for segmentSprite in self.segmentSprites:
segmentSprite.image.set_alpha(200)
segmentSprite.dirty = 1
def update(self, sprites):
newHead, oldTail = BasicSnake.update(self)
newHeadSprite = MySprite(self.color, newHead)
self.segmentSprites.insert(0, newHeadSprite) # add new head to segmentSprites
sprites.add(newHeadSprite) # add it also to "global" sprites
if oldTail != None:
oldTailSprite = self.segmentSprites.pop() # remove old tail from segmentSprites
sprites.remove(oldTailSprite) # remove it also from "global" sprites
return newHead, oldTail
| Python |
from datetime import datetime
from math import fabs
import random
from grid import BasicGrid, SnakeContainer
from snake import BasicSnake
from globals import *
# There is a special case when snake.totalLength == 1.
# This case is supported but requires some additional
# code, which is not really pretty. Maybe there is a
# way to include this case implicitly.
# Note that if snake.totalLength == 2, it can go
# "through" itself. This behaviour seems to be
# wrong but is acceptable product of our algorithm.
# If desired, it could be handled by a little code
# when detecting crashes.
# Other case works as expected.
# snake composed of line segments
class AISnake:
def __init__(self, basicSnake):
self.template = basicSnake
self.isHuman = basicSnake.isHuman
self.length = len(basicSnake.segments)
self.totalLength = basicSnake.totalLength
self.symbol = basicSnake.symbol
self.direction = basicSnake.direction
self.lsegments = []
self.head = basicSnake.segments[-1]
# convert discrete segments into line segments
for i in xrange(self.length-2, -1, -1):
newHead = basicSnake.segments[i]
self.addNewHead(newHead)
# creates new line segment or extends existing
def addNewHead(self, newHead):
unitVec = tuple(subZip (newHead) (self.head))
if self.lsegments == [] or self.lsegments[0][2] != unitVec:
self.lsegments.insert(0, [newHead, self.head, unitVec])
else:
self.lsegments[0][0] = newHead
self.head = newHead
def removeTail(self):
last = self.lsegments[-1]
last[1] = addZip (last[1]) (last[2])
if last[0] == last[1]:
lsegment = self.lsegments.pop(-1)
def update(self):
newHead = addZip (self.head) (MOVEMODS[self.direction])
self.addNewHead(newHead)
self.length += 1
# remove old tail
if self.length == self.totalLength + 1:
self.removeTail()
self.length -= 1
# continuous grid that enables usage of continuous bfs to
# calculate voronoi territories. Kept in sync with gameGrid.
class AIGrid:
def __init__(self, gridWalls, gameSnakes):
self.snakes = [] # order of snakes is going to be fixed
self.gridWalls = gridWalls
for snake in gameSnakes:
if snake.isAlive:
self.snakes.append(AISnake(snake))
def isCrashed(self, snake, wall):
if snake.lsegments != []: # snake has length > 1
# prevent head being crashed with its own lsegment
if snake.lsegments[0] == wall:
return False
else: # snake has length == 1
# prevent head being crashed with itself
if [snake.head, snake.head, snake] == wall:
return False
hx = snake.head[0]
hy = snake.head[1]
w0x = wall[0][0]
w0y = wall[0][1]
w1x = wall[1][0]
w1y = wall[1][1]
if hx == w0x and hy >= min(w0y, w1y) and hy <= max(w0y, w1y):
return True
if hy == w0y and hx >= min(w0x, w1x) and hx <= max(w0x, w1x):
return True
return False
def update(self):
# update snakes
for snake in self.snakes:
snake.update()
# check for collisions
# TODO: make quad tree of grid, solve collisions on it
# TODO: probably exclude case when snake.totalLenght == 1,
# it makes code messy, or rethink the way we work
# with lsegments.
walls = []
walls += self.gridWalls
for snake in self.snakes:
if snake.lsegments != []:
walls += snake.lsegments
else:
# snake has only head (no lsegments) but we still
# want to recognize crashes with it. This happens
# only if snake.totalLength == 1.
walls.append([snake.head, snake.head, snake])
# If a snake crashes, it is removed from self.snakes and hence,
# we need to keep information on which position it was stored
# for its later adding back (relevant if called from negamax).
crashedSnakes = []
index = 0
for snake in self.snakes:
for wall in walls:
if self.isCrashed(snake, wall):
crashedSnakes.append((index, snake))
break
index += 1
for index, snake in crashedSnakes:
self.snakes.remove(snake)
return crashedSnakes
# AI works with relative moves (STRAIGHT, RIGHT, LEFT)
class AI:
def __init__ (self, walls, gameGrid): # TODO: we need whole gameGrid only for debug, snakes are enough
self.gameGrid = gameGrid
self.grid = AIGrid(walls, gameGrid.snakes)
self.botsMoveOpts = []
self.humansMoveOpts = []
self.bestBotsMove = None
self.aliveBotsCount = 0
self.aliveHumansCount = 0
for snake in self.grid.snakes:
if snake.isHuman:
self.aliveHumansCount += 1
else:
self.aliveBotsCount += 1
for cnt in xrange(self.aliveBotsCount+1):
self.botsMoveOpts.append([])
self.generateMoves(self.botsMoveOpts[cnt], cnt)
for cnt in xrange(self.aliveHumansCount+1):
self.humansMoveOpts.append([])
self.generateMoves(self.humansMoveOpts[cnt], cnt)
#self.startingTime = 0 # time when negamax started
#self.timelimit = 0 # how long it can run
#FIXME: unusuable atm
def getTerritories(self):
return self.voronoi()
# pregenerate all possible relative moves of a team of
# snakes of teamSize or less members (humans or bots)
# e.g. for two snakes there are 9 posibilites
def generateMoves(self, moveList, teamSize):
del moveList[:]
if teamSize <= 0:
moveList.append([])
return
moveGen = [[move] for move in RELMOVES]
while len(moveGen) != 0:
partialMove = moveGen.pop(0)
if len(partialMove) == teamSize:
moveList.append(partialMove)
continue
for move in RELMOVES:
moveGen.append([elem for elem in partialMove]+[move])
def setMoves(self, botsMove, humansMove):
# store current state of snakes
snakeRecords = [] # [(direction, length, head, last segment), ...]
for snake in self.grid.snakes:
oldTail = None
if snake.length == snake.totalLength and snake.lsegments != []:
oldTail = snake.lsegments[-1][:]
snakeRecords.append((snake.direction, snake.length, snake.head, oldTail))
# set and apply moves (directions) of snakes
botIndex = 0
humanIndex = 0
for snake in self.grid.snakes:
if snake.isHuman:
snake.direction = convertDirection (snake.direction) (humansMove[humanIndex])
humanIndex += 1
else:
snake.direction = convertDirection (snake.direction) (botsMove[botIndex])
botIndex += 1
return snakeRecords
# reverting changes made by update()
def revertMoves(self, snakeRecords, crashedSnakes):
# Note that crashedSnakes are ordered by index in
# ascending order implicitly. That assures we insert
# snakes back to their correct positions.
for index, snake in crashedSnakes:
self.grid.snakes.insert(index, snake)
for index, snake in enumerate(self.grid.snakes):
snakeRecord = snakeRecords[index]
snake.direction = snakeRecord[0]
snake.length = snakeRecord[1]
snake.head = snakeRecord[2]
oldTail = snakeRecord[3]
if oldTail != None:
x1, y1 = oldTail[0]
x2, y2 = oldTail[1]
if fabs(x2-x1) == 1 or fabs(y2-y1) == 1:
snake.lsegments.append(oldTail)
else:
tail = snake.lsegments[-1]
tail[1] = subZip (tail[1]) (tail[2])
if snake.lsegments != []:
head = snake.lsegments[0]
x1, y1 = head[0]
x2, y2 = head[1]
if fabs(x2-x1) == 1 or fabs(y2-y1) == 1:
snake.lsegments.pop(0)
else:
head[0] = subZip (head[0]) (head[2])
# FIXME: unusuable atm
# TODO: this algorithm is very very slow and unusable as part of evaluation
# of negamax leaves. Find something much more faster.
# get size of voronoi territory for each snake and return them
# bfs variant with a queue for each snake and taking turns
def voronoi(self):
retSizes = [0 for snake in self.snakes]
gridMap = [[0 for y in xrange(self.grid.size[1])] for x in xrange(self.grid.size[0])]
expandedPrevs = [(1 if snake.isAlive else 0) for snake in self.snakes]
ques = [([snake.segments[0]] if snake.isAlive else []) for snake in self.snakes]
empty = False
while not empty:
index = 0
for que in ques:
processed = 0
expandedPrev = expandedPrevs[index]
expandedPrevs[index] = 0
while processed < expandedPrev:
head = que.pop(0)
processed += 1
if head == (-1, -1): # territory border, see code below
retSizes[index] -= 1 # nobody's tile but has been counted
continue
for move in MOVES:
nextTile = addZip(head)(MOVEMODS[move])
# if occupied or we have visited this tile before, continue
if not self.grid.gmap[nextTile[0]][nextTile[1]].isEmpty() \
or gridMap[nextTile[0]][nextTile[1]] & (1 << index) > 0:
continue
que.append(nextTile)
retSizes[index] += 1
expandedPrevs[index] += 1
# (1 << index) is a snake unique mark (footprint)
gridMap[nextTile[0]][nextTile[1]] |= (1 << index)
index += 1
# Some tiles (territory borders) might have been visited
# by more than one snake. Set them to (-1, -1) for the
# code above.
for que in ques:
for i in xrange(len(que)):
tileVal = gridMap[que[i][0]][que[i][1]]
setBits = 0
while tileVal > 0:
tileVal &= tileVal - 1 # clear the least significant bit set
setBits += 1
if setBits > 1:
que[i] = (-1, -1)
empty = True
for que in ques:
if len(que) > 0:
empty = False
# end while
return retSizes, gridMap
# evaluate current grid state (position)
def evaluate(self):
botsvsHumans = 0
for snake in self.grid.snakes:
if snake.isHuman: botsvsHumans -= 1
else: botsvsHumans += 1
botTerritory = 0
humanTerritory = 0
"""
retSizes, gridMap = self.voronoi()
for i, retSize in enumerate(retSizes):
if self.snakes[i].isHuman:
humanTerritory += retSize
else:
botTerritory += retSize
"""
return (botsvsHumans, botTerritory - humanTerritory)
def outOfTime(self):
timeDiff = (datetime.now() - self.startingTime).microseconds / 1000.0
if timeDiff > self.timelimit:
return True
return False
# TODO: iterating, calculating till timelimit
def run(self, timelimit):
if self.aliveBotsCount == 0:
return
self.bestBotsMove = self.botsMoveOpts[self.aliveBotsCount][0] # initial value to be reseted
"""
self.startingTime = datetime.now()
self.timelimit = timelimit
depth2reach = 3
while True:
self.negamax(0, depth2reach)
depth2reach += 1
if self.outOfTime(): break
"""
self.startingTime = datetime.now()
self.negamax(0, 8, (-1E10, -1E10), (1E10, 1E10), [])
#print self.negamax(0, 2, (-1E10, -1E10), (1E10, 1E10), []), RMOVESTRS[self.bestBotsMove[0]]
#self.grid.dump()
#print "-------------------------------"
print (datetime.now() - self.startingTime).microseconds / 1000.0
# lexicographical ordering operator on position values
def greaterThan(self, v1, v2):
return v1[0] > v2[0] or (v1[0] == v2[0] and v1[1] > v2[1])
# lexicographical ordering operator on position values
def greaterThanOrEqual(self, v1, v2):
return v1[0] > v2[0] or (v1[0] == v2[0] and v1[1] >= v2[1])
# FIXME: unusuable atm
# move sorting according to count of crashes likely to happen
# better moves should be examined first for algorithm to be faster
def sortMoves(self, moveOptions, snakeTeam):
sortList = []
for moveOption in moveOptions:
index = 0
likelyDeaths = 0
for snake in snakeTeam:
if snake.isAlive:
relMove = moveOption[index]
absMove = convertDirection (snake.direction) (relMove)
moveMod = MOVEMODS[absMove]
x, y = addZip (snake.segments[0]) (moveMod)
if not self.grid.gmap[x][y].isEmpty():
likelyDeaths += 1
index += 1
index2 = 0
for elem in sortList:
if elem[0] >= likelyDeaths:
sortList.insert(index2, (likelyDeaths, moveOption))
break
index2 += 1
if index2 == len(sortList):
sortList.append((likelyDeaths, moveOption))
sortedMoveOptions = []
for elem in sortList:
sortedMoveOptions.append(elem[1])
return sortedMoveOptions
# search in depth for the best move using alpha-beta prunned negamax
# depth2reach should be even (odd depth2reach gives the same as depth2reach - 1)
def negamax(self, depth, depth2reach, alpha, beta, botsMove):
if depth == depth2reach:
return self.evaluate()
values = []
maxValue = (-1E10, -1E10) # (life diff, territory diff)
isBotsMove = (depth % 2 == 0)
if isBotsMove:
moveOptions = self.botsMoveOpts[self.aliveBotsCount]
#snakeTeam = self.bots
else:
moveOptions = self.humansMoveOpts[self.aliveHumansCount]
#snakeTeam = self.humans
# sorting moves for alpha beta
#moveOptions = self.sortMoves(moveOptions, snakeTeam)
# moves are applied only at odd depth (where both humans' and bots' move has been chosen)
for move in moveOptions:
if isBotsMove:
# move is going to be applied one level below
tmp = self.negamax(depth+1, depth2reach, (-beta[0], -beta[1]), (-alpha[0], -alpha[1]), move)
value = (-tmp[0], -tmp[1])
else:
snakeRecords = self.setMoves(botsMove, move) # set moves
crashedSnakes = self.grid.update() # apply moves
# update counts of alive snakes and determine
# value of current position based on them
crashedBotsCount = 0
crashedHumansCount = 0
for index, snake in crashedSnakes:
if snake.isHuman:
crashedHumansCount += 1
else:
crashedBotsCount += 1
self.aliveBotsCount -= crashedBotsCount
self.aliveHumansCount -= crashedHumansCount
currentLifeValue = self.aliveHumansCount - self.aliveBotsCount
if alpha[0] > currentLifeValue or beta[0] < currentLifeValue:
# alpha prunned based on current difference in snakes alive
value = (currentLifeValue, 0)
else:
# regular position evaluation
tmp = self.negamax(depth+1, depth2reach, (-beta[0], -beta[1]), (-alpha[0], -alpha[1]), []) # go deeper
value = (-tmp[0], -tmp[1])
self.revertMoves(snakeRecords, crashedSnakes) # revert moves
# revert counts of alive snakes
self.aliveBotsCount += crashedBotsCount
self.aliveHumansCount += crashedHumansCount
# if self.outOfTime(): return 0
# updating local alpha value
if self.greaterThan(value, alpha):
alpha = value
# updating maxValue and best found move of bots
if self.greaterThan(value, maxValue):
maxValue = value
if depth == 0:
self.bestBotsMove = move
#print " " * (depth + 1), value, RMOVESTRS[move[0]] if len(move) > 0 else None
# alpha beta prunning based on current difference in
# snakes alive and also territory sizes counted in leaves
if self.greaterThanOrEqual(alpha, beta):
break
return maxValue
def moveBots(self):
index = 0
for snake in self.grid.snakes:
if not snake.isHuman:
absDir = convertDirection (snake.direction) (self.bestBotsMove[index])
snake.template.direction = absDir
index += 1
# synchronize AIGrid with GameGrid
def update(self):
for aiSnake in self.grid.snakes:
aiSnake.direction = aiSnake.template.direction
crashedSnakes = self.grid.update()
for index, snake in crashedSnakes:
if snake.isHuman:
self.aliveHumansCount -= 1
else:
self.aliveBotsCount -= 1
| Python |
# directions/moves
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
STRAIGHT = 0
RELMOVES = [STRAIGHT, RIGHT, LEFT]
MOVES = [UP, RIGHT, DOWN, LEFT]
MOVESTRS = ["UP", "RIGHT", "DOWN", "LEFT"]
RMOVESTRS = ["STRAIGHT", "RIGHT", "NONE", "LEFT"]
# converts relative direction (LEFT, RIGHT, STRAIGHT) into absolute (UP, RIGHT, DOWN, LEFT)
convertDirection = lambda baseDir: lambda relDir: (baseDir + relDir) % 4
# first coord - columns - horizontal axis - x
# second coord - rows - vertical axis - y
MOVEMODS = {UP: (0, -1), RIGHT: (+1, 0), DOWN: (0, +1), LEFT: (-1, 0)}
# grid tile symbols
EMPTY = '.'
WALL = '#'
# snakes are denoted '0', '1', '2', ...
XRES = 800
YRES = 700
# grid size
DIMX = 20
DIMY = 20
TILESIZE = 5
# colors
BGTILECOLOR = [65, 65, 145]
BGLINECOLOR = [114, 117, 172]
WALLCOLOR = [0, 0, 0]
# position on grid -> position on screen
OFFSETX = (XRES/2 - DIMX * 3 - 1) - (XRES/2 - DIMX * 3 - 1) % 6 + 1
OFFSETY = (YRES/2 - DIMY * 3 - 1) - (YRES/2 - DIMY * 3 - 1) % 6 + 1
posInPixels = lambda k: (6*k[0] + OFFSETX, 6*k[1] + OFFSETY)
# adds/subs two tuples/lists as vectors
addZip = lambda l1: lambda l2: tuple([l1[i] + l2[i] for i in xrange(len(l1))])
subZip = lambda l1: lambda l2: tuple([l1[i] - l2[i] for i in xrange(len(l1))])
| Python |
import pygame
from globals import *
# describes all sprites in the game
class MySprite(pygame.sprite.DirtySprite):
def __init__(self, color, position):
pygame.sprite.DirtySprite.__init__(self)
# create the image that will be displayed
# and fill it with the right color
self.image = pygame.Surface([TILESIZE, TILESIZE])
self.image.fill(color)
self.dirty = 0
self.rect = self.image.get_rect()
self.rect.topleft = posInPixels (position)
| Python |
import os
import sys
import unittest
gae_path = '/usr/local/google/home/proppy/google_appengine'
current_path = os.path.abspath(os.path.dirname(__file__))
tests_path = os.path.join(current_path, 'tests')
sys.path[0:0] = [
current_path,
tests_path,
gae_path,
# All libs used by webapp2 and extras.
os.path.join(current_path, 'lib', 'babel'),
os.path.join(current_path, 'lib', 'Jinja2-2.6'),
os.path.join(current_path, 'lib', 'Mako-0.4.1'),
os.path.join(current_path, 'lib', 'gaepytz-2011h'),
os.path.join(current_path, 'lib', 'WebOb-1.2.2'),
# SDK libs.
os.path.join(gae_path, 'lib', 'django_0_96'),
#os.path.join(gae_path, 'lib', 'webob'),
os.path.join(gae_path, 'lib', 'yaml', 'lib'),
os.path.join(gae_path, 'lib', 'protorpc'),
os.path.join(gae_path, 'lib', 'simplejson'),
]
all_tests = [f[:-8] for f in os.listdir(tests_path) if f.endswith('_test.py')]
def get_suite(tests):
tests = sorted(tests)
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for test in tests:
suite.addTest(loader.loadTestsFromName(test))
return suite
if __name__ == '__main__':
"""
To run all tests:
$ python run_tests.py
To run a single test:
$ python run_tests.py app
To run a couple of tests:
$ python run_tests.py app config sessions
To run code coverage:
$ coverage run run_tests.py
$ coverage report -m
"""
tests = sys.argv[1:]
if not tests:
tests = all_tests
tests = ['%s_test' % t for t in tests]
suite = get_suite(tests)
unittest.TextTestRunner(verbosity=2).run(suite)
| Python |
import ConfigParser
import os
import textwrap
import StringIO
import sys
import unittest
import StringIO
import test_utils
from manage.config import Config
class TestConfig(test_utils.BaseTestCase):
def get_fp(self, config):
return StringIO.StringIO(textwrap.dedent(config))
def test_get(self):
fp = self.get_fp("""\
[DEFAULT]
foo = bar
[section_1]
baz = ding
""")
config = Config()
config.readfp(fp)
self.assertEqual(config.get('section_1', 'foo'), 'bar')
self.assertEqual(config.get('section_1', 'baz'), 'ding')
# Invalid key.
self.assertEqual(config.get('section_1', 'invalid'), None)
def test_getboolean(self):
fp = self.get_fp("""\
[DEFAULT]
true_1 = 1
true_2 = yes
false_1 = 0
false_2 = no
[section_1]
true_3 = on
true_4 = true
false_3 = off
false_4 = false
invalid = bar
""")
config = Config()
config.readfp(fp)
self.assertEqual(config.getboolean('section_1', 'true_1'), True)
self.assertEqual(config.getboolean('section_1', 'true_2'), True)
self.assertEqual(config.getboolean('section_1', 'true_3'), True)
self.assertEqual(config.getboolean('section_1', 'true_4'), True)
self.assertEqual(config.getboolean('section_1', 'false_1'), False)
self.assertEqual(config.getboolean('section_1', 'false_2'), False)
self.assertEqual(config.getboolean('section_1', 'false_3'), False)
self.assertEqual(config.getboolean('section_1', 'false_4'), False)
# Invalid boolean.
self.assertEqual(config.getboolean('section_1', 'invalid'), None)
def test_getfloat(self):
fp = self.get_fp("""\
[DEFAULT]
foo = 0.1
[section_1]
baz = 0.2
invalid = bar
""")
config = Config()
config.readfp(fp)
self.assertEqual(config.getfloat('section_1', 'foo'), 0.1)
self.assertEqual(config.getfloat('section_1', 'baz'), 0.2)
# Invalid float.
self.assertEqual(config.getboolean('section_1', 'invalid'), None)
def test_getint(self):
fp = self.get_fp("""\
[DEFAULT]
foo = 999
[section_1]
baz = 1999
invalid = bar
""")
config = Config()
config.readfp(fp)
self.assertEqual(config.getint('section_1', 'foo'), 999)
self.assertEqual(config.getint('section_1', 'baz'), 1999)
# Invalid int.
self.assertEqual(config.getboolean('section_1', 'invalid'), None)
def test_getlist(self):
fp = self.get_fp("""\
[DEFAULT]
animals =
rhino
rhino
hamster
hamster
goat
goat
[section_1]
fruits =
orange
watermellow
grape
""")
config = Config()
config.readfp(fp)
# Non-unique values.
self.assertEqual(config.getlist('section_1', 'animals'), [
'rhino',
'rhino',
'hamster',
'hamster',
'goat',
'goat',
])
self.assertEqual(config.getlist('section_1', 'fruits'), [
'orange',
'watermellow',
'grape',
])
# Unique values.
self.assertEqual(config.getlist('section_1', 'animals', unique=True), [
'rhino',
'hamster',
'goat',
])
def test_interpolation(self):
fp = self.get_fp("""\
[DEFAULT]
path = /path/to/%(path_name)s
[section_1]
path_name = foo
path_1 = /special%(path)s
path_2 = /special/%(path_name)s
[section_2]
path_name = bar
[section_3]
path_1 = /path/to/%(section_1|path_name)s
path_2 = /path/to/%(section_2|path_name)s
path_3 = /%(section_1|path_name)s/%(section_2|path_name)s/%(section_1|path_name)s/%(section_2|path_name)s
path_error_1 = /path/to/%(section_3|path_error_1)s
path_error_2 = /path/to/%(section_3|path_error_3)s
path_error_3 = /path/to/%(section_3|path_error_2)s
path_not_really = /path/to/%(foo
""")
config = Config()
config.readfp(fp)
self.assertEqual(config.get('section_1', 'path'), '/path/to/foo')
self.assertEqual(config.get('section_1', 'path_1'), '/special/path/to/foo')
self.assertEqual(config.get('section_1', 'path_2'), '/special/foo')
self.assertEqual(config.get('section_2', 'path'), '/path/to/bar')
self.assertEqual(config.get('section_3', 'path_1'), '/path/to/foo')
self.assertEqual(config.get('section_3', 'path_2'), '/path/to/bar')
self.assertEqual(config.get('section_3', 'path_3'), '/foo/bar/foo/bar')
# Failed interpolation (recursive)
self.assertRaises(ConfigParser.InterpolationError, config.get,
'section_3', 'path_error_1')
self.assertRaises(ConfigParser.InterpolationError, config.get,
'section_3', 'path_error_2')
self.assertRaises(ConfigParser.InterpolationError, config.get,
'section_3', 'path_error_3')
self.assertEqual(config.get('section_3', 'path_not_really'), '/path/to/%(foo')
if __name__ == '__main__':
test_base.main()
| Python |
import ConfigParser
import re
InterpolationError = ConfigParser.InterpolationError
InterpolationSyntaxError = ConfigParser.InterpolationSyntaxError
NoOptionError = ConfigParser.NoOptionError
NoSectionError = ConfigParser.NoSectionError
class Converter(object):
"""Converts config values to several types.
Supported types are boolean, float, int, list and unicode.
"""
_boolean_states = {
'1': True,
'yes': True,
'true': True,
'on': True,
'0': False,
'no': False,
'false': False,
'off': False,
}
def to_boolean(self, value):
key = value.lower()
if key not in self._boolean_states:
raise ValueError(
'Not a boolean: %r. Booleans must be one of %s.' %
(value, ', '.join(self._boolean_states.keys())))
return self._boolean_states[key]
def to_float(self, value):
return float(value)
def to_int(self, value):
return int(value)
def to_list(self, value):
value = [line.strip() for line in value.splitlines()]
return [v for v in value if v]
def to_unicode(self, value):
return unicode(value)
class Config(ConfigParser.RawConfigParser):
"""Extended RawConfigParser with the following extra features:
- All `get*()` functions allow a default to be returned. Instead
of throwing errors when no section or option is found, it returns the
default value or None.
- The `get*()` functions can receive a list of sections to be searched in
order.
- A `getlist()` method splits multi-line values into a list.
- It also implements the magical interpolation behavior similar to the one
from `SafeConfigParser`, but also supports references to sections.
This means that values can contain format strings which refer to other
values in the config file. These variables are replaced on the fly.
An example of variable substituition is::
[my_section]
app_name = my_app
path = path/to/%(app_name)s
Here, calling `get('my_section', 'path')` will automatically replace
variables, resulting in `path/to/my_app`. To get the raw value without
substitutions, use `get('my_section', 'path', raw=True)`.
To reference a different section, separate the section and option
names using a pipe::
[my_section]
app_name = my_app
[my_other_section]
path = path/to/%(my_section|app_name)s
If any variables aren't found, a `InterpolationError`is
raised.
Variables are case sensitive, differently from the interpolation behavior
in `SafeConfigParser`.
"""
converter = Converter()
_interpolate_re = re.compile(r"%\(([^)]*)\)s")
def get(self, sections, option, default=None, raw=False):
"""Returns a config value from a given section, converted to unicode.
:param sections:
The config section name, or a list of config section names to be
searched in order.
:param option:
The config option name.
:param default:
A default value to return in case the section or option are not
found. Default is None.
:param raw:
If True, doesn't perform variable substitution if the value
has placeholders. Default is False.
:returns:
A config value.
"""
converter = self.converter.to_unicode
return self._get_many(sections, option, converter, default, raw)
def getboolean(self, sections, option, default=None, raw=False):
"""Returns a config value from a given section, converted to boolean.
See :methd:`get` for a description of the parameters.
"""
converter = self.converter.to_boolean
return self._get_many(sections, option, converter, default, raw)
def getfloat(self, sections, option, default=None, raw=False):
"""Returns a config value from a given section, converted to float.
See :methd:`get` for a description of the parameters.
"""
converter = self.converter.to_float
return self._get_many(sections, option, converter, default, raw)
def getint(self, sections, option, default=None, raw=False):
"""Returns a config value from a given section, converted to int.
See :methd:`get` for a description of the parameters.
"""
converter = self.converter.to_int
return self._get_many(sections, option, converter, default, raw)
def getlist(self, sections, option, default=None, raw=False):
"""Returns a config value from a given section, converted to boolean.
See :methd:`get` for a description of the parameters.
"""
converter = self.converter.to_list
return self._get_many(sections, option, converter, default, raw)
def _get(self, section, option):
"""Wrapper for `RawConfigParser.get`."""
return ConfigParser.RawConfigParser.get(self, section, option)
def _get_many(self, sections, option, converter, default, raw):
"""Wraps get functions allowing default values and a list of sections
looked up in order until a value is found.
"""
if isinstance(sections, basestring):
sections = [sections]
for section in sections:
try:
value = self._get(section, option)
if not raw:
value = self._interpolate(section, option, value)
return converter(value)
except (NoSectionError, NoOptionError):
pass
return default
def _interpolate(self, section, option, raw_value, tried=None):
"""Performs variable substituition in a config value."""
variables = self._get_variable_names(section, option, raw_value)
if not variables:
return raw_value
if tried is None:
tried = [(section, option)]
values = {}
for var in variables:
parts = var.split('|', 1)
if len(parts) == 1:
new_section, new_option = section, var
else:
new_section, new_option = parts
if parts in tried:
continue
try:
found = self._get(new_section, new_option)
except (NoSectionError, NoOptionError):
raise InterpolationError(section, option,
'Could not find section %r and option %r.' %
(new_section, new_option))
tried.append((new_section, new_option))
if not self.has_option(new_section, new_option):
tried.append(('DEFAULT', new_option))
values[var] = self._interpolate(new_section, new_option,
found, tried)
try:
return raw_value % values
except KeyError, e:
raise InterpolationError(section, option,
'Cound not replace %r: variable %r is missing.' %
(raw_value, e.args[0]))
def _get_variable_names(self, section, option, raw_value):
"""Returns a list of placeholder names in a config value, if any.
Adapted from SafeConfigParser._interpolate_some().
"""
rv = set()
while raw_value:
pos = raw_value.find('%')
if pos < 0:
return rv
if pos > 0:
raw_value = raw_value[pos:]
char = raw_value[1:2]
if char == '%':
raw_value = raw_value[2:]
elif char == '(':
match = self._interpolate_re.match(raw_value)
if match is None:
raise InterpolationSyntaxError(option, section,
'Bad interpolation variable reference: %r.' %
raw_value)
rv.add(match.group(1))
raw_value = raw_value[match.end():]
else:
raise InterpolationSyntaxError(option, section,
"'%%' must be followed by '%%' or '(', "
"found: %r." % raw_value)
return rv
| Python |
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
"""Command-line parsing library
This module is an optparse-inspired command-line parsing library that:
- handles both optional and positional arguments
- produces highly informative usage messages
- supports parsers that dispatch to sub-parsers
The following is a simple usage example that sums integers from the
command-line and writes the result to a file::
parser = argparse.ArgumentParser(
description='sum the integers at the command line')
parser.add_argument(
'integers', metavar='int', nargs='+', type=int,
help='an integer to be summed')
parser.add_argument(
'--log', default=sys.stdout, type=argparse.FileType('w'),
help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()
The module contains the following public classes:
- ArgumentParser -- The main entry point for command-line parsing. As the
example above shows, the add_argument() method is used to populate
the parser with actions for optional and positional arguments. Then
the parse_args() method is invoked to convert the args at the
command-line into an object with attributes.
- ArgumentError -- The exception raised by ArgumentParser objects when
there are errors with the parser's actions. Errors raised while
parsing the command-line are caught by ArgumentParser and emitted
as command-line messages.
- FileType -- A factory for defining types of files to be created. As the
example above shows, instances of FileType are typically passed as
the type= argument of add_argument() calls.
- Action -- The base class for parser actions. Typically actions are
selected by passing strings like 'store_true' or 'append_const' to
the action= argument of add_argument(). However, for greater
customization of ArgumentParser actions, subclasses of Action may
be defined and passed as the action= argument.
- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
ArgumentDefaultsHelpFormatter -- Formatter classes which
may be passed as the formatter_class= argument to the
ArgumentParser constructor. HelpFormatter is the default,
RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
not to change the formatting for help text, and
ArgumentDefaultsHelpFormatter adds information about argument defaults
to the help.
All other classes in this module are considered implementation details.
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
considered public as object names -- the API of the formatter objects is
still considered an implementation detail.)
"""
__version__ = '1.2.1'
__all__ = [
'ArgumentParser',
'ArgumentError',
'ArgumentTypeError',
'FileType',
'HelpFormatter',
'ArgumentDefaultsHelpFormatter',
'RawDescriptionHelpFormatter',
'RawTextHelpFormatter',
'Namespace',
'Action',
'ONE_OR_MORE',
'OPTIONAL',
'PARSER',
'REMAINDER',
'SUPPRESS',
'ZERO_OR_MORE',
]
import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap
from gettext import gettext as _
try:
set
except NameError:
# for python < 2.4 compatibility (sets module is there since 2.3):
from sets import Set as set
try:
basestring
except NameError:
basestring = str
try:
sorted
except NameError:
# for python < 2.4 compatibility:
def sorted(iterable, reverse=False):
result = list(iterable)
result.sort()
if reverse:
result.reverse()
return result
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
ZERO_OR_MORE = '*'
ONE_OR_MORE = '+'
PARSER = 'A...'
REMAINDER = '...'
_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
# =============================
# Utility functions and classes
# =============================
class _AttributeHolder(object):
"""Abstract base class that provides __repr__.
The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, ...)
The attributes are determined either by a class-level attribute,
'_kwarg_names', or by inspecting the instance __dict__.
"""
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
arg_strings.append('%s=%r' % (name, value))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
return sorted(self.__dict__.items())
def _get_args(self):
return []
def _ensure_value(namespace, name, value):
if getattr(namespace, name, None) is None:
setattr(namespace, name, value)
return getattr(namespace, name)
# ===============
# Formatting Help
# ===============
class HelpFormatter(object):
"""Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def __init__(self,
prog,
indent_increment=2,
max_help_position=24,
width=None):
# default setting for width
if width is None:
try:
width = int(_os.environ['COLUMNS'])
except (KeyError, ValueError):
width = 80
width -= 2
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = max_help_position
self._width = width
self._current_indent = 0
self._level = 0
self._action_max_length = 0
self._root_section = self._Section(self, None)
self._current_section = self._root_section
self._whitespace_matcher = _re.compile(r'\s+')
self._long_break_matcher = _re.compile(r'\n\n\n+')
# ===============================
# Section and indentation methods
# ===============================
def _indent(self):
self._current_indent += self._indent_increment
self._level += 1
def _dedent(self):
self._current_indent -= self._indent_increment
assert self._current_indent >= 0, 'Indent decreased below 0.'
self._level -= 1
class _Section(object):
def __init__(self, formatter, parent, heading=None):
self.formatter = formatter
self.parent = parent
self.heading = heading
self.items = []
def format_help(self):
# format the indented section
if self.parent is not None:
self.formatter._indent()
join = self.formatter._join_parts
for func, args in self.items:
func(*args)
item_help = join([func(*args) for func, args in self.items])
if self.parent is not None:
self.formatter._dedent()
# return nothing if the section was empty
if not item_help:
return ''
# add the heading if the section was non-empty
if self.heading is not SUPPRESS and self.heading is not None:
current_indent = self.formatter._current_indent
heading = '%*s%s:\n' % (current_indent, '', self.heading)
else:
heading = ''
# join the section-initial newline, the heading and the help
return join(['\n', heading, item_help, '\n'])
def _add_item(self, func, args):
self._current_section.items.append((func, args))
# ========================
# Message building methods
# ========================
def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section, heading)
self._add_item(section.format_help, [])
self._current_section = section
def end_section(self):
self._current_section = self._current_section.parent
self._dedent()
def add_text(self, text):
if text is not SUPPRESS and text is not None:
self._add_item(self._format_text, [text])
def add_usage(self, usage, actions, groups, prefix=None):
if usage is not SUPPRESS:
args = usage, actions, groups, prefix
self._add_item(self._format_usage, args)
def add_argument(self, action):
if action.help is not SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
def add_arguments(self, actions):
for action in actions:
self.add_argument(action)
# =======================
# Help-formatting methods
# =======================
def format_help(self):
help = self._root_section.format_help()
if help:
help = self._long_break_matcher.sub('\n\n', help)
help = help.strip('\n') + '\n'
return help
def _join_parts(self, part_strings):
return ''.join([part
for part in part_strings
if part and part is not SUPPRESS])
def _format_usage(self, usage, actions, groups, prefix):
if prefix is None:
prefix = _('usage: ')
# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = '%(prog)s' % dict(prog=self._prog)
# if optionals and positionals are available, calculate usage
elif usage is None:
prog = '%(prog)s' % dict(prog=self._prog)
# split optionals from positionals
optionals = []
positionals = []
for action in actions:
if action.option_strings:
optionals.append(action)
else:
positionals.append(action)
# build full usage string
format = self._format_actions_usage
action_usage = format(optionals + positionals, groups)
usage = ' '.join([s for s in [prog, action_usage] if s])
# wrap the usage parts if it's too long
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
# break usage into wrappable parts
part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
opt_usage = format(optionals, groups)
pos_usage = format(positionals, groups)
opt_parts = _re.findall(part_regexp, opt_usage)
pos_parts = _re.findall(part_regexp, pos_usage)
assert ' '.join(opt_parts) == opt_usage
assert ' '.join(pos_parts) == pos_usage
# helper for wrapping lines
def get_lines(parts, indent, prefix=None):
lines = []
line = []
if prefix is not None:
line_len = len(prefix) - 1
else:
line_len = len(indent) - 1
for part in parts:
if line_len + 1 + len(part) > text_width:
lines.append(indent + ' '.join(line))
line = []
line_len = len(indent) - 1
line.append(part)
line_len += len(part) + 1
if line:
lines.append(indent + ' '.join(line))
if prefix is not None:
lines[0] = lines[0][len(indent):]
return lines
# if prog is short, follow it with optionals or positionals
if len(prefix) + len(prog) <= 0.75 * text_width:
indent = ' ' * (len(prefix) + len(prog) + 1)
if opt_parts:
lines = get_lines([prog] + opt_parts, indent, prefix)
lines.extend(get_lines(pos_parts, indent))
elif pos_parts:
lines = get_lines([prog] + pos_parts, indent, prefix)
else:
lines = [prog]
# if prog is long, put it on its own line
else:
indent = ' ' * len(prefix)
parts = opt_parts + pos_parts
lines = get_lines(parts, indent)
if len(lines) > 1:
lines = []
lines.extend(get_lines(opt_parts, indent))
lines.extend(get_lines(pos_parts, indent))
lines = [prog] + lines
# join lines into usage
usage = '\n'.join(lines)
# prefix with 'usage:'
return '%s%s\n\n' % (prefix, usage)
def _format_actions_usage(self, actions, groups):
# find group indices and identify actions in groups
group_actions = set()
inserts = {}
for group in groups:
try:
start = actions.index(group._group_actions[0])
except ValueError:
continue
else:
end = start + len(group._group_actions)
if actions[start:end] == group._group_actions:
for action in group._group_actions:
group_actions.add(action)
if not group.required:
if start in inserts:
inserts[start] += ' ['
else:
inserts[start] = '['
inserts[end] = ']'
else:
if start in inserts:
inserts[start] += ' ('
else:
inserts[start] = '('
inserts[end] = ')'
for i in range(start + 1, end):
inserts[i] = '|'
# collect all actions format strings
parts = []
for i, action in enumerate(actions):
# suppressed arguments are marked with None
# remove | separators for suppressed arguments
if action.help is SUPPRESS:
parts.append(None)
if inserts.get(i) == '|':
inserts.pop(i)
elif inserts.get(i + 1) == '|':
inserts.pop(i + 1)
# produce all arg strings
elif not action.option_strings:
part = self._format_args(action, action.dest)
# if it's in a group, strip the outer []
if action in group_actions:
if part[0] == '[' and part[-1] == ']':
part = part[1:-1]
# add the action string to the list
parts.append(part)
# produce the first way to invoke the option in brackets
else:
option_string = action.option_strings[0]
# if the Optional doesn't take a value, format is:
# -s or --long
if action.nargs == 0:
part = '%s' % option_string
# if the Optional takes a value, format is:
# -s ARGS or --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
part = '%s %s' % (option_string, args_string)
# make it look optional if it's not required or in a group
if not action.required and action not in group_actions:
part = '[%s]' % part
# add the action string to the list
parts.append(part)
# insert things at the necessary indices
for i in sorted(inserts, reverse=True):
parts[i:i] = [inserts[i]]
# join all the action items with spaces
text = ' '.join([item for item in parts if item is not None])
# clean up separators for mutually exclusive groups
open = r'[\[(]'
close = r'[\])]'
text = _re.sub(r'(%s) ' % open, r'\1', text)
text = _re.sub(r' (%s)' % close, r'\1', text)
text = _re.sub(r'%s *%s' % (open, close), r'', text)
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
text = text.strip()
# return the text
return text
def _format_text(self, text):
if '%(prog)' in text:
text = text % dict(prog=self._prog)
text_width = self._width - self._current_indent
indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n'
def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = self._width - help_position
action_width = help_position - self._current_indent - 2
action_header = self._format_action_invocation(action)
# ho nelp; start on same line and add a final newline
if not action.help:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
tup = self._current_indent, '', action_width, action_header
action_header = '%*s%-*s ' % tup
indent_first = 0
# long action name; start on the next line
else:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
indent_first = help_position
# collect the pieces of the action help
parts = [action_header]
# if there was help for the action, add lines of help text
if action.help:
help_text = self._expand_help(action)
help_lines = self._split_lines(help_text, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
# or add a newline if the description doesn't end with one
elif not action_header.endswith('\n'):
parts.append('\n')
# if there are any sub-actions, add their help as well
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
# return a single string
return self._join_parts(parts)
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (option_string, args_string))
return ', '.join(parts)
def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is None:
result = '%s' % get_metavar(1)
elif action.nargs == OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs == ZERO_OR_MORE:
result = '[%s [%s ...]]' % get_metavar(2)
elif action.nargs == ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
elif action.nargs == REMAINDER:
result = '...'
elif action.nargs == PARSER:
result = '%s ...' % get_metavar(1)
else:
formats = ['%s' for _ in range(action.nargs)]
result = ' '.join(formats) % get_metavar(action.nargs)
return result
def _expand_help(self, action):
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], '__name__'):
params[name] = params[name].__name__
if params.get('choices') is not None:
choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str
return self._get_help_string(action) % params
def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
for subaction in get_subactions():
yield subaction
self._dedent()
def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.wrap(text, width)
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.fill(text, width, initial_indent=indent,
subsequent_indent=indent)
def _get_help_string(self, action):
return action.help
class RawDescriptionHelpFormatter(HelpFormatter):
"""Help message formatter which retains any formatting in descriptions.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _fill_text(self, text, width, indent):
return ''.join([indent + line for line in text.splitlines(True)])
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
"""Help message formatter which retains formatting of all help text.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _split_lines(self, text, width):
return text.splitlines()
class ArgumentDefaultsHelpFormatter(HelpFormatter):
"""Help message formatter which adds default values to argument help.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _get_help_string(self, action):
help = action.help
if '%(default)' not in action.help:
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
return help
# =====================
# Options and Arguments
# =====================
def _get_action_name(argument):
if argument is None:
return None
elif argument.option_strings:
return '/'.join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS):
return argument.metavar
elif argument.dest not in (None, SUPPRESS):
return argument.dest
else:
return None
class ArgumentError(Exception):
"""An error from creating or using an argument (optional or positional).
The string value of this exception is the message, augmented with
information about the argument that caused it.
"""
def __init__(self, argument, message):
self.argument_name = _get_action_name(argument)
self.message = message
def __str__(self):
if self.argument_name is None:
format = '%(message)s'
else:
format = 'argument %(argument_name)s: %(message)s'
return format % dict(message=self.message,
argument_name=self.argument_name)
class ArgumentTypeError(Exception):
"""An error from trying to convert a command line string to a type."""
pass
# ==============
# Action classes
# ==============
class Action(_AttributeHolder):
"""Information about how to convert command line strings to Python objects.
Action objects are used by an ArgumentParser to represent the information
needed to parse a single argument from one or more strings from the
command line. The keyword arguments to the Action constructor are also
all attributes of Action instances.
Keyword Arguments:
- option_strings -- A list of command-line option strings which
should be associated with this action.
- dest -- The name of the attribute to hold the created object(s)
- nargs -- The number of command-line arguments that should be
consumed. By default, one argument will be consumed and a single
value will be produced. Other values include:
- N (an integer) consumes N arguments (and produces a list)
- '?' consumes zero or one arguments
- '*' consumes zero or more arguments (and produces a list)
- '+' consumes one or more arguments (and produces a list)
Note that the difference between the default and nargs=1 is that
with the default, a single value will be produced, while with
nargs=1, a list containing a single value will be produced.
- const -- The value to be produced if the option is specified and the
option uses an action that takes no values.
- default -- The value to be produced if the option is not specified.
- type -- The type which the command-line arguments should be converted
to, should be one of 'string', 'int', 'float', 'complex' or a
callable object that accepts a single string argument. If None,
'string' is assumed.
- choices -- A container of values that should be allowed. If not None,
after a command-line argument has been converted to the appropriate
type, an exception will be raised if it is not a member of this
collection.
- required -- True if the action must always be specified at the
command line. This is only meaningful for optional command-line
arguments.
- help -- The help string describing the argument.
- metavar -- The name to be used for the option's argument with the
help string. If None, the 'dest' value will be used as the name.
"""
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
self.option_strings = option_strings
self.dest = dest
self.nargs = nargs
self.const = const
self.default = default
self.type = type
self.choices = choices
self.required = required
self.help = help
self.metavar = metavar
def _get_kwargs(self):
names = [
'option_strings',
'dest',
'nargs',
'const',
'default',
'type',
'choices',
'help',
'metavar',
]
return [(name, getattr(self, name)) for name in names]
def __call__(self, parser, namespace, values, option_string=None):
raise NotImplementedError(_('.__call__() not defined'))
class _StoreAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for store actions must be > 0; if you '
'have nothing to store, actions such as store '
'true or store const may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_StoreAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
class _StoreConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_StoreConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, self.const)
class _StoreTrueAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=False,
required=False,
help=None):
super(_StoreTrueAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=True,
default=default,
required=required,
help=help)
class _StoreFalseAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=True,
required=False,
help=None):
super(_StoreFalseAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=False,
default=default,
required=required,
help=help)
class _AppendAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for append actions must be > 0; if arg '
'strings are not supplying the value to append, '
'the append const action may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_AppendAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(values)
setattr(namespace, self.dest, items)
class _AppendConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_AppendConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(self.const)
setattr(namespace, self.dest, items)
class _CountAction(Action):
def __init__(self,
option_strings,
dest,
default=None,
required=False,
help=None):
super(_CountAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
new_count = _ensure_value(namespace, self.dest, 0) + 1
setattr(namespace, self.dest, new_count)
class _HelpAction(Action):
def __init__(self,
option_strings,
dest=SUPPRESS,
default=SUPPRESS,
help=None):
super(_HelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
parser.exit()
class _VersionAction(Action):
def __init__(self,
option_strings,
version=None,
dest=SUPPRESS,
default=SUPPRESS,
help="show program's version number and exit"):
super(_VersionAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
self.version = version
def __call__(self, parser, namespace, values, option_string=None):
version = self.version
if version is None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser.exit(message=formatter.format_help())
class _SubParsersAction(Action):
class _ChoicesPseudoAction(Action):
def __init__(self, name, help):
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sup.__init__(option_strings=[], dest=name, help=help)
def __init__(self,
option_strings,
prog,
parser_class,
dest=SUPPRESS,
help=None,
metavar=None):
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = {}
self._choices_actions = []
super(_SubParsersAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
help=help,
metavar=metavar)
def add_parser(self, name, **kwargs):
# set prog from the existing prefix
if kwargs.get('prog') is None:
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, help)
self._choices_actions.append(choice_action)
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
self._name_parser_map[name] = parser
return parser
def _get_subactions(self):
return self._choices_actions
def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
except KeyError:
tup = parser_name, ', '.join(self._name_parser_map)
msg = _('unknown parser %r (choices: %s)' % tup)
raise ArgumentError(self, msg)
# parse all the remaining options into the namespace
# store any unrecognized options on the object, so that the top
# level parser can decide what to do with them
namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
# ==============
# Type classes
# ==============
class FileType(object):
"""Factory for creating file object types
Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function.
"""
def __init__(self, mode='r', bufsize=None):
self._mode = mode
self._bufsize = bufsize
def __call__(self, string):
# the special argument "-" means sys.std{in,out}
if string == '-':
if 'r' in self._mode:
return _sys.stdin
elif 'w' in self._mode:
return _sys.stdout
else:
msg = _('argument "-" with mode %r' % self._mode)
raise ValueError(msg)
# all other arguments are used as file names
if self._bufsize:
return open(string, self._mode, self._bufsize)
else:
return open(string, self._mode)
def __repr__(self):
args = [self._mode, self._bufsize]
args_str = ', '.join([repr(arg) for arg in args if arg is not None])
return '%s(%s)' % (type(self).__name__, args_str)
# ===========================
# Optional and Positional Parsing
# ===========================
class Namespace(_AttributeHolder):
"""Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple
string representation.
"""
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
__hash__ = None
def __eq__(self, other):
return vars(self) == vars(other)
def __ne__(self, other):
return not (self == other)
def __contains__(self, key):
return key in self.__dict__
class _ActionsContainer(object):
def __init__(self,
description,
prefix_chars,
argument_default,
conflict_handler):
super(_ActionsContainer, self).__init__()
self.description = description
self.argument_default = argument_default
self.prefix_chars = prefix_chars
self.conflict_handler = conflict_handler
# set up registries
self._registries = {}
# register actions
self.register('action', None, _StoreAction)
self.register('action', 'store', _StoreAction)
self.register('action', 'store_const', _StoreConstAction)
self.register('action', 'store_true', _StoreTrueAction)
self.register('action', 'store_false', _StoreFalseAction)
self.register('action', 'append', _AppendAction)
self.register('action', 'append_const', _AppendConstAction)
self.register('action', 'count', _CountAction)
self.register('action', 'help', _HelpAction)
self.register('action', 'version', _VersionAction)
self.register('action', 'parsers', _SubParsersAction)
# raise an exception if the conflict handler is invalid
self._get_handler()
# action storage
self._actions = []
self._option_string_actions = {}
# groups
self._action_groups = []
self._mutually_exclusive_groups = []
# defaults storage
self._defaults = {}
# determines whether an "option" looks like a negative number
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
# whether or not there are any optionals that look like negative
# numbers -- uses a list so it can be shared and edited
self._has_negative_number_optionals = []
# ====================
# Registration methods
# ====================
def register(self, registry_name, value, object):
registry = self._registries.setdefault(registry_name, {})
registry[value] = object
def _registry_get(self, registry_name, value, default=None):
return self._registries[registry_name].get(value, default)
# ==================================
# Namespace default accessor methods
# ==================================
def set_defaults(self, **kwargs):
self._defaults.update(kwargs)
# if these defaults match any existing arguments, replace
# the previous default on the object with the new one
for action in self._actions:
if action.dest in kwargs:
action.default = kwargs[action.dest]
def get_default(self, dest):
for action in self._actions:
if action.dest == dest and action.default is not None:
return action.default
return self._defaults.get(dest, None)
# =======================
# Adding argument actions
# =======================
def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, parse a positional
# argument
chars = self.prefix_chars
if not args or len(args) == 1 and args[0][0] not in chars:
if args and 'dest' in kwargs:
raise ValueError('dest supplied twice for positional argument')
kwargs = self._get_positional_kwargs(*args, **kwargs)
# otherwise, we're adding an optional argument
else:
kwargs = self._get_optional_kwargs(*args, **kwargs)
# if no default was supplied, use the parser-level default
if 'default' not in kwargs:
dest = kwargs['dest']
if dest in self._defaults:
kwargs['default'] = self._defaults[dest]
elif self.argument_default is not None:
kwargs['default'] = self.argument_default
# create the action object, and add it to the parser
action_class = self._pop_action_class(kwargs)
if not _callable(action_class):
raise ValueError('unknown action "%s"' % action_class)
action = action_class(**kwargs)
# raise an error if the action type is not callable
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
raise ValueError('%r is not callable' % type_func)
return self._add_action(action)
def add_argument_group(self, *args, **kwargs):
group = _ArgumentGroup(self, *args, **kwargs)
self._action_groups.append(group)
return group
def add_mutually_exclusive_group(self, **kwargs):
group = _MutuallyExclusiveGroup(self, **kwargs)
self._mutually_exclusive_groups.append(group)
return group
def _add_action(self, action):
# resolve any conflicts
self._check_conflict(action)
# add to actions list
self._actions.append(action)
action.container = self
# index the action by any option strings it has
for option_string in action.option_strings:
self._option_string_actions[option_string] = action
# set the flag if any option strings look like negative numbers
for option_string in action.option_strings:
if self._negative_number_matcher.match(option_string):
if not self._has_negative_number_optionals:
self._has_negative_number_optionals.append(True)
# return the created action
return action
def _remove_action(self, action):
self._actions.remove(action)
def _add_container_actions(self, container):
# collect groups by titles
title_group_map = {}
for group in self._action_groups:
if group.title in title_group_map:
msg = _('cannot merge actions - two groups are named %r')
raise ValueError(msg % (group.title))
title_group_map[group.title] = group
# map each action to its group
group_map = {}
for group in container._action_groups:
# if a group with the title exists, use that, otherwise
# create a new group matching the container's group
if group.title not in title_group_map:
title_group_map[group.title] = self.add_argument_group(
title=group.title,
description=group.description,
conflict_handler=group.conflict_handler)
# map the actions to their new group
for action in group._group_actions:
group_map[action] = title_group_map[group.title]
# add container's mutually exclusive groups
# NOTE: if add_mutually_exclusive_group ever gains title= and
# description= then this code will need to be expanded as above
for group in container._mutually_exclusive_groups:
mutex_group = self.add_mutually_exclusive_group(
required=group.required)
# map the actions to their new mutex group
for action in group._group_actions:
group_map[action] = mutex_group
# add all actions to this container or their group
for action in container._actions:
group_map.get(action, self)._add_action(action)
def _get_positional_kwargs(self, dest, **kwargs):
# make sure required is not specified
if 'required' in kwargs:
msg = _("'required' is an invalid argument for positionals")
raise TypeError(msg)
# mark positional arguments as required if at least one is
# always required
if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
kwargs['required'] = True
if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
kwargs['required'] = True
# return the keyword arguments with no option strings
return dict(kwargs, dest=dest, option_strings=[])
def _get_optional_kwargs(self, *args, **kwargs):
# determine short and long option strings
option_strings = []
long_option_strings = []
for option_string in args:
# error on strings that don't start with an appropriate prefix
if not option_string[0] in self.prefix_chars:
msg = _('invalid option string %r: '
'must start with a character %r')
tup = option_string, self.prefix_chars
raise ValueError(msg % tup)
# strings starting with two prefix characters are long options
option_strings.append(option_string)
if option_string[0] in self.prefix_chars:
if len(option_string) > 1:
if option_string[1] in self.prefix_chars:
long_option_strings.append(option_string)
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
dest = kwargs.pop('dest', None)
if dest is None:
if long_option_strings:
dest_option_string = long_option_strings[0]
else:
dest_option_string = option_strings[0]
dest = dest_option_string.lstrip(self.prefix_chars)
if not dest:
msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string)
dest = dest.replace('-', '_')
# return the updated keyword arguments
return dict(kwargs, dest=dest, option_strings=option_strings)
def _pop_action_class(self, kwargs, default=None):
action = kwargs.pop('action', default)
return self._registry_get('action', action, action)
def _get_handler(self):
# determine function from conflict handler string
handler_func_name = '_handle_conflict_%s' % self.conflict_handler
try:
return getattr(self, handler_func_name)
except AttributeError:
msg = _('invalid conflict_resolution value: %r')
raise ValueError(msg % self.conflict_handler)
def _check_conflict(self, action):
# find all options that conflict with this option
confl_optionals = []
for option_string in action.option_strings:
if option_string in self._option_string_actions:
confl_optional = self._option_string_actions[option_string]
confl_optionals.append((option_string, confl_optional))
# resolve any conflicts
if confl_optionals:
conflict_handler = self._get_handler()
conflict_handler(action, confl_optionals)
def _handle_conflict_error(self, action, conflicting_actions):
message = _('conflicting option string(s): %s')
conflict_string = ', '.join([option_string
for option_string, action
in conflicting_actions])
raise ArgumentError(action, message % conflict_string)
def _handle_conflict_resolve(self, action, conflicting_actions):
# remove all conflicting options
for option_string, action in conflicting_actions:
# remove the conflicting option
action.option_strings.remove(option_string)
self._option_string_actions.pop(option_string, None)
# if the option now has no option string, remove it from the
# container holding it
if not action.option_strings:
action.container._remove_action(action)
class _ArgumentGroup(_ActionsContainer):
def __init__(self, container, title=None, description=None, **kwargs):
# add any missing keyword arguments by checking the container
update = kwargs.setdefault
update('conflict_handler', container.conflict_handler)
update('prefix_chars', container.prefix_chars)
update('argument_default', container.argument_default)
super_init = super(_ArgumentGroup, self).__init__
super_init(description=description, **kwargs)
# group attributes
self.title = title
self._group_actions = []
# share most attributes with the container
self._registries = container._registries
self._actions = container._actions
self._option_string_actions = container._option_string_actions
self._defaults = container._defaults
self._has_negative_number_optionals = \
container._has_negative_number_optionals
def _add_action(self, action):
action = super(_ArgumentGroup, self)._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action)
class _MutuallyExclusiveGroup(_ArgumentGroup):
def __init__(self, container, required=False):
super(_MutuallyExclusiveGroup, self).__init__(container)
self.required = required
self._container = container
def _add_action(self, action):
if action.required:
msg = _('mutually exclusive arguments must be optional')
raise ValueError(msg)
action = self._container._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
self._container._remove_action(action)
self._group_actions.remove(action)
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
version=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True):
if version is not None:
import warnings
warnings.warn(
"""The "version" argument to ArgumentParser is deprecated. """
"""Please use """
""""add_argument(..., action='version', version="N", ...)" """
"""instead""", DeprecationWarning)
superinit = super(ArgumentParser, self).__init__
superinit(description=description,
prefix_chars=prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler)
# default setting for prog
if prog is None:
prog = _os.path.basename(_sys.argv[0])
self.prog = prog
self.usage = usage
self.epilog = epilog
self.version = version
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('optional arguments'))
self._subparsers = None
# register types
def identity(string):
return string
self.register('type', None, identity)
# add help and version arguments if necessary
# (using explicit default to override global argument_default)
if '-' in prefix_chars:
default_prefix = '-'
else:
default_prefix = prefix_chars[0]
if self.add_help:
self.add_argument(
default_prefix+'h', default_prefix*2+'help',
action='help', default=SUPPRESS,
help=_('show this help message and exit'))
if self.version:
self.add_argument(
default_prefix+'v', default_prefix*2+'version',
action='version', default=SUPPRESS,
version=self.version,
help=_("show program's version number and exit"))
# add parent arguments and defaults
for parent in parents:
self._add_container_actions(parent)
try:
defaults = parent._defaults
except AttributeError:
pass
else:
self._defaults.update(defaults)
# =======================
# Pretty __repr__ methods
# =======================
def _get_kwargs(self):
names = [
'prog',
'usage',
'description',
'version',
'formatter_class',
'conflict_handler',
'add_help',
]
return [(name, getattr(self, name)) for name in names]
# ==================================
# Optional/Positional adding methods
# ==================================
def add_subparsers(self, **kwargs):
if self._subparsers is not None:
self.error(_('cannot have multiple subparser arguments'))
# add the parser class to the arguments if it's not present
kwargs.setdefault('parser_class', type(self))
if 'title' in kwargs or 'description' in kwargs:
title = _(kwargs.pop('title', 'subcommands'))
description = _(kwargs.pop('description', None))
self._subparsers = self.add_argument_group(title, description)
else:
self._subparsers = self._positionals
# prog defaults to the usage message of this parser, skipping
# optional arguments and with no "usage:" prefix
if kwargs.get('prog') is None:
formatter = self._get_formatter()
positionals = self._get_positional_actions()
groups = self._mutually_exclusive_groups
formatter.add_usage(self.usage, positionals, groups, '')
kwargs['prog'] = formatter.format_help().strip()
# create the parsers action and add it to the positionals list
parsers_class = self._pop_action_class(kwargs, 'parsers')
action = parsers_class(option_strings=[], **kwargs)
self._subparsers._add_action(action)
# return the created parsers action
return action
def _add_action(self, action):
if action.option_strings:
self._optionals._add_action(action)
else:
self._positionals._add_action(action)
return action
def _get_optional_actions(self):
return [action
for action in self._actions
if action.option_strings]
def _get_positional_actions(self):
return [action
for action in self._actions
if not action.option_strings]
# =====================================
# Command line argument parsing methods
# =====================================
def parse_args(self, args=None, namespace=None):
args, argv = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_args(self, args=None, namespace=None):
# args default to the system args
if args is None:
args = _sys.argv[1:]
# default Namespace built from parser defaults
if namespace is None:
namespace = Namespace()
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
default = action.default
if isinstance(action.default, basestring):
default = self._get_value(action, default)
setattr(namespace, action.dest, default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
try:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
def _parse_known_args(self, arg_strings, namespace):
# replace arg strings that are file references
if self.fromfile_prefix_chars is not None:
arg_strings = self._read_args_from_files(arg_strings)
# map all mutually exclusive arguments to the other arguments
# they can't occur with
action_conflicts = {}
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern
# which has an 'O' if there is an option at an index,
# an 'A' if there is an argument, or a '-' if there is a '--'
option_string_indices = {}
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
# all args after -- are non-options
if arg_string == '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
# otherwise, add the arg to the arg strings
# and note the index if it was an option
else:
option_tuple = self._parse_optional(arg_string)
if option_tuple is None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
# join the pieces together to form the pattern
arg_strings_pattern = ''.join(arg_string_pattern_parts)
# converts arg strings to the appropriate and then takes the action
seen_actions = set()
seen_non_default_actions = set()
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen arguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
# take the action if we didn't receive a SUPPRESS value
# (e.g. from a default)
if argument_values is not SUPPRESS:
action(self, namespace, argument_values, option_string)
# function to convert arg_strings into an optional action
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
action, option_string, explicit_arg = option_tuple
# identify additional optionals in the same arg string
# (e.g. -xyz is the same as -x -y -z if no args are required)
match_argument = self._match_argument
action_tuples = []
while True:
# if we found no optional action, skip it
if action is None:
extras.append(arg_strings[start_index])
return start_index + 1
# if there is an explicit argument, try to match the
# optional's string arguments to only this
if explicit_arg is not None:
arg_count = match_argument(action, 'A')
# if the action is a single-dash option and takes no
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
new_explicit_arg = explicit_arg[1:] or None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
explicit_arg = new_explicit_arg
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
elif arg_count == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if there is no explicit argument, try to match the
# optional's string arguments with the following strings
# if successful, exit the loop
else:
start = start_index + 1
selected_patterns = arg_strings_pattern[start:]
arg_count = match_argument(action, selected_patterns)
stop = start + arg_count
args = arg_strings[start:stop]
action_tuples.append((action, args, option_string))
break
# add the Optional to the list and return the index at which
# the Optional's string args stopped
assert action_tuples
for action, args, option_string in action_tuples:
take_action(action, args, option_string)
return stop
# the list of Positionals left to be parsed; this is modified
# by consume_positionals()
positionals = self._get_positional_actions()
# function to convert arg_strings into positional actions
def consume_positionals(start_index):
# match as many Positionals as possible
match_partial = self._match_arguments_partial
selected_pattern = arg_strings_pattern[start_index:]
arg_counts = match_partial(positionals, selected_pattern)
# slice off the appropriate arg strings for each Positional
# and add the Positional and its args to the list
for action, arg_count in zip(positionals, arg_counts):
args = arg_strings[start_index: start_index + arg_count]
start_index += arg_count
take_action(action, args)
# slice off the Positionals that we just parsed and return the
# index at which the Positionals' string args stopped
positionals[:] = positionals[len(arg_counts):]
return start_index
# consume Positionals and Optionals alternately, until we have
# passed the last option string
extras = []
start_index = 0
if option_string_indices:
max_option_string_index = max(option_string_indices)
else:
max_option_string_index = -1
while start_index <= max_option_string_index:
# consume any Positionals preceding the next option
next_option_string_index = min([
index
for index in option_string_indices
if index >= start_index])
if start_index != next_option_string_index:
positionals_end_index = consume_positionals(start_index)
# only try to parse the next optional if we didn't consume
# the option string during the positionals parsing
if positionals_end_index > start_index:
start_index = positionals_end_index
continue
else:
start_index = positionals_end_index
# if we consumed all the positionals we could and we're not
# at the index of an option string, there were extra arguments
if start_index not in option_string_indices:
strings = arg_strings[start_index:next_option_string_index]
extras.extend(strings)
start_index = next_option_string_index
# consume the next optional and any arguments for it
start_index = consume_optional(start_index)
# consume any positionals following the last Optional
stop_index = consume_positionals(start_index)
# if we didn't consume all the argument strings, there were extras
extras.extend(arg_strings[stop_index:])
# if we didn't use all the Positional objects, there were too few
# arg strings supplied.
if positionals:
self.error(_('too few arguments'))
# make sure all required actions were present
for action in self._actions:
if action.required:
if action not in seen_actions:
name = _get_action_name(action)
self.error(_('argument %s is required') % name)
# make sure all required groups had one option present
for group in self._mutually_exclusive_groups:
if group.required:
for action in group._group_actions:
if action in seen_non_default_actions:
break
# if no actions were used, report the error
else:
names = [_get_action_name(action)
for action in group._group_actions
if action.help is not SUPPRESS]
msg = _('one of the arguments %s is required')
self.error(msg % ' '.join(names))
# return the updated namespace and the extra arguments
return namespace, extras
def _read_args_from_files(self, arg_strings):
# expand arguments referencing files
new_arg_strings = []
for arg_string in arg_strings:
# for regular arguments, just add them back into the list
if arg_string[0] not in self.fromfile_prefix_chars:
new_arg_strings.append(arg_string)
# replace arguments referencing files with the file content
else:
try:
args_file = open(arg_string[1:])
try:
arg_strings = []
for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
finally:
args_file.close()
except IOError:
err = _sys.exc_info()[1]
self.error(str(err))
# return the modified argument list
return new_arg_strings
def convert_arg_line_to_args(self, arg_line):
return [arg_line]
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = _('expected %s argument(s)') % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_arguments_partial(self, actions, arg_strings_pattern):
# progressively shorten the actions list by slicing off the
# final actions until we find a match
result = []
for i in range(len(actions), 0, -1):
actions_slice = actions[:i]
pattern = ''.join([self._get_nargs_pattern(action)
for action in actions_slice])
match = _re.match(pattern, arg_strings_pattern)
if match is not None:
result.extend([len(string) for string in match.groups()])
break
# return the list of arg string counts
return result
def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
return None
# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
return None
# if the option string is present in the parser, return the action
if arg_string in self._option_string_actions:
action = self._option_string_actions[arg_string]
return action, arg_string, None
# if it's just a single character, it was meant to be positional
if len(arg_string) == 1:
return None
# if the option string before the "=" is present, return the action
if '=' in arg_string:
option_string, explicit_arg = arg_string.split('=', 1)
if option_string in self._option_string_actions:
action = self._option_string_actions[option_string]
return action, option_string, explicit_arg
# search through all possible prefixes of the option string
# and all actions in the parser for possible interpretations
option_tuples = self._get_option_tuples(arg_string)
# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
for action, option_string, explicit_arg in option_tuples])
tup = arg_string, options
self.error(_('ambiguous option: %s could match %s') % tup)
# if exactly one action matched, this segmentation is good,
# so return the parsed action
elif len(option_tuples) == 1:
option_tuple, = option_tuples
return option_tuple
# if it was not found as an option, but it looks like a negative
# number, it was meant to be positional
# unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string):
if not self._has_negative_number_optionals:
return None
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
# it was meant to be an optional but there is no such option
# in this parser (though it might be a valid option in a subparser)
return None, arg_string, None
def _get_option_tuples(self, option_string):
result = []
# option strings starting with two prefix characters are only
# split at the '='
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
if '=' in option_string:
option_prefix, explicit_arg = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
for option_string in self._option_string_actions:
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# single character options can be concatenated with their arguments
# but multiple character options always have to have their argument
# separate
elif option_string[0] in chars and option_string[1] not in chars:
option_prefix = option_string
explicit_arg = None
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
for option_string in self._option_string_actions:
if option_string == short_option_prefix:
action = self._option_string_actions[option_string]
tup = action, option_string, short_explicit_arg
result.append(tup)
elif option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# shouldn't ever get here
else:
self.error(_('unexpected option string: %s') % option_string)
# return the collected option tuples
return result
def _get_nargs_pattern(self, action):
# in all examples below, we have to allow for '--' args
# which are represented as '-' in the pattern
nargs = action.nargs
# the default (None) is assumed to be a single argument
if nargs is None:
nargs_pattern = '(-*A-*)'
# allow zero or one arguments
elif nargs == OPTIONAL:
nargs_pattern = '(-*A?-*)'
# allow zero or more arguments
elif nargs == ZERO_OR_MORE:
nargs_pattern = '(-*[A-]*)'
# allow one or more arguments
elif nargs == ONE_OR_MORE:
nargs_pattern = '(-*A[A-]*)'
# allow any number of options or arguments
elif nargs == REMAINDER:
nargs_pattern = '([-AO]*)'
# allow one argument followed by any number of options or arguments
elif nargs == PARSER:
nargs_pattern = '(-*A[-AO]*)'
# all others should be integers
else:
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
# if this is an optional action, -- is not allowed
if action.option_strings:
nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = nargs_pattern.replace('-', '')
# return the pattern
return nargs_pattern
# ========================
# Value conversion methods
# ========================
def _get_values(self, action, arg_strings):
# for everything but PARSER args, strip out '--'
if action.nargs not in [PARSER, REMAINDER]:
arg_strings = [s for s in arg_strings if s != '--']
# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
if action.option_strings:
value = action.const
else:
value = action.default
if isinstance(value, basestring):
value = self._get_value(action, value)
self._check_value(action, value)
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
# single argument or optional argument produces a single value
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
arg_string, = arg_strings
value = self._get_value(action, arg_string)
self._check_value(action, value)
# REMAINDER arguments convert all values, checking none
elif action.nargs == REMAINDER:
value = [self._get_value(action, v) for v in arg_strings]
# PARSER arguments convert all values, but check only the first
elif action.nargs == PARSER:
value = [self._get_value(action, v) for v in arg_strings]
self._check_value(action, value[0])
# all other types of nargs produce a list
else:
value = [self._get_value(action, v) for v in arg_strings]
for v in value:
self._check_value(action, v)
# return the converted value
return value
def _get_value(self, action, arg_string):
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
msg = _('%r is not callable')
raise ArgumentError(action, msg % type_func)
# convert the value to the appropriate type
try:
result = type_func(arg_string)
# ArgumentTypeErrors indicate errors
except ArgumentTypeError:
name = getattr(action.type, '__name__', repr(action.type))
msg = str(_sys.exc_info()[1])
raise ArgumentError(action, msg)
# TypeErrors or ValueErrors also indicate errors
except (TypeError, ValueError):
name = getattr(action.type, '__name__', repr(action.type))
msg = _('invalid %s value: %r')
raise ArgumentError(action, msg % (name, arg_string))
# return the converted value
return result
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
tup = value, ', '.join(map(repr, action.choices))
msg = _('invalid choice: %r (choose from %s)') % tup
raise ArgumentError(action, msg)
# =======================
# Help-formatting methods
# =======================
def format_usage(self):
formatter = self._get_formatter()
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
return formatter.format_help()
def format_help(self):
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
def format_version(self):
import warnings
warnings.warn(
'The format_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
formatter = self._get_formatter()
formatter.add_text(self.version)
return formatter.format_help()
def _get_formatter(self):
return self.formatter_class(prog=self.prog)
# =====================
# Help-printing methods
# =====================
def print_usage(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_usage(), file)
def print_help(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_help(), file)
def print_version(self, file=None):
import warnings
warnings.warn(
'The print_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
self._print_message(self.format_version(), file)
def _print_message(self, message, file=None):
if message:
if file is None:
file = _sys.stderr
file.write(message)
# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
if message:
self._print_message(message, _sys.stderr)
_sys.exit(status)
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
self.exit(2, _('%s: error: %s\n') % (self.prog, message))
| Python |
class BaseAction(object):
"""Base interface for custom actions."""
#: Reference to :class:`Manager`.
manager = None
#: Action name.
name = None
#: ArgumentParser description.
description = None
#: ArgumentParser epilog.
epilog = None
def __init__(self, manager):
raise NotImplementedError()
def __call__(self, argv):
raise NotImplementedError()
class Action(object):
def __init__(self, manager):
self.manager = manager
| Python |
# -*- coding: utf-8 -*-
"""
webapp2
=======
`webapp2`_ is a lightweight Python web framework compatible with Google App
Engine's `webapp`_.
webapp2 is `simple`_. it follows the simplicity of webapp, but
improves it in some ways: it adds better URI routing and exception handling,
a full featured response object and a more flexible dispatching mechanism.
webapp2 also offers the package `webapp2_extras`_ with several optional
utilities: sessions, localization, internationalization, domain and subdomain
routing, secure cookies and others.
webapp2 can also be used outside of Google App Engine, independently of the
App Engine SDK.
For a complete description of how webapp2 improves webapp, see
`webapp2 features`_.
Quick links
-----------
- `User Guide <http://webapp-improved.appspot.com/>`_
- `Repository <http://code.google.com/p/webapp-improved/>`_
- `Discussion Group <https://groups.google.com/forum/#!forum/webapp2>`_
- `@webapp2 <https://twitter.com/#!/webapp2>`_
.. _webapp: http://code.google.com/appengine/docs/python/tools/webapp/
.. _webapp2: http://code.google.com/p/webapp-improved/
.. _simple: http://code.google.com/p/webapp-improved/source/browse/webapp2.py
.. _webapp2_extras: http://webapp-improved.appspot.com/#api-reference-webapp2-extras
.. _webapp2 features: http://webapp-improved.appspot.com/features.html
"""
from setuptools import setup
setup(
name = 'webapp2',
version = '2.5.2',
license = 'Apache Software License',
url = 'http://webapp-improved.appspot.com',
description = "Taking Google App Engine's webapp to the next level!",
long_description = __doc__,
author = 'Rodrigo Moraes',
author_email = 'rodrigo.moraes@gmail.com',
zip_safe = False,
platforms = 'any',
py_modules = [
'webapp2',
],
packages = [
'webapp2_extras',
'webapp2_extras.appengine',
'webapp2_extras.appengine.auth',
],
include_package_data=True,
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
]
) | Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.jinja2
=====================
Jinja2 template support for webapp2.
Learn more about Jinja2: http://jinja.pocoo.org/
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import absolute_import
import jinja2
import webapp2
#: Default configuration values for this module. Keys are:
#:
#: template_path
#: Directory for templates. Default is `templates`.
#:
#: compiled_path
#: Target for compiled templates. If set, uses the loader for compiled
#: templates in production. If it ends with a '.zip' it will be treated
#: as a zip file. Default is None.
#:
#: force_compiled
#: Forces the use of compiled templates even in the development server.
#:
#: environment_args
#: Keyword arguments used to instantiate the Jinja2 environment. By
#: default autoescaping is enabled and two extensions are set:
#: ``jinja2.ext.autoescape`` and ``jinja2.ext.with_``. For production it
#: may be a good idea to set 'auto_reload' to False -- we don't need to
#: check if templates changed after deployed.
#:
#: globals
#: Extra global variables for the Jinja2 environment.
#:
#: filters
#: Extra filters for the Jinja2 environment.
default_config = {
'template_path': 'templates',
'compiled_path': None,
'force_compiled': False,
'environment_args': {
'autoescape': True,
'extensions': [
'jinja2.ext.autoescape',
'jinja2.ext.with_',
],
},
'globals': None,
'filters': None,
}
class Jinja2(object):
"""Wrapper for configurable and cached Jinja2 environment.
To used it, set it as a cached property in a base `RequestHandler`::
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
Then extended handlers can render templates directly::
class MyHandler(BaseHandler):
def get(self):
context = {'message': 'Hello, world!'}
self.render_response('my_template.html', **context)
"""
#: Configuration key.
config_key = __name__
#: Loaded configuration.
config = None
def __init__(self, app, config=None):
"""Initializes the Jinja2 object.
:param app:
A :class:`webapp2.WSGIApplication` instance.
:param config:
A dictionary of configuration values to be overridden. See
the available keys in :data:`default_config`.
"""
self.config = config = app.config.load_config(self.config_key,
default_values=default_config, user_values=config,
required_keys=None)
kwargs = config['environment_args'].copy()
enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])
if 'loader' not in kwargs:
template_path = config['template_path']
compiled_path = config['compiled_path']
use_compiled = not app.debug or config['force_compiled']
if compiled_path and use_compiled:
# Use precompiled templates loaded from a module or zip.
kwargs['loader'] = jinja2.ModuleLoader(compiled_path)
else:
# Parse templates for every new environment instances.
kwargs['loader'] = jinja2.FileSystemLoader(template_path)
# Initialize the environment.
env = jinja2.Environment(**kwargs)
if config['globals']:
env.globals.update(config['globals'])
if config['filters']:
env.filters.update(config['filters'])
if enable_i18n:
# Install i18n.
from webapp2_extras import i18n
env.install_gettext_callables(
lambda x: i18n.gettext(x),
lambda s, p, n: i18n.ngettext(s, p, n),
newstyle=True)
env.filters.update({
'format_date': i18n.format_date,
'format_time': i18n.format_time,
'format_datetime': i18n.format_datetime,
'format_timedelta': i18n.format_timedelta,
})
self.environment = env
def render_template(self, _filename, **context):
"""Renders a template and returns a response object.
:param _filename:
The template filename, related to the templates directory.
:param context:
Keyword arguments used as variables in the rendered template.
These will override values set in the request context.
:returns:
A rendered template.
"""
return self.environment.get_template(_filename).render(**context)
def get_template_attribute(self, filename, attribute):
"""Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_foo.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this::
hello = get_template_attribute('_foo.html', 'hello')
return hello('World')
This function comes from `Flask`.
:param filename:
The template filename.
:param attribute:
The name of the variable of macro to acccess.
"""
template = self.environment.get_template(filename)
return getattr(template.module, attribute)
# Factories -------------------------------------------------------------------
#: Key used to store :class:`Jinja2` in the app registry.
_registry_key = 'webapp2_extras.jinja2.Jinja2'
def get_jinja2(factory=Jinja2, key=_registry_key, app=None):
"""Returns an instance of :class:`Jinja2` from the app registry.
It'll try to get it from the current app registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`Jinja2` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param app:
A :class:`webapp2.WSGIApplication` instance used to store the instance.
The active app is used if it is not set.
"""
app = app or webapp2.get_app()
jinja2 = app.registry.get(key)
if not jinja2:
jinja2 = app.registry[key] = factory(app)
return jinja2
def set_jinja2(jinja2, key=_registry_key, app=None):
"""Sets an instance of :class:`Jinja2` in the app registry.
:param store:
An instance of :class:`Jinja2`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.WSGIApplication` instance used to retrieve the
instance. The active app is used if it is not set.
"""
app = app or webapp2.get_app()
app.registry[key] = jinja2
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.auth
===================
Utilities for authentication and authorization.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import logging
import time
import webapp2
from webapp2_extras import security
from webapp2_extras import sessions
#: Default configuration values for this module. Keys are:
#:
#: user_model
#: User model which authenticates custom users and tokens.
#: Can also be a string in dotted notation to be lazily imported.
#: Default is :class:`webapp2_extras.appengine.auth.models.User`.
#:
#: session_backend
#: Name of the session backend to be used. Default is `securecookie`.
#:
#: cookie_name
#: Name of the cookie to save the auth session. Default is `auth`.
#:
#: token_max_age
#: Number of seconds of inactivity after which an auth token is
#: invalidated. The same value is used to set the ``max_age`` for
#: persistent auth sessions. Default is 86400 * 7 * 3 (3 weeks).
#:
#: token_new_age
#: Number of seconds after which a new token is created and written to
#: the database, and the old one is invalidated.
#: Use this to limit database writes; set to None to write on all requests.
#: Default is 86400 (1 day).
#:
#: token_cache_age
#: Number of seconds after which a token must be checked in the database.
#: Use this to limit database reads; set to None to read on all requests.
#: Default is 3600 (1 hour).
#:
#: user_attributes
#: A list of extra user attributes to be stored in the session.
# The user object must provide all of them as attributes.
#: Default is an empty list.
default_config = {
'user_model': 'webapp2_extras.appengine.auth.models.User',
'session_backend': 'securecookie',
'cookie_name': 'auth',
'token_max_age': 86400 * 7 * 3,
'token_new_age': 86400,
'token_cache_age': 3600,
'user_attributes': [],
}
#: Internal flag for anonymous users.
_anon = object()
class AuthError(Exception):
"""Base auth exception."""
class InvalidAuthIdError(AuthError):
"""Raised when a user can't be fetched given an auth_id."""
class InvalidPasswordError(AuthError):
"""Raised when a user password doesn't match."""
class AuthStore(object):
"""Provides common utilities and configuration for :class:`Auth`."""
#: Configuration key.
config_key = __name__
#: Required attributes stored in a session.
_session_attributes = ['user_id', 'remember',
'token', 'token_ts', 'cache_ts']
def __init__(self, app, config=None):
"""Initializes the session store.
:param app:
A :class:`webapp2.WSGIApplication` instance.
:param config:
A dictionary of configuration values to be overridden. See
the available keys in :data:`default_config`.
"""
self.app = app
# Base configuration.
self.config = app.config.load_config(self.config_key,
default_values=default_config, user_values=config)
# User data we're interested in -------------------------------------------
@webapp2.cached_property
def session_attributes(self):
"""The list of attributes stored in a session.
This must be an ordered list of unique elements.
"""
seen = set()
attrs = self._session_attributes + self.user_attributes
return [a for a in attrs if a not in seen and not seen.add(a)]
@webapp2.cached_property
def user_attributes(self):
"""The list of attributes retrieved from the user model.
This must be an ordered list of unique elements.
"""
seen = set()
attrs = self.config['user_attributes']
return [a for a in attrs if a not in seen and not seen.add(a)]
# User model related ------------------------------------------------------
@webapp2.cached_property
def user_model(self):
"""Configured user model."""
cls = self.config['user_model']
if isinstance(cls, basestring):
cls = self.config['user_model'] = webapp2.import_string(cls)
return cls
def get_user_by_auth_password(self, auth_id, password, silent=False):
"""Returns a user dict based on auth_id and password.
:param auth_id:
Authentication id.
:param password:
User password.
:param silent:
If True, raises an exception if auth_id or password are invalid.
:returns:
A dictionary with user data.
:raises:
``InvalidAuthIdError`` or ``InvalidPasswordError``.
"""
try:
user = self.user_model.get_by_auth_password(auth_id, password)
return self.user_to_dict(user)
except (InvalidAuthIdError, InvalidPasswordError):
if not silent:
raise
return None
def get_user_by_auth_token(self, user_id, token):
"""Returns a user dict based on user_id and auth token.
:param user_id:
User id.
:param token:
Authentication token.
:returns:
A tuple ``(user_dict, token_timestamp)``. Both values can be None.
The token timestamp will be None if the user is invalid or it
is valid but the token requires renewal.
"""
user, ts = self.user_model.get_by_auth_token(user_id, token)
return self.user_to_dict(user), ts
def create_auth_token(self, user_id):
"""Creates a new authentication token.
:param user_id:
Authentication id.
:returns:
A new authentication token.
"""
return self.user_model.create_auth_token(user_id)
def delete_auth_token(self, user_id, token):
"""Deletes an authentication token.
:param user_id:
User id.
:param token:
Authentication token.
"""
return self.user_model.delete_auth_token(user_id, token)
def user_to_dict(self, user):
"""Returns a dictionary based on a user object.
Extra attributes to be retrieved must be set in this module's
configuration.
:param user:
User object: an instance the custom user model.
:returns:
A dictionary with user data.
"""
if not user:
return None
user_dict = dict((a, getattr(user, a)) for a in self.user_attributes)
user_dict['user_id'] = user.get_id()
return user_dict
# Session related ---------------------------------------------------------
def get_session(self, request):
"""Returns an auth session.
:param request:
A :class:`webapp2.Request` instance.
:returns:
A session dict.
"""
store = sessions.get_store(request=request)
return store.get_session(self.config['cookie_name'],
backend=self.config['session_backend'])
def serialize_session(self, data):
"""Serializes values for a session.
:param data:
A dict with session data.
:returns:
A list with session data.
"""
try:
assert len(data) >= len(self.session_attributes)
return [data.get(k) for k in self.session_attributes]
except AssertionError:
logging.warning(
'Invalid user data: %r. Expected attributes: %r.' %
(data, self.session_attributes))
return None
def deserialize_session(self, data):
"""Deserializes values for a session.
:param data:
A list with session data.
:returns:
A dict with session data.
"""
try:
assert len(data) >= len(self.session_attributes)
return dict(zip(self.session_attributes, data))
except AssertionError:
logging.warning(
'Invalid user data: %r. Expected attributes: %r.' %
(data, self.session_attributes))
return None
# Validators --------------------------------------------------------------
def validate_password(self, auth_id, password, silent=False):
"""Validates a password.
Passwords are used to log-in using forms or to request auth tokens
from services.
:param auth_id:
Authentication id.
:param password:
Password to be checked.
:param silent:
If True, raises an exception if auth_id or password are invalid.
:returns:
user or None
:raises:
``InvalidAuthIdError`` or ``InvalidPasswordError``.
"""
return self.get_user_by_auth_password(auth_id, password, silent=silent)
def validate_token(self, user_id, token, token_ts=None):
"""Validates a token.
Tokens are random strings used to authenticate temporarily. They are
used to validate sessions or service requests.
:param user_id:
User id.
:param token:
Token to be checked.
:param token_ts:
Optional token timestamp used to pre-validate the token age.
:returns:
A tuple ``(user_dict, token)``.
"""
now = int(time.time())
delete = token_ts and ((now - token_ts) > self.config['token_max_age'])
create = False
if not delete:
# Try to fetch the user.
user, ts = self.get_user_by_auth_token(user_id, token)
if user:
# Now validate the real timestamp.
delete = (now - ts) > self.config['token_max_age']
create = (now - ts) > self.config['token_new_age']
if delete or create or not user:
if delete or create:
# Delete token from db.
self.delete_auth_token(user_id, token)
if delete:
user = None
token = None
return user, token
def validate_cache_timestamp(self, cache_ts, token_ts=None):
"""Validates a cache timestamp.
:param cache_ts:
Token timestamp to validate the cache age.
:param token_ts:
Token timestamp to validate the token age.
:returns:
True if it is valid, False otherwise.
"""
now = int(time.time())
valid = (now - cache_ts) < self.config['token_cache_age']
if valid and token_ts:
valid2 = (now - token_ts) < self.config['token_max_age']
valid3 = (now - token_ts) < self.config['token_new_age']
valid = valid2 and valid3
return valid
class Auth(object):
"""Authentication provider for a single request."""
#: A :class:`webapp2.Request` instance.
request = None
#: An :class:`AuthStore` instance.
store = None
#: Cached user for the request.
_user = None
def __init__(self, request):
"""Initializes the auth provider for a request.
:param request:
A :class:`webapp2.Request` instance.
"""
self.request = request
self.store = get_store(app=request.app)
# Retrieving a user -------------------------------------------------------
def _user_or_none(self):
return self._user if self._user is not _anon else None
def get_user_by_session(self, save_session=True):
"""Returns a user based on the current session.
:param save_session:
If True, saves the user in the session if authentication succeeds.
:returns:
A user dict or None.
"""
if self._user is None:
data = self.get_session_data(pop=True)
if not data:
self._user = _anon
else:
self._user = self.get_user_by_token(
user_id=data['user_id'], token=data['token'],
token_ts=data['token_ts'], cache=data,
cache_ts=data['cache_ts'], remember=data['remember'],
save_session=save_session)
return self._user_or_none()
def get_user_by_token(self, user_id, token, token_ts=None, cache=None,
cache_ts=None, remember=False, save_session=True):
"""Returns a user based on an authentication token.
:param user_id:
User id.
:param token:
Authentication token.
:param token_ts:
Token timestamp, used to perform pre-validation.
:param cache:
Cached user data (from the session).
:param cache_ts:
Cache timestamp.
:param remember:
If True, saves permanent sessions.
:param save_session:
If True, saves the user in the session if authentication succeeds.
:returns:
A user dict or None.
"""
if self._user is not None:
assert (self._user is not _anon and
self._user['user_id'] == user_id and
self._user['token'] == token)
return self._user_or_none()
if cache and cache_ts:
valid = self.store.validate_cache_timestamp(cache_ts, token_ts)
if valid:
self._user = cache
else:
cache_ts = None
if self._user is None:
# Fetch and validate the token.
self._user, token = self.store.validate_token(user_id, token,
token_ts=token_ts)
if self._user is None:
self._user = _anon
elif save_session:
if not token:
token_ts = None
self.set_session(self._user, token=token, token_ts=token_ts,
cache_ts=cache_ts, remember=remember)
return self._user_or_none()
def get_user_by_password(self, auth_id, password, remember=False,
save_session=True, silent=False):
"""Returns a user based on password credentials.
:param auth_id:
Authentication id.
:param password:
User password.
:param remember:
If True, saves permanent sessions.
:param save_session:
If True, saves the user in the session if authentication succeeds.
:param silent:
If True, raises an exception if auth_id or password are invalid.
:returns:
A user dict or None.
:raises:
``InvalidAuthIdError`` or ``InvalidPasswordError``.
"""
if save_session:
# During a login attempt, invalidate current session.
self.unset_session()
self._user = self.store.validate_password(auth_id, password,
silent=silent)
if not self._user:
self._user = _anon
elif save_session:
# This always creates a new token with new timestamp.
self.set_session(self._user, remember=remember)
return self._user_or_none()
# Storing and removing user from session ----------------------------------
@webapp2.cached_property
def session(self):
"""Auth session."""
return self.store.get_session(self.request)
def set_session(self, user, token=None, token_ts=None, cache_ts=None,
remember=False, **session_args):
"""Saves a user in the session.
:param user:
A dictionary with user data.
:param token:
A unique token to be persisted. If None, a new one is created.
:param token_ts:
Token timestamp. If None, a new one is created.
:param cache_ts:
Token cache timestamp. If None, a new one is created.
:remember:
If True, session is set to be persisted.
:param session_args:
Keyword arguments to set the session arguments.
"""
now = int(time.time())
token = token or self.store.create_auth_token(user['user_id'])
token_ts = token_ts or now
cache_ts = cache_ts or now
if remember:
max_age = self.store.config['token_max_age']
else:
max_age = None
session_args.setdefault('max_age', max_age)
# Create a new dict or just update user?
# We are doing the latter, and so the user dict will always have
# the session metadata (token, timestamps etc). This is easier to test.
# But we could store only user_id and custom user attributes instead.
user.update({
'token': token,
'token_ts': token_ts,
'cache_ts': cache_ts,
'remember': int(remember),
})
self.set_session_data(user, **session_args)
self._user = user
def unset_session(self):
"""Removes a user from the session and invalidates the auth token."""
self._user = None
data = self.get_session_data(pop=True)
if data:
# Invalidate current token.
self.store.delete_auth_token(data['user_id'], data['token'])
def get_session_data(self, pop=False):
"""Returns the session data as a dictionary.
:param pop:
If True, removes the session.
:returns:
A deserialized session, or None.
"""
func = self.session.pop if pop else self.session.get
rv = func('_user', None)
if rv is not None:
data = self.store.deserialize_session(rv)
if data:
return data
elif not pop:
self.session.pop('_user', None)
return None
def set_session_data(self, data, **session_args):
"""Sets the session data as a list.
:param data:
Deserialized session data.
:param session_args:
Extra arguments for the session.
"""
data = self.store.serialize_session(data)
if data is not None:
self.session['_user'] = data
self.session.container.session_args.update(session_args)
# Factories -------------------------------------------------------------------
#: Key used to store :class:`AuthStore` in the app registry.
_store_registry_key = 'webapp2_extras.auth.Auth'
#: Key used to store :class:`Auth` in the request registry.
_auth_registry_key = 'webapp2_extras.auth.Auth'
def get_store(factory=AuthStore, key=_store_registry_key, app=None):
"""Returns an instance of :class:`AuthStore` from the app registry.
It'll try to get it from the current app registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`AuthStore` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param app:
A :class:`webapp2.WSGIApplication` instance used to store the instance.
The active app is used if it is not set.
"""
app = app or webapp2.get_app()
store = app.registry.get(key)
if not store:
store = app.registry[key] = factory(app)
return store
def set_store(store, key=_store_registry_key, app=None):
"""Sets an instance of :class:`AuthStore` in the app registry.
:param store:
An instance of :class:`AuthStore`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.WSGIApplication` instance used to retrieve the
instance. The active app is used if it is not set.
"""
app = app or webapp2.get_app()
app.registry[key] = store
def get_auth(factory=Auth, key=_auth_registry_key, request=None):
"""Returns an instance of :class:`Auth` from the request registry.
It'll try to get it from the current request registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`Auth` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param request:
A :class:`webapp2.Request` instance used to store the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
auth = request.registry.get(key)
if not auth:
auth = request.registry[key] = factory(request)
return auth
def set_auth(auth, key=_auth_registry_key, request=None):
"""Sets an instance of :class:`Auth` in the request registry.
:param auth:
An instance of :class:`Auth`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.Request` instance used to retrieve the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
request.registry[key] = auth
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.appengine.auth.models
====================================
Auth related models.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import time
try:
from ndb import model
except ImportError: # pragma: no cover
from google.appengine.ext.ndb import model
from webapp2_extras import auth
from webapp2_extras import security
class Unique(model.Model):
"""A model to store unique values.
The only purpose of this model is to "reserve" values that must be unique
within a given scope, as a workaround because datastore doesn't support
the concept of uniqueness for entity properties.
For example, suppose we have a model `User` with three properties that
must be unique across a given group: `username`, `auth_id` and `email`::
class User(model.Model):
username = model.StringProperty(required=True)
auth_id = model.StringProperty(required=True)
email = model.StringProperty(required=True)
To ensure property uniqueness when creating a new `User`, we first create
`Unique` records for those properties, and if everything goes well we can
save the new `User` record::
@classmethod
def create_user(cls, username, auth_id, email):
# Assemble the unique values for a given class and attribute scope.
uniques = [
'User.username.%s' % username,
'User.auth_id.%s' % auth_id,
'User.email.%s' % email,
]
# Create the unique username, auth_id and email.
success, existing = Unique.create_multi(uniques)
if success:
# The unique values were created, so we can save the user.
user = User(username=username, auth_id=auth_id, email=email)
user.put()
return user
else:
# At least one of the values is not unique.
# Make a list of the property names that failed.
props = [name.split('.', 2)[1] for name in uniques]
raise ValueError('Properties %r are not unique.' % props)
Based on the idea from http://goo.gl/pBQhB
"""
@classmethod
def create(cls, value):
"""Creates a new unique value.
:param value:
The value to be unique, as a string.
The value should include the scope in which the value must be
unique (ancestor, namespace, kind and/or property name).
For example, for a unique property `email` from kind `User`, the
value can be `User.email:me@myself.com`. In this case `User.email`
is the scope, and `me@myself.com` is the value to be unique.
:returns:
True if the unique value was created, False otherwise.
"""
entity = cls(key=model.Key(cls, value))
txn = lambda: entity.put() if not entity.key.get() else None
return model.transaction(txn) is not None
@classmethod
def create_multi(cls, values):
"""Creates multiple unique values at once.
:param values:
A sequence of values to be unique. See :meth:`create`.
:returns:
A tuple (bool, list_of_keys). If all values were created, bool is
True and list_of_keys is empty. If one or more values weren't
created, bool is False and the list contains all the values that
already existed in datastore during the creation attempt.
"""
# Maybe do a preliminary check, before going for transactions?
# entities = model.get_multi(keys)
# existing = [entity.key.id() for entity in entities if entity]
# if existing:
# return False, existing
# Create all records transactionally.
keys = [model.Key(cls, value) for value in values]
entities = [cls(key=key) for key in keys]
func = lambda e: e.put() if not e.key.get() else None
created = [model.transaction(lambda: func(e)) for e in entities]
if created != keys:
# A poor man's "rollback": delete all recently created records.
model.delete_multi(k for k in created if k)
return False, [k.id() for k in keys if k not in created]
return True, []
@classmethod
def delete_multi(cls, values):
"""Deletes multiple unique values at once.
:param values:
A sequence of values to be deleted.
"""
return model.delete_multi(model.Key(cls, v) for v in values)
class UserToken(model.Model):
"""Stores validation tokens for users."""
created = model.DateTimeProperty(auto_now_add=True)
updated = model.DateTimeProperty(auto_now=True)
user = model.StringProperty(required=True, indexed=False)
subject = model.StringProperty(required=True)
token = model.StringProperty(required=True)
@classmethod
def get_key(cls, user, subject, token):
"""Returns a token key.
:param user:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
Randomly generated token.
:returns:
``model.Key`` containing a string id in the following format:
``{user_id}.{subject}.{token}.``
"""
return model.Key(cls, '%s.%s.%s' % (str(user), subject, token))
@classmethod
def create(cls, user, subject, token=None):
"""Creates a new token for the given user.
:param user:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
Optionally an existing token may be provided.
If None, a random token will be generated.
:returns:
The newly created :class:`UserToken`.
"""
user = str(user)
token = token or security.generate_random_string(entropy=128)
key = cls.get_key(user, subject, token)
entity = cls(key=key, user=user, subject=subject, token=token)
entity.put()
return entity
@classmethod
def get(cls, user=None, subject=None, token=None):
"""Fetches a user token.
:param user:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
The existing token needing verified.
:returns:
A :class:`UserToken` or None if the token does not exist.
"""
if user and subject and token:
return cls.get_key(user, subject, token).get()
assert subject and token, \
'subject and token must be provided to UserToken.get().'
return cls.query(cls.subject == subject, cls.token == token).get()
class User(model.Expando):
"""Stores user authentication credentials or authorization ids."""
#: The model used to ensure uniqueness.
unique_model = Unique
#: The model used to store tokens.
token_model = UserToken
created = model.DateTimeProperty(auto_now_add=True)
updated = model.DateTimeProperty(auto_now=True)
# ID for third party authentication, e.g. 'google:username'. UNIQUE.
auth_ids = model.StringProperty(repeated=True)
# Hashed password. Not required because third party authentication
# doesn't use password.
password = model.StringProperty()
def get_id(self):
"""Returns this user's unique ID, which can be an integer or string."""
return self._key.id()
def add_auth_id(self, auth_id):
"""A helper method to add additional auth ids to a User
:param auth_id:
String representing a unique id for the user. Examples:
- own:username
- google:username
:returns:
A tuple (boolean, info). The boolean indicates if the user
was saved. If creation succeeds, ``info`` is the user entity;
otherwise it is a list of duplicated unique properties that
caused creation to fail.
"""
self.auth_ids.append(auth_id)
unique = '%s.auth_id:%s' % (self.__class__.__name__, auth_id)
ok = self.unique_model.create(unique)
if ok:
self.put()
return True, self
else:
return False, ['auth_id']
@classmethod
def get_by_auth_id(cls, auth_id):
"""Returns a user object based on a auth_id.
:param auth_id:
String representing a unique id for the user. Examples:
- own:username
- google:username
:returns:
A user object.
"""
return cls.query(cls.auth_ids == auth_id).get()
@classmethod
def get_by_auth_token(cls, user_id, token):
"""Returns a user object based on a user ID and token.
:param user_id:
The user_id of the requesting user.
:param token:
The token string to be verified.
:returns:
A tuple ``(User, timestamp)``, with a user object and
the token timestamp, or ``(None, None)`` if both were not found.
"""
token_key = cls.token_model.get_key(user_id, 'auth', token)
user_key = model.Key(cls, user_id)
# Use get_multi() to save a RPC call.
valid_token, user = model.get_multi([token_key, user_key])
if valid_token and user:
timestamp = int(time.mktime(valid_token.created.timetuple()))
return user, timestamp
return None, None
@classmethod
def get_by_auth_password(cls, auth_id, password):
"""Returns a user object, validating password.
:param auth_id:
Authentication id.
:param password:
Password to be checked.
:returns:
A user object, if found and password matches.
:raises:
``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
"""
user = cls.get_by_auth_id(auth_id)
if not user:
raise auth.InvalidAuthIdError()
if not security.check_password_hash(password, user.password):
raise auth.InvalidPasswordError()
return user
@classmethod
def validate_token(cls, user_id, subject, token):
"""Checks for existence of a token, given user_id, subject and token.
:param user_id:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
The token string to be validated.
:returns:
A :class:`UserToken` or None if the token does not exist.
"""
return cls.token_model.get(user=user_id, subject=subject,
token=token) is not None
@classmethod
def create_auth_token(cls, user_id):
"""Creates a new authorization token for a given user ID.
:param user_id:
User unique ID.
:returns:
A string with the authorization token.
"""
return cls.token_model.create(user_id, 'auth').token
@classmethod
def validate_auth_token(cls, user_id, token):
return cls.validate_token(user_id, 'auth', token)
@classmethod
def delete_auth_token(cls, user_id, token):
"""Deletes a given authorization token.
:param user_id:
User unique ID.
:param token:
A string with the authorization token.
"""
cls.token_model.get_key(user_id, 'auth', token).delete()
@classmethod
def create_signup_token(cls, user_id):
entity = cls.token_model.create(user_id, 'signup')
return entity.token
@classmethod
def validate_signup_token(cls, user_id, token):
return cls.validate_token(user_id, 'signup', token)
@classmethod
def delete_signup_token(cls, user_id, token):
cls.token_model.get_key(user_id, 'signup', token).delete()
@classmethod
def create_user(cls, auth_id, unique_properties=None, **user_values):
"""Creates a new user.
:param auth_id:
A string that is unique to the user. Users may have multiple
auth ids. Example auth ids:
- own:username
- own:email@example.com
- google:username
- yahoo:username
The value of `auth_id` must be unique.
:param unique_properties:
Sequence of extra property names that must be unique.
:param user_values:
Keyword arguments to create a new user entity. Since the model is
an ``Expando``, any provided custom properties will be saved.
To hash a plain password, pass a keyword ``password_raw``.
:returns:
A tuple (boolean, info). The boolean indicates if the user
was created. If creation succeeds, ``info`` is the user entity;
otherwise it is a list of duplicated unique properties that
caused creation to fail.
"""
assert user_values.get('password') is None, \
'Use password_raw instead of password to create new users.'
assert not isinstance(auth_id, list), \
'Creating a user with multiple auth_ids is not allowed, ' \
'please provide a single auth_id.'
if 'password_raw' in user_values:
user_values['password'] = security.generate_password_hash(
user_values.pop('password_raw'), length=12)
user_values['auth_ids'] = [auth_id]
user = cls(**user_values)
# Set up unique properties.
uniques = [('%s.auth_id:%s' % (cls.__name__, auth_id), 'auth_id')]
if unique_properties:
for name in unique_properties:
key = '%s.%s:%s' % (cls.__name__, name, user_values[name])
uniques.append((key, name))
ok, existing = cls.unique_model.create_multi(k for k, v in uniques)
if ok:
user.put()
return True, user
else:
properties = [v for k, v in uniques if k in existing]
return False, properties
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.appengine.auth
=============================
Authentication and authorization utilities.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.appengine.sessions_ndb
=====================================
Extended sessions stored in datastore using the ndb library.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import absolute_import
from google.appengine.api import memcache
try:
from ndb import model
except ImportError: # pragma: no cover
from google.appengine.ext.ndb import model
try:
from ndb.model import PickleProperty
except ImportError: # pragma: no cover
try:
from google.appengine.ext.ndb.model import PickleProperty
except ImportError: # pragma: no cover
# ndb in SDK 1.6.1 doesn't have PickleProperty.
import pickle
class PickleProperty(model.BlobProperty):
"""A Property whose value is any picklable Python object."""
def _validate(self, value):
return value
def _db_set_value(self, v, p, value):
super(PickleProperty, self)._db_set_value(v, p,
pickle.dumps(value))
def _db_get_value(self, v, p):
if not v.has_stringvalue():
return None
return pickle.loads(v.stringvalue())
from webapp2_extras import sessions
class Session(model.Model):
"""A model to store session data."""
#: Save time.
updated = model.DateTimeProperty(auto_now=True)
#: Session data, pickled.
data = PickleProperty()
@classmethod
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id.
:param sid:
A session id.
:returns:
An existing ``Session`` entity.
"""
data = memcache.get(sid)
if not data:
session = model.Key(cls, sid).get()
if session:
data = session.data
memcache.set(sid, data)
return data
def _put(self):
"""Saves the session and updates the memcache entry."""
memcache.set(self._key.id(), self.data)
super(Session, self).put()
class DatastoreSessionFactory(sessions.CustomBackendSessionFactory):
"""A session factory that stores data serialized in datastore.
To use datastore sessions, pass this class as the `factory` keyword to
:meth:`webapp2_extras.sessions.SessionStore.get_session`::
from webapp2_extras import sessions_ndb
# [...]
session = self.session_store.get_session(
name='db_session', factory=sessions_ndb.DatastoreSessionFactory)
See in :meth:`webapp2_extras.sessions.SessionStore` an example of how to
make sessions available in a :class:`webapp2.RequestHandler`.
"""
#: The session model class.
session_model = Session
def _get_by_sid(self, sid):
"""Returns a session given a session id."""
if self._is_valid_sid(sid):
data = self.session_model.get_by_sid(sid)
if data is not None:
self.sid = sid
return sessions.SessionDict(self, data=data)
self.sid = self._get_new_sid()
return sessions.SessionDict(self, new=True)
def save_session(self, response):
if self.session is None or not self.session.modified:
return
self.session_model(id=self.sid, data=dict(self.session))._put()
self.session_store.save_secure_cookie(
response, self.name, {'_sid': self.sid}, **self.session_args)
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.appengine
========================
App Engine-specific modules.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.appengine.users
==============================
Helpers for google.appengine.api.users.
:copyright: 2011 tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from google.appengine.api import users
def login_required(handler_method):
"""A decorator to require that a user be logged in to access a handler.
To use it, decorate your get() method like this::
@login_required
def get(self):
user = users.get_current_user(self)
self.response.out.write('Hello, ' + user.nickname())
We will redirect to a login page if the user is not logged in. We always
redirect to the request URI, and Google Accounts only redirects back as
a GET request, so this should not be used for POSTs.
"""
def check_login(self, *args, **kwargs):
if self.request.method != 'GET':
self.abort(400, detail='The login_required decorator '
'can only be used for GET requests.')
user = users.get_current_user()
if not user:
return self.redirect(users.create_login_url(self.request.url))
else:
handler_method(self, *args, **kwargs)
return check_login
def admin_required(handler_method):
"""A decorator to require that a user be an admin for this application
to access a handler.
To use it, decorate your get() method like this::
@admin_required
def get(self):
user = users.get_current_user(self)
self.response.out.write('Hello, ' + user.nickname())
We will redirect to a login page if the user is not logged in. We always
redirect to the request URI, and Google Accounts only redirects back as
a GET request, so this should not be used for POSTs.
"""
def check_admin(self, *args, **kwargs):
if self.request.method != 'GET':
self.abort(400, detail='The admin_required decorator '
'can only be used for GET requests.')
user = users.get_current_user()
if not user:
return self.redirect(users.create_login_url(self.request.url))
elif not users.is_current_user_admin():
self.abort(403)
else:
handler_method(self, *args, **kwargs)
return check_admin
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.appengine.sessions_memcache
==========================================
Extended sessions stored in memcache.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from google.appengine.api import memcache
from webapp2_extras import sessions
class MemcacheSessionFactory(sessions.CustomBackendSessionFactory):
"""A session factory that stores data serialized in memcache.
To use memcache sessions, pass this class as the `factory` keyword to
:meth:`webapp2_extras.sessions.SessionStore.get_session`::
from webapp2_extras import sessions_memcache
# [...]
session = self.session_store.get_session(
name='mc_session',
factory=sessions_memcache.MemcacheSessionFactory)
See in :meth:`webapp2_extras.sessions.SessionStore` an example of how to
make sessions available in a :class:`webapp2.RequestHandler`.
"""
def _get_by_sid(self, sid):
"""Returns a session given a session id."""
if self._is_valid_sid(sid):
data = memcache.get(sid)
if data is not None:
self.sid = sid
return sessions.SessionDict(self, data=data)
self.sid = self._get_new_sid()
return sessions.SessionDict(self, new=True)
def save_session(self, response):
if self.session is None or not self.session.modified:
return
memcache.set(self.sid, dict(self.session))
self.session_store.save_secure_cookie(
response, self.name, {'_sid': self.sid}, **self.session_args)
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.local
~~~~~~~~~~~~~~~~~~~~
This module implements thread-local utilities.
This implementation comes from werkzeug.local.
:copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from greenlet import getcurrent as get_current_greenlet
except ImportError: # pragma: no cover
try:
from py.magic import greenlet
get_current_greenlet = greenlet.getcurrent
del greenlet
except:
# catch all, py.* fails with so many different errors.
get_current_greenlet = int
try:
from thread import get_ident as get_current_thread, allocate_lock
except ImportError: # pragma: no cover
from dummy_thread import get_ident as get_current_thread, allocate_lock
# get the best ident function. if greenlets are not installed we can
# safely just use the builtin thread function and save a python methodcall
# and the cost of calculating a hash.
if get_current_greenlet is int: # pragma: no cover
get_ident = get_current_thread
else:
get_ident = lambda: (get_current_thread(), get_current_greenlet())
class Local(object):
"""A container for thread-local objects.
Attributes are assigned or retrieved using the current thread.
"""
__slots__ = ('__storage__', '__lock__')
def __init__(self):
object.__setattr__(self, '__storage__', {})
object.__setattr__(self, '__lock__', allocate_lock())
def __iter__(self):
return self.__storage__.iteritems()
def __call__(self, proxy):
"""Creates a proxy for a name."""
return LocalProxy(self, proxy)
def __release_local__(self):
self.__storage__.pop(get_ident(), None)
def __getattr__(self, name):
self.__lock__.acquire()
try:
try:
return self.__storage__[get_ident()][name]
except KeyError:
raise AttributeError(name)
finally:
self.__lock__.release()
def __setattr__(self, name, value):
self.__lock__.acquire()
try:
ident = get_ident()
storage = self.__storage__
if ident in storage:
storage[ident][name] = value
else:
storage[ident] = {name: value}
finally:
self.__lock__.release()
def __delattr__(self, name):
self.__lock__.acquire()
try:
try:
del self.__storage__[get_ident()][name]
except KeyError:
raise AttributeError(name)
finally:
self.__lock__.release()
class LocalProxy(object):
"""Acts as a proxy for a local object.
Forwards all operations to a proxied object. The only operations not
supported for forwarding are right handed operands and any kind of
assignment.
Example usage::
from webapp2_extras import Local
l = Local()
# these are proxies
request = l('request')
user = l('user')
Whenever something is bound to l.user or l.request the proxy objects
will forward all operations. If no object is bound a :exc:`RuntimeError`
will be raised.
To create proxies to :class:`Local` object, call the object as shown above.
If you want to have a proxy to an object looked up by a function, you can
pass a function to the :class:`LocalProxy` constructor::
route_kwargs = LocalProxy(lambda: webapp2.get_request().route_kwargs)
"""
__slots__ = ('__local', '__dict__', '__name__')
def __init__(self, local, name=None):
object.__setattr__(self, '_LocalProxy__local', local)
object.__setattr__(self, '__name__', name)
def _get_current_object(self):
"""Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
if not hasattr(self.__local, '__release_local__'):
return self.__local()
try:
return getattr(self.__local, self.__name__)
except AttributeError:
raise RuntimeError('no object bound to %s' % self.__name__)
@property
def __dict__(self):
try:
return self._get_current_object().__dict__
except RuntimeError:
return AttributeError('__dict__')
def __repr__(self):
try:
obj = self._get_current_object()
except RuntimeError:
return '<%s unbound>' % self.__class__.__name__
return repr(obj)
def __nonzero__(self):
try:
return bool(self._get_current_object())
except RuntimeError:
return False
def __unicode__(self):
try:
return unicode(self._get_current_object())
except RuntimeError:
return repr(self)
def __dir__(self):
try:
return dir(self._get_current_object())
except RuntimeError:
return []
def __getattr__(self, name):
if name == '__members__':
return dir(self._get_current_object())
return getattr(self._get_current_object(), name)
def __setitem__(self, key, value):
self._get_current_object()[key] = value
def __delitem__(self, key):
del self._get_current_object()[key]
def __setslice__(self, i, j, seq):
self._get_current_object()[i:j] = seq
def __delslice__(self, i, j):
del self._get_current_object()[i:j]
__setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
__delattr__ = lambda x, n: delattr(x._get_current_object(), n)
__str__ = lambda x: str(x._get_current_object())
__lt__ = lambda x, o: x._get_current_object() < o
__le__ = lambda x, o: x._get_current_object() <= o
__eq__ = lambda x, o: x._get_current_object() == o
__ne__ = lambda x, o: x._get_current_object() != o
__gt__ = lambda x, o: x._get_current_object() > o
__ge__ = lambda x, o: x._get_current_object() >= o
__cmp__ = lambda x, o: cmp(x._get_current_object(), o)
__hash__ = lambda x: hash(x._get_current_object())
__call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw)
__len__ = lambda x: len(x._get_current_object())
__getitem__ = lambda x, i: x._get_current_object()[i]
__iter__ = lambda x: iter(x._get_current_object())
__contains__ = lambda x, i: i in x._get_current_object()
__getslice__ = lambda x, i, j: x._get_current_object()[i:j]
__add__ = lambda x, o: x._get_current_object() + o
__sub__ = lambda x, o: x._get_current_object() - o
__mul__ = lambda x, o: x._get_current_object() * o
__floordiv__ = lambda x, o: x._get_current_object() // o
__mod__ = lambda x, o: x._get_current_object() % o
__divmod__ = lambda x, o: x._get_current_object().__divmod__(o)
__pow__ = lambda x, o: x._get_current_object() ** o
__lshift__ = lambda x, o: x._get_current_object() << o
__rshift__ = lambda x, o: x._get_current_object() >> o
__and__ = lambda x, o: x._get_current_object() & o
__xor__ = lambda x, o: x._get_current_object() ^ o
__or__ = lambda x, o: x._get_current_object() | o
__div__ = lambda x, o: x._get_current_object().__div__(o)
__truediv__ = lambda x, o: x._get_current_object().__truediv__(o)
__neg__ = lambda x: -(x._get_current_object())
__pos__ = lambda x: +(x._get_current_object())
__abs__ = lambda x: abs(x._get_current_object())
__invert__ = lambda x: ~(x._get_current_object())
__complex__ = lambda x: complex(x._get_current_object())
__int__ = lambda x: int(x._get_current_object())
__long__ = lambda x: long(x._get_current_object())
__float__ = lambda x: float(x._get_current_object())
__oct__ = lambda x: oct(x._get_current_object())
__hex__ = lambda x: hex(x._get_current_object())
__index__ = lambda x: x._get_current_object().__index__()
__coerce__ = lambda x, o: x.__coerce__(x, o)
__enter__ = lambda x: x.__enter__()
__exit__ = lambda x, *a, **kw: x.__exit__(*a, **kw)
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.xsrf
===================
Helpers for defending against cross-site request forgery attacks.
:copyright: 2012 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
__author__ = 'John Lockwood'
import base64
import hmac
import hashlib
import time
class XSRFException(Exception):
pass
class XSRFTokenMalformed(XSRFException):
pass
class XSRFTokenExpiredException(XSRFException):
pass
class XSRFTokenInvalid(XSRFException):
pass
class XSRFToken(object):
_DELIMITER = '|'
def __init__(self, user_id, secret, current_time=None):
"""Initializes the XSRFToken object.
:param user_id:
A string representing the user that the token will be valid for.
:param secret:
A string containing a secret key that will be used to seed the
hash used by the :class:`XSRFToken`.
:param current_time:
An int representing the number of seconds since the epoch. Will be
used by `verify_token_string` to check for token expiry. If `None`
then the current time will be used.
"""
self.user_id = user_id
self.secret = secret
if current_time is None:
self.current_time = int(time.time())
else:
self.current_time = int(current_time)
def _digest_maker(self):
return hmac.new(self.secret, digestmod=hashlib.sha1)
def generate_token_string(self, action=None):
"""Generate a hash of the given token contents that can be verified.
:param action:
A string representing the action that the generated hash is valid
for. This string is usually a URL.
:returns:
A string containing the hash contents of the given `action` and the
contents of the `XSRFToken`. Can be verified with
`verify_token_string`. The string is base64 encoded so it is safe
to use in HTML forms without escaping.
"""
digest_maker = self._digest_maker()
digest_maker.update(self.user_id)
digest_maker.update(self._DELIMITER)
if action:
digest_maker.update(action)
digest_maker.update(self._DELIMITER)
digest_maker.update(str(self.current_time))
return base64.urlsafe_b64encode(
self._DELIMITER.join([digest_maker.hexdigest(),
str(self.current_time)]))
def verify_token_string(self,
token_string,
action=None,
timeout=None,
current_time=None):
"""Generate a hash of the given token contents that can be verified.
:param token_string:
A string containing the hashed token (generated by
`generate_token_string`).
:param action:
A string containing the action that is being verified.
:param timeout:
An int or float representing the number of seconds that the token
is valid for. If None then tokens are valid forever.
:current_time:
An int representing the number of seconds since the epoch. Will be
used by to check for token expiry if `timeout` is set. If `None`
then the current time will be used.
:raises:
XSRFTokenMalformed if the given token_string cannot be parsed.
XSRFTokenExpiredException if the given token string is expired.
XSRFTokenInvalid if the given token string does not match the
contents of the `XSRFToken`.
"""
try:
decoded_token_string = base64.urlsafe_b64decode(token_string)
except TypeError:
raise XSRFTokenMalformed()
split_token = decoded_token_string.split(self._DELIMITER)
if len(split_token) != 2:
raise XSRFTokenMalformed()
try:
token_time = int(split_token[1])
except ValueError:
raise XSRFTokenMalformed()
if timeout is not None:
if current_time is None:
current_time = time.time()
# If an attacker modifies the plain text time then it will not match
# the hashed time so this check is sufficient.
if (token_time + timeout) < current_time:
raise XSRFTokenExpiredException()
expected_token = XSRFToken(self.user_id, self.secret, token_time)
expected_token_string = expected_token.generate_token_string(action)
if len(expected_token_string) != len(token_string):
raise XSRFTokenInvalid()
# Compare the two strings in constant time to prevent timing attacks.
different = 0
for a, b in zip(token_string, expected_token_string):
different |= ord(a) ^ ord(b)
if different:
raise XSRFTokenInvalid()
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.routes
=====================
Extra route classes for webapp2.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import re
import urllib
from webob import exc
import webapp2
class MultiRoute(object):
"""Base class for routes with nested routes."""
routes = None
children = None
match_children = None
build_children = None
def __init__(self, routes):
self.routes = routes
def get_children(self):
if self.children is None:
self.children = []
for route in self.routes:
for r in route.get_routes():
self.children.append(r)
for rv in self.children:
yield rv
def get_match_children(self):
if self.match_children is None:
self.match_children = []
for route in self.get_children():
for r in route.get_match_routes():
self.match_children.append(r)
for rv in self.match_children:
yield rv
def get_build_children(self):
if self.build_children is None:
self.build_children = {}
for route in self.get_children():
for n, r in route.get_build_routes():
self.build_children[n] = r
for rv in self.build_children.iteritems():
yield rv
get_routes = get_children
get_match_routes = get_match_children
get_build_routes = get_build_children
class DomainRoute(MultiRoute):
"""A route used to restrict route matches to a given domain or subdomain.
For example, to restrict routes to a subdomain of the appspot domain::
app = WSGIApplication([
DomainRoute('<subdomain>.app-id.appspot.com', [
Route('/foo', 'FooHandler', 'subdomain-thing'),
]),
Route('/bar', 'BarHandler', 'normal-thing'),
])
The template follows the same syntax used by :class:`webapp2.Route` and
must define named groups if any value must be added to the match results.
In the example above, an extra `subdomain` keyword is passed to the
handler, but if the regex didn't define any named groups, nothing would
be added.
"""
def __init__(self, template, routes):
"""Initializes a URL route.
:param template:
A route template to match against ``environ['SERVER_NAME']``.
See a syntax description in :meth:`webapp2.Route.__init__`.
:param routes:
A list of :class:`webapp2.Route` instances.
"""
super(DomainRoute, self).__init__(routes)
self.template = template
def get_match_routes(self):
# This route will do pre-matching before matching the nested routes!
yield self
def match(self, request):
# Use SERVER_NAME to ignore port number that comes with request.host?
# host_match = self.regex.match(request.host.split(':', 1)[0])
host_match = self.regex.match(request.environ['SERVER_NAME'])
if host_match:
args, kwargs = webapp2._get_route_variables(host_match)
return _match_routes(self.get_match_children, request, None,
kwargs)
@webapp2.cached_property
def regex(self):
regex, reverse_template, args_count, kwargs_count, variables = \
webapp2._parse_route_template(self.template,
default_sufix='[^\.]+')
return regex
class NamePrefixRoute(MultiRoute):
"""The idea of this route is to set a base name for other routes::
app = WSGIApplication([
NamePrefixRoute('user-', [
Route('/users/<user:\w+>/', UserOverviewHandler, 'overview'),
Route('/users/<user:\w+>/profile', UserProfileHandler,
'profile'),
Route('/users/<user:\w+>/projects', UserProjectsHandler,
'projects'),
]),
])
The example above is the same as setting the following routes, just more
convenient as you can reuse the name prefix::
app = WSGIApplication([
Route('/users/<user:\w+>/', UserOverviewHandler, 'user-overview'),
Route('/users/<user:\w+>/profile', UserProfileHandler,
'user-profile'),
Route('/users/<user:\w+>/projects', UserProjectsHandler,
'user-projects'),
])
"""
_attr = 'name'
def __init__(self, prefix, routes):
"""Initializes a URL route.
:param prefix:
The prefix to be prepended.
:param routes:
A list of :class:`webapp2.Route` instances.
"""
super(NamePrefixRoute, self).__init__(routes)
self.prefix = prefix
# Prepend a prefix to a route attribute.
for route in self.get_routes():
setattr(route, self._attr, prefix + getattr(route, self._attr))
class HandlerPrefixRoute(NamePrefixRoute):
"""Same as :class:`NamePrefixRoute`, but prefixes the route handler."""
_attr = 'handler'
class PathPrefixRoute(NamePrefixRoute):
"""Same as :class:`NamePrefixRoute`, but prefixes the route path.
For example, imagine we have these routes::
app = WSGIApplication([
Route('/users/<user:\w+>/', UserOverviewHandler,
'user-overview'),
Route('/users/<user:\w+>/profile', UserProfileHandler,
'user-profile'),
Route('/users/<user:\w+>/projects', UserProjectsHandler,
'user-projects'),
])
We could refactor them to reuse the common path prefix::
app = WSGIApplication([
PathPrefixRoute('/users/<user:\w+>', [
Route('/', UserOverviewHandler, 'user-overview'),
Route('/profile', UserProfileHandler, 'user-profile'),
Route('/projects', UserProjectsHandler, 'user-projects'),
]),
])
This is not only convenient, but also performs better: the nested routes
will only be tested if the path prefix matches.
"""
_attr = 'template'
def __init__(self, prefix, routes):
"""Initializes a URL route.
:param prefix:
The prefix to be prepended. It must start with a slash but not
end with a slash.
:param routes:
A list of :class:`webapp2.Route` instances.
"""
assert prefix.startswith('/') and not prefix.endswith('/'), \
'Path prefixes must start with a slash but not end with a slash.'
super(PathPrefixRoute, self).__init__(prefix, routes)
def get_match_routes(self):
# This route will do pre-matching before matching the nested routes!
yield self
def match(self, request):
if not self.regex.match(urllib.unquote(request.path)):
return None
return _match_routes(self.get_match_children, request)
@webapp2.cached_property
def regex(self):
regex, reverse_template, args_count, kwargs_count, variables = \
webapp2._parse_route_template(self.prefix + '<:/.*>')
return regex
class RedirectRoute(webapp2.Route):
"""A convenience route class for easy redirects.
It adds redirect_to, redirect_to_name and strict_slash options to
:class:`webapp2.Route`.
"""
def __init__(self, template, handler=None, name=None, defaults=None,
build_only=False, handler_method=None, methods=None,
schemes=None, redirect_to=None, redirect_to_name=None,
strict_slash=False):
"""Initializes a URL route. Extra arguments compared to
:meth:`webapp2.Route.__init__`:
:param redirect_to:
A URL string or a callable that returns a URL. If set, this route
is used to redirect to it. The callable is called passing
``(handler, *args, **kwargs)`` as arguments. This is a
convenience to use :class:`RedirectHandler`. These two are
equivalent::
route = Route('/foo', handler=webapp2.RedirectHandler,
defaults={'_uri': '/bar'})
route = Route('/foo', redirect_to='/bar')
:param redirect_to_name:
Same as `redirect_to`, but the value is the name of a route to
redirect to. In the example below, accessing '/hello-again' will
redirect to the route named 'hello'::
route = Route('/hello', handler=HelloHandler, name='hello')
route = Route('/hello-again', redirect_to_name='hello')
:param strict_slash:
If True, redirects access to the same URL with different trailing
slash to the strict path defined in the route. For example, take
these routes::
route = Route('/foo', FooHandler, strict_slash=True)
route = Route('/bar/', BarHandler, strict_slash=True)
Because **strict_slash** is True, this is what will happen:
- Access to ``/foo`` will execute ``FooHandler`` normally.
- Access to ``/bar/`` will execute ``BarHandler`` normally.
- Access to ``/foo/`` will redirect to ``/foo``.
- Access to ``/bar`` will redirect to ``/bar/``.
"""
super(RedirectRoute, self).__init__(
template, handler=handler, name=name, defaults=defaults,
build_only=build_only, handler_method=handler_method,
methods=methods, schemes=schemes)
if strict_slash and not name:
raise ValueError('Routes with strict_slash must have a name.')
self.strict_slash = strict_slash
self.redirect_to_name = redirect_to_name
if redirect_to is not None:
assert redirect_to_name is None
self.handler = webapp2.RedirectHandler
self.defaults['_uri'] = redirect_to
def get_match_routes(self):
"""Generator to get all routes that can be matched from a route.
:yields:
This route or all nested routes that can be matched.
"""
if self.redirect_to_name:
main_route = self._get_redirect_route(name=self.redirect_to_name)
else:
main_route = self
if not self.build_only:
if self.strict_slash is True:
if self.template.endswith('/'):
template = self.template[:-1]
else:
template = self.template + '/'
yield main_route
yield self._get_redirect_route(template=template)
else:
yield main_route
def _get_redirect_route(self, template=None, name=None):
template = template or self.template
name = name or self.name
defaults = self.defaults.copy()
defaults.update({
'_uri': self._redirect,
'_name': name,
})
new_route = webapp2.Route(template, webapp2.RedirectHandler,
defaults=defaults)
return new_route
def _redirect(self, handler, *args, **kwargs):
# Get from request because args is empty if named routes are set?
# args, kwargs = (handler.request.route_args,
# handler.request.route_kwargs)
kwargs.pop('_uri', None)
kwargs.pop('_code', None)
return handler.uri_for(kwargs.pop('_name'), *args, **kwargs)
def _match_routes(iter_func, request, extra_args=None, extra_kwargs=None):
"""Tries to match a route given an iterator."""
method_not_allowed = False
for route in iter_func():
try:
match = route.match(request)
if match:
route, args, kwargs = match
if extra_args:
args += extra_args
if extra_kwargs:
kwargs.update(extra_kwargs)
return route, args, kwargs
except exc.HTTPMethodNotAllowed:
method_not_allowed = True
if method_not_allowed:
raise exc.HTTPMethodNotAllowed()
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.sessions
=======================
Lightweight but flexible session support for webapp2.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import re
import webapp2
from webapp2_extras import securecookie
from webapp2_extras import security
#: Default configuration values for this module. Keys are:
#:
#: secret_key
#: Secret key to generate session cookies. Set this to something random
#: and unguessable. This is the only required configuration key:
#: an exception is raised if it is not defined.
#:
#: cookie_name
#: Name of the cookie to save a session or session id. Default is
#: `session`.
#:
#: session_max_age:
#: Default session expiration time in seconds. Limits the duration of the
#: contents of a cookie, even if a session cookie exists. If None, the
#: contents lasts as long as the cookie is valid. Default is None.
#:
#: cookie_args
#: Default keyword arguments used to set a cookie. Keys are:
#:
#: - max_age: Cookie max age in seconds. Limits the duration
#: of a session cookie. If None, the cookie lasts until the client
#: is closed. Default is None.
#:
#: - domain: Domain of the cookie. To work accross subdomains the
#: domain must be set to the main domain with a preceding dot, e.g.,
#: cookies set for `.mydomain.org` will work in `foo.mydomain.org` and
#: `bar.mydomain.org`. Default is None, which means that cookies will
#: only work for the current subdomain.
#:
#: - path: Path in which the authentication cookie is valid.
#: Default is `/`.
#:
#: - secure: Make the cookie only available via HTTPS.
#:
#: - httponly: Disallow JavaScript to access the cookie.
#:
#: backends
#: A dictionary of available session backend classes used by
#: :meth:`SessionStore.get_session`.
default_config = {
'secret_key': None,
'cookie_name': 'session',
'session_max_age': None,
'cookie_args': {
'max_age': None,
'domain': None,
'path': '/',
'secure': None,
'httponly': False,
},
'backends': {
'securecookie': 'webapp2_extras.sessions.SecureCookieSessionFactory',
'datastore': 'webapp2_extras.appengine.sessions_ndb.' \
'DatastoreSessionFactory',
'memcache': 'webapp2_extras.appengine.sessions_memcache.' \
'MemcacheSessionFactory',
},
}
_default_value = object()
class _UpdateDictMixin(object):
"""Makes dicts call `self.on_update` on modifications.
From werkzeug.datastructures.
"""
on_update = None
def calls_update(name):
def oncall(self, *args, **kw):
rv = getattr(super(_UpdateDictMixin, self), name)(*args, **kw)
if self.on_update is not None:
self.on_update()
return rv
oncall.__name__ = name
return oncall
__setitem__ = calls_update('__setitem__')
__delitem__ = calls_update('__delitem__')
clear = calls_update('clear')
pop = calls_update('pop')
popitem = calls_update('popitem')
setdefault = calls_update('setdefault')
update = calls_update('update')
del calls_update
class SessionDict(_UpdateDictMixin, dict):
"""A dictionary for session data."""
__slots__ = ('container', 'new', 'modified')
def __init__(self, container, data=None, new=False):
self.container = container
self.new = new
self.modified = False
dict.update(self, data or ())
def pop(self, key, *args):
# Only pop if key doesn't exist, do not alter the dictionary.
if key in self:
return super(SessionDict, self).pop(key, *args)
if args:
return args[0]
raise KeyError(key)
def on_update(self):
self.modified = True
def get_flashes(self, key='_flash'):
"""Returns a flash message. Flash messages are deleted when first read.
:param key:
Name of the flash key stored in the session. Default is '_flash'.
:returns:
The data stored in the flash, or an empty list.
"""
return self.pop(key, [])
def add_flash(self, value, level=None, key='_flash'):
"""Adds a flash message. Flash messages are deleted when first read.
:param value:
Value to be saved in the flash message.
:param level:
An optional level to set with the message. Default is `None`.
:param key:
Name of the flash key stored in the session. Default is '_flash'.
"""
self.setdefault(key, []).append((value, level))
class BaseSessionFactory(object):
"""Base class for all session factories."""
#: Name of the session.
name = None
#: A reference to :class:`SessionStore`.
session_store = None
#: Keyword arguments to save the session.
session_args = None
#: The session data, a :class:`SessionDict` instance.
session = None
def __init__(self, name, session_store):
self.name = name
self.session_store = session_store
self.session_args = session_store.config['cookie_args'].copy()
self.session = None
def get_session(self, max_age=_default_value):
raise NotImplementedError()
def save_session(self, response):
raise NotImplementedError()
class SecureCookieSessionFactory(BaseSessionFactory):
"""A session factory that stores data serialized in a signed cookie.
Signed cookies can't be forged because the HMAC signature won't match.
This is the default factory passed as the `factory` keyword to
:meth:`SessionStore.get_session`.
.. warning::
The values stored in a signed cookie will be visible in the cookie,
so do not use secure cookie sessions if you need to store data that
can't be visible to users. For this, use datastore or memcache sessions.
"""
def get_session(self, max_age=_default_value):
if self.session is None:
data = self.session_store.get_secure_cookie(self.name,
max_age=max_age)
new = data is None
self.session = SessionDict(self, data=data, new=new)
return self.session
def save_session(self, response):
if self.session is None or not self.session.modified:
return
self.session_store.save_secure_cookie(
response, self.name, dict(self.session), **self.session_args)
class CustomBackendSessionFactory(BaseSessionFactory):
"""Base class for sessions that use custom backends, e.g., memcache."""
#: The session unique id.
sid = None
#: Used to validate session ids.
_sid_re = re.compile(r'^\w{22}$')
def get_session(self, max_age=_default_value):
if self.session is None:
data = self.session_store.get_secure_cookie(self.name,
max_age=max_age)
sid = data.get('_sid') if data else None
self.session = self._get_by_sid(sid)
return self.session
def _get_by_sid(self, sid):
raise NotImplementedError()
def _is_valid_sid(self, sid):
"""Check if a session id has the correct format."""
return sid and self._sid_re.match(sid) is not None
def _get_new_sid(self):
return security.generate_random_string(entropy=128)
class SessionStore(object):
"""A session provider for a single request.
The session store can provide multiple sessions using different keys,
even using different backends in the same request, through the method
:meth:`get_session`. By default it returns a session using the default key.
To use, define a base handler that extends the dispatch() method to start
the session store and save all sessions at the end of a request::
import webapp2
from webapp2_extras import sessions
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
# Get a session store for this request.
self.session_store = sessions.get_store(request=self.request)
try:
# Dispatch the request.
webapp2.RequestHandler.dispatch(self)
finally:
# Save all sessions.
self.session_store.save_sessions(self.response)
@webapp2.cached_property
def session(self):
# Returns a session using the default cookie key.
return self.session_store.get_session()
Then just use the session as a dictionary inside a handler::
# To set a value:
self.session['foo'] = 'bar'
# To get a value:
foo = self.session.get('foo')
A configuration dict can be passed to :meth:`__init__`, or the application
must be initialized with the ``secret_key`` configuration defined. The
configuration is a simple dictionary::
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'my-super-secret-key',
}
app = webapp2.WSGIApplication([
('/', HomeHandler),
], config=config)
Other configuration keys are optional.
"""
#: Configuration key.
config_key = __name__
def __init__(self, request, config=None):
"""Initializes the session store.
:param request:
A :class:`webapp2.Request` instance.
:param config:
A dictionary of configuration values to be overridden. See
the available keys in :data:`default_config`.
"""
self.request = request
# Base configuration.
self.config = request.app.config.load_config(self.config_key,
default_values=default_config, user_values=config,
required_keys=('secret_key',))
# Tracked sessions.
self.sessions = {}
@webapp2.cached_property
def serializer(self):
# Serializer and deserializer for signed cookies.
return securecookie.SecureCookieSerializer(self.config['secret_key'])
def get_backend(self, name):
"""Returns a configured session backend, importing it if needed.
:param name:
The backend keyword.
:returns:
A :class:`BaseSessionFactory` subclass.
"""
backends = self.config['backends']
backend = backends[name]
if isinstance(backend, basestring):
backend = backends[name] = webapp2.import_string(backend)
return backend
# Backend based sessions --------------------------------------------------
def _get_session_container(self, name, factory):
if name not in self.sessions:
self.sessions[name] = factory(name, self)
return self.sessions[name]
def get_session(self, name=None, max_age=_default_value, factory=None,
backend='securecookie'):
"""Returns a session for a given name. If the session doesn't exist, a
new session is returned.
:param name:
Cookie name. If not provided, uses the ``cookie_name``
value configured for this module.
:param max_age:
A maximum age in seconds for the session to be valid. Sessions
store a timestamp to invalidate them if needed. If `max_age` is
None, the timestamp won't be checked.
:param factory:
A session factory that creates the session using the preferred
backend. For convenience, use the `backend` argument instead,
which defines a backend keyword based on the configured ones.
:param backend:
A configured backend keyword. Available ones are:
- ``securecookie``: uses secure cookies. This is the default
backend.
- ``datastore``: uses App Engine's datastore.
- ``memcache``: uses App Engine's memcache.
:returns:
A dictionary-like session object.
"""
factory = factory or self.get_backend(backend)
name = name or self.config['cookie_name']
if max_age is _default_value:
max_age = self.config['session_max_age']
container = self._get_session_container(name, factory)
return container.get_session(max_age=max_age)
# Signed cookies ----------------------------------------------------------
def get_secure_cookie(self, name, max_age=_default_value):
"""Returns a deserialized secure cookie value.
:param name:
Cookie name.
:param max_age:
Maximum age in seconds for a valid cookie. If the cookie is older
than this, returns None.
:returns:
A secure cookie value or None if it is not set.
"""
if max_age is _default_value:
max_age = self.config['session_max_age']
value = self.request.cookies.get(name)
if value:
return self.serializer.deserialize(name, value, max_age=max_age)
def set_secure_cookie(self, name, value, **kwargs):
"""Sets a secure cookie to be saved.
:param name:
Cookie name.
:param value:
Cookie value. Must be a dictionary.
:param kwargs:
Options to save the cookie. See :meth:`get_session`.
"""
assert isinstance(value, dict), 'Secure cookie values must be a dict.'
container = self._get_session_container(name,
SecureCookieSessionFactory)
container.get_session().update(value)
container.session_args.update(kwargs)
# Saving to a response object ---------------------------------------------
def save_sessions(self, response):
"""Saves all sessions in a response object.
:param response:
A :class:`webapp.Response` object.
"""
for session in self.sessions.values():
session.save_session(response)
def save_secure_cookie(self, response, name, value, **kwargs):
value = self.serializer.serialize(name, value)
response.set_cookie(name, value, **kwargs)
# Factories -------------------------------------------------------------------
#: Key used to store :class:`SessionStore` in the request registry.
_registry_key = 'webapp2_extras.sessions.SessionStore'
def get_store(factory=SessionStore, key=_registry_key, request=None):
"""Returns an instance of :class:`SessionStore` from the request registry.
It'll try to get it from the current request registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`SessionStore` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param request:
A :class:`webapp2.Request` instance used to store the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
store = request.registry.get(key)
if not store:
store = request.registry[key] = factory(request)
return store
def set_store(store, key=_registry_key, request=None):
"""Sets an instance of :class:`SessionStore` in the request registry.
:param store:
An instance of :class:`SessionStore`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.Request` instance used to retrieve the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
request.registry[key] = store
# Don't need to import it. :)
default_config['backends']['securecookie'] = SecureCookieSessionFactory
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.json
===================
JSON helpers for webapp2.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import absolute_import
import base64
import urllib
try:
# Preference for installed library with updated fixes.
# Also available in Google App Engine SDK >= 1.4.2.
import simplejson as json
except ImportError: # pragma: no cover
try:
# Standard library module in Python >= 2.6.
import json
except ImportError: # pragma: no cover
raise RuntimeError(
'A JSON parser is required, e.g., simplejson at '
'http://pypi.python.org/pypi/simplejson/')
assert hasattr(json, 'loads') and hasattr(json, 'dumps'), \
'Expected a JSON module with the functions loads() and dumps().'
def encode(value, *args, **kwargs):
"""Serializes a value to JSON.
This comes from `Tornado`_.
:param value:
A value to be serialized.
:param args:
Extra arguments to be passed to `json.dumps()`.
:param kwargs:
Extra keyword arguments to be passed to `json.dumps()`.
:returns:
The serialized value.
"""
# By default encode using a compact format.
kwargs.setdefault('separators', (',', ':'))
# JSON permits but does not require forward slashes to be escaped.
# This is useful when json data is emitted in a <script> tag
# in HTML, as it prevents </script> tags from prematurely terminating
# the javascript. Some json libraries do this escaping by default,
# although python's standard library does not, so we do it here.
# See: http://goo.gl/WsXwv
return json.dumps(value, *args, **kwargs).replace("</", "<\\/")
def decode(value, *args, **kwargs):
"""Deserializes a value from JSON.
This comes from `Tornado`_.
:param value:
A value to be deserialized.
:param args:
Extra arguments to be passed to `json.loads()`.
:param kwargs:
Extra keyword arguments to be passed to `json.loads()`.
:returns:
The deserialized value.
"""
if isinstance(value, str):
value = value.decode('utf-8')
assert isinstance(value, unicode)
return json.loads(value, *args, **kwargs)
def b64encode(value, *args, **kwargs):
"""Serializes a value to JSON and encodes it using base64.
Parameters and return value are the same from :func:`encode`.
"""
return base64.b64encode(encode(value, *args, **kwargs))
def b64decode(value, *args, **kwargs):
"""Decodes a value using base64 and deserializes it from JSON.
Parameters and return value are the same from :func:`decode`.
"""
return decode(base64.b64decode(value), *args, **kwargs)
def quote(value, *args, **kwargs):
"""Serializes a value to JSON and encodes it using urllib.quote.
Parameters and return value are the same from :func:`encode`.
"""
return urllib.quote(encode(value, *args, **kwargs))
def unquote(value, *args, **kwargs):
"""Decodes a value using urllib.unquote and deserializes it from JSON.
Parameters and return value are the same from :func:`decode`.
"""
return decode(urllib.unquote(value), *args, **kwargs)
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.local_app
~~~~~~~~~~~~~~~~~~~~~~~~
This module is deprecated. The functionality is now available
directly in webapp2.
Previously it implemented a WSGIApplication adapted for threaded
environments.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import warnings
import webapp2
warnings.warn(DeprecationWarning(
'webapp2_extras.local_app is deprecated. webapp2.WSGIApplication is now '
'thread-safe by default when webapp2_extras.local is available.'),
stacklevel=1)
WSGIApplication = webapp2.WSGIApplication
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.securecookie
===========================
A serializer for signed cookies.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import Cookie
import hashlib
import hmac
import logging
import time
from webapp2_extras import json
from webapp2_extras import security
class SecureCookieSerializer(object):
"""Serializes and deserializes secure cookie values.
Extracted from `Tornado`_ and modified.
"""
def __init__(self, secret_key):
"""Initiliazes the serializer/deserializer.
:param secret_key:
A random string to be used as the HMAC secret for the cookie
signature.
"""
self.secret_key = secret_key
def serialize(self, name, value):
"""Serializes a signed cookie value.
:param name:
Cookie name.
:param value:
Cookie value to be serialized.
:returns:
A serialized value ready to be stored in a cookie.
"""
timestamp = str(self._get_timestamp())
value = self._encode(value)
signature = self._get_signature(name, value, timestamp)
return '|'.join([value, timestamp, signature])
def deserialize(self, name, value, max_age=None):
"""Deserializes a signed cookie value.
:param name:
Cookie name.
:param value:
A cookie value to be deserialized.
:param max_age:
Maximum age in seconds for a valid cookie. If the cookie is older
than this, returns None.
:returns:
The deserialized secure cookie, or None if it is not valid.
"""
if not value:
return None
# Unquote for old WebOb.
value = Cookie._unquote(value)
parts = value.split('|')
if len(parts) != 3:
return None
signature = self._get_signature(name, parts[0], parts[1])
if not security.compare_hashes(parts[2], signature):
logging.warning('Invalid cookie signature %r', value)
return None
if max_age is not None:
if int(parts[1]) < self._get_timestamp() - max_age:
logging.warning('Expired cookie %r', value)
return None
try:
return self._decode(parts[0])
except Exception, e:
logging.warning('Cookie value failed to be decoded: %r', parts[0])
return None
def _encode(self, value):
return json.b64encode(value)
def _decode(self, value):
return json.b64decode(value)
def _get_timestamp(self):
return int(time.time())
def _get_signature(self, *parts):
"""Generates an HMAC signature."""
signature = hmac.new(self.secret_key, digestmod=hashlib.sha1)
signature.update('|'.join(parts))
return signature.hexdigest()
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.sessions_ndb
===========================
Extended sessions stored in datastore using the ndb library.
App Engine-specific modules were moved to webapp2_extras.appengine.
This module is here for compatibility purposes.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import warnings
warnings.warn(DeprecationWarning(
'webapp2_extras.sessions_ndb is deprecated. '
'App Engine-specific modules were moved to webapp2_extras.appengine.'),
stacklevel=1)
from webapp2_extras.appengine.sessions_ndb import *
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras
==============
Extra modules for webapp2.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.users
====================
Helpers for google.appengine.api.users.
App Engine-specific modules were moved to webapp2_extras.appengine.
This module is here for compatibility purposes.
:copyright: 2011 tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import warnings
warnings.warn(DeprecationWarning(
'webapp2_extras.users is deprecated. '
'App Engine-specific modules were moved to webapp2_extras.appengine.'),
stacklevel=1)
from webapp2_extras.appengine.users import *
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.i18n
===================
Internationalization support for webapp2.
Several ideas borrowed from tipfy.i18n and Flask-Babel.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import datetime
import gettext as gettext_stdlib
import babel
from babel import dates
from babel import numbers
from babel import support
try:
# Monkeypatches pytz for gae.
import pytz.gae
except ImportError: # pragma: no cover
pass
import pytz
import webapp2
#: Default configuration values for this module. Keys are:
#:
#: translations_path
#: Path to the translations directory. Default is `locale`.
#:
#: domains
#: List of gettext domains to be used. Default is ``['messages']``.
#:
#: default_locale
#: A locale code to be used as fallback. Default is ``'en_US'``.
#:
#: default_timezone
#: The application default timezone according to the Olson
#: database. Default is ``'UTC'``.
#:
#: locale_selector
#: A function that receives (store, request) and returns a locale
#: to be used for a request. If not defined, uses `default_locale`.
#: Can also be a string in dotted notation to be imported.
#:
#: timezone_selector
#: A function that receives (store, request) and returns a timezone
#: to be used for a request. If not defined, uses `default_timezone`.
#: Can also be a string in dotted notation to be imported.
#:
#: date_formats
#: Default date formats for datetime, date and time.
default_config = {
'translations_path': 'locale',
'domains': ['messages'],
'default_locale': 'en_US',
'default_timezone': 'UTC',
'locale_selector': None,
'timezone_selector': None,
'date_formats': {
'time': 'medium',
'date': 'medium',
'datetime': 'medium',
'time.short': None,
'time.medium': None,
'time.full': None,
'time.long': None,
'time.iso': "HH':'mm':'ss",
'date.short': None,
'date.medium': None,
'date.full': None,
'date.long': None,
'date.iso': "yyyy'-'MM'-'dd",
'datetime.short': None,
'datetime.medium': None,
'datetime.full': None,
'datetime.long': None,
'datetime.iso': "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ",
},
}
NullTranslations = gettext_stdlib.NullTranslations
class I18nStore(object):
"""Internalization store.
Caches loaded translations and configuration to be used between requests.
"""
#: Configuration key.
config_key = __name__
#: A dictionary with all loaded translations.
translations = None
#: Path to where traslations are stored.
translations_path = None
#: Translation domains to merge.
domains = None
#: Default locale code.
default_locale = None
#: Default timezone code.
default_timezone = None
#: Dictionary of default date formats.
date_formats = None
#: A callable that returns the locale for a request.
locale_selector = None
#: A callable that returns the timezone for a request.
timezone_selector = None
def __init__(self, app, config=None):
"""Initializes the i18n store.
:param app:
A :class:`webapp2.WSGIApplication` instance.
:param config:
A dictionary of configuration values to be overridden. See
the available keys in :data:`default_config`.
"""
config = app.config.load_config(self.config_key,
default_values=default_config, user_values=config,
required_keys=None)
self.translations = {}
self.translations_path = config['translations_path']
self.domains = config['domains']
self.default_locale = config['default_locale']
self.default_timezone = config['default_timezone']
self.date_formats = config['date_formats']
self.set_locale_selector(config['locale_selector'])
self.set_timezone_selector(config['timezone_selector'])
def set_locale_selector(self, func):
"""Sets the function that defines the locale for a request.
:param func:
A callable that receives (store, request) and returns the locale
for a request.
"""
if func is None:
self.locale_selector = self.default_locale_selector
else:
if isinstance(func, basestring):
func = webapp2.import_string(func)
# Functions are descriptors, so bind it to this instance with
# __get__.
self.locale_selector = func.__get__(self, self.__class__)
def set_timezone_selector(self, func):
"""Sets the function that defines the timezone for a request.
:param func:
A callable that receives (store, request) and returns the timezone
for a request.
"""
if func is None:
self.timezone_selector = self.default_timezone_selector
else:
if isinstance(func, basestring):
func = webapp2.import_string(func)
self.timezone_selector = func.__get__(self, self.__class__)
def default_locale_selector(self, request):
return self.default_locale
def default_timezone_selector(self, request):
return self.default_timezone
def get_translations(self, locale):
"""Returns a translation catalog for a locale.
:param locale:
A locale code.
:returns:
A ``babel.support.Translations`` instance, or
``gettext.NullTranslations`` if none was found.
"""
trans = self.translations.get(locale)
if not trans:
locales = (locale, self.default_locale)
trans = self.load_translations(self.translations_path, locales,
self.domains)
if not webapp2.get_app().debug:
self.translations[locale] = trans
return trans
def load_translations(self, dirname, locales, domains):
"""Loads a translation catalog.
:param dirname:
Path to where translations are stored.
:param locales:
A list of locale codes.
:param domains:
A list of domains to be merged.
:returns:
A ``babel.support.Translations`` instance, or
``gettext.NullTranslations`` if none was found.
"""
trans = None
trans_null = None
for domain in domains:
_trans = support.Translations.load(dirname, locales, domain)
if isinstance(_trans, NullTranslations):
trans_null = _trans
continue
elif trans is None:
trans = _trans
else:
trans.merge(_trans)
return trans or trans_null or NullTranslations()
class I18n(object):
"""Internalization provider for a single request."""
#: A reference to :class:`I18nStore`.
store = None
#: The current locale code.
locale = None
#: The current translations.
translations = None
#: The current timezone code.
timezone = None
#: The current tzinfo object.
tzinfo = None
def __init__(self, request):
"""Initializes the i18n provider for a request.
:param request:
A :class:`webapp2.Request` instance.
"""
self.store = store = get_store(app=request.app)
self.set_locale(store.locale_selector(request))
self.set_timezone(store.timezone_selector(request))
def set_locale(self, locale):
"""Sets the locale code for this request.
:param locale:
A locale code.
"""
self.locale = locale
self.translations = self.store.get_translations(locale)
def set_timezone(self, timezone):
"""Sets the timezone code for this request.
:param timezone:
A timezone code.
"""
self.timezone = timezone
self.tzinfo = pytz.timezone(timezone)
def gettext(self, string, **variables):
"""Translates a given string according to the current locale.
:param string:
The string to be translated.
:param variables:
Variables to format the returned string.
:returns:
The translated string.
"""
if variables:
return self.translations.ugettext(string) % variables
return self.translations.ugettext(string)
def ngettext(self, singular, plural, n, **variables):
"""Translates a possible pluralized string according to the current
locale.
:param singular:
The singular for of the string to be translated.
:param plural:
The plural for of the string to be translated.
:param n:
An integer indicating if this is a singular or plural. If greater
than 1, it is a plural.
:param variables:
Variables to format the returned string.
:returns:
The translated string.
"""
if variables:
return self.translations.ungettext(singular, plural, n) % variables
return self.translations.ungettext(singular, plural, n)
def to_local_timezone(self, datetime):
"""Returns a datetime object converted to the local timezone.
:param datetime:
A ``datetime`` object.
:returns:
A ``datetime`` object normalized to a timezone.
"""
if datetime.tzinfo is None:
datetime = datetime.replace(tzinfo=pytz.UTC)
return self.tzinfo.normalize(datetime.astimezone(self.tzinfo))
def to_utc(self, datetime):
"""Returns a datetime object converted to UTC and without tzinfo.
:param datetime:
A ``datetime`` object.
:returns:
A naive ``datetime`` object (no timezone), converted to UTC.
"""
if datetime.tzinfo is None:
datetime = self.tzinfo.localize(datetime)
return datetime.astimezone(pytz.UTC).replace(tzinfo=None)
def _get_format(self, key, format):
"""A helper for the datetime formatting functions. Returns a format
name or pattern to be used by Babel date format functions.
:param key:
A format key to be get from config. Valid values are "date",
"datetime" or "time".
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time pattern.
:returns:
A format name or pattern to be used by Babel date format functions.
"""
if format is None:
format = self.store.date_formats.get(key)
if format in ('short', 'medium', 'full', 'long', 'iso'):
rv = self.store.date_formats.get('%s.%s' % (key, format))
if rv is not None:
format = rv
return format
def format_date(self, date=None, format=None, rebase=True):
"""Returns a date formatted according to the given pattern and
following the current locale.
:param date:
A ``date`` or ``datetime`` object. If None, the current date in
UTC is used.
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time pattern. Example outputs:
- short: 11/10/09
- medium: Nov 10, 2009
- long: November 10, 2009
- full: Tuesday, November 10, 2009
:param rebase:
If True, converts the date to the current :attr:`timezone`.
:returns:
A formatted date in unicode.
"""
format = self._get_format('date', format)
if rebase and isinstance(date, datetime.datetime):
date = self.to_local_timezone(date)
return dates.format_date(date, format, locale=self.locale)
def format_datetime(self, datetime=None, format=None, rebase=True):
"""Returns a date and time formatted according to the given pattern
and following the current locale and timezone.
:param datetime:
A ``datetime`` object. If None, the current date and time in UTC
is used.
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time pattern. Example outputs:
- short: 11/10/09 4:36 PM
- medium: Nov 10, 2009 4:36:05 PM
- long: November 10, 2009 4:36:05 PM +0000
- full: Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time
:param rebase:
If True, converts the datetime to the current :attr:`timezone`.
:returns:
A formatted date and time in unicode.
"""
format = self._get_format('datetime', format)
kwargs = {}
if rebase:
kwargs['tzinfo'] = self.tzinfo
return dates.format_datetime(datetime, format, locale=self.locale,
**kwargs)
def format_time(self, time=None, format=None, rebase=True):
"""Returns a time formatted according to the given pattern and
following the current locale and timezone.
:param time:
A ``time`` or ``datetime`` object. If None, the current
time in UTC is used.
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time pattern. Example outputs:
- short: 4:36 PM
- medium: 4:36:05 PM
- long: 4:36:05 PM +0000
- full: 4:36:05 PM World (GMT) Time
:param rebase:
If True, converts the time to the current :attr:`timezone`.
:returns:
A formatted time in unicode.
"""
format = self._get_format('time', format)
kwargs = {}
if rebase:
kwargs['tzinfo'] = self.tzinfo
return dates.format_time(time, format, locale=self.locale, **kwargs)
def format_timedelta(self, datetime_or_timedelta, granularity='second',
threshold=.85):
"""Formats the elapsed time from the given date to now or the given
timedelta. This currently requires an unreleased development version
of Babel.
:param datetime_or_timedelta:
A ``timedelta`` object representing the time difference to format,
or a ``datetime`` object in UTC.
:param granularity:
Determines the smallest unit that should be displayed, the value
can be one of "year", "month", "week", "day", "hour", "minute" or
"second".
:param threshold:
Factor that determines at which point the presentation switches to
the next higher unit.
:returns:
A string with the elapsed time.
"""
if isinstance(datetime_or_timedelta, datetime.datetime):
datetime_or_timedelta = datetime.datetime.utcnow() - \
datetime_or_timedelta
return dates.format_timedelta(datetime_or_timedelta, granularity,
threshold=threshold,
locale=self.locale)
def format_number(self, number):
"""Returns the given number formatted for the current locale. Example::
>>> format_number(1099, locale='en_US')
u'1,099'
:param number:
The number to format.
:returns:
The formatted number.
"""
return numbers.format_number(number, locale=self.locale)
def format_decimal(self, number, format=None):
"""Returns the given decimal number formatted for the current locale.
Example::
>>> format_decimal(1.2345, locale='en_US')
u'1.234'
>>> format_decimal(1.2346, locale='en_US')
u'1.235'
>>> format_decimal(-1.2346, locale='en_US')
u'-1.235'
>>> format_decimal(1.2345, locale='sv_SE')
u'1,234'
>>> format_decimal(12345, locale='de')
u'12.345'
The appropriate thousands grouping and the decimal separator are used
for each locale::
>>> format_decimal(12345.5, locale='en_US')
u'12,345.5'
:param number:
The number to format.
:param format:
Notation format.
:returns:
The formatted decimal number.
"""
return numbers.format_decimal(number, format=format,
locale=self.locale)
def format_currency(self, number, currency, format=None):
"""Returns a formatted currency value. Example::
>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'US$\\xa01.099,98'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\\xa0\\u20ac'
The pattern can also be specified explicitly::
>>> format_currency(1099.98, 'EUR', u'\\xa4\\xa4 #,##0.00',
... locale='en_US')
u'EUR 1,099.98'
:param number:
The number to format.
:param currency:
The currency code.
:param format:
Notation format.
:returns:
The formatted currency value.
"""
return numbers.format_currency(number, currency, format=format,
locale=self.locale)
def format_percent(self, number, format=None):
"""Returns formatted percent value for the current locale. Example::
>>> format_percent(0.34, locale='en_US')
u'34%'
>>> format_percent(25.1234, locale='en_US')
u'2,512%'
>>> format_percent(25.1234, locale='sv_SE')
u'2\\xa0512\\xa0%'
The format pattern can also be specified explicitly::
>>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
u'25,123\u2030'
:param number:
The percent number to format
:param format:
Notation format.
:returns:
The formatted percent number.
"""
return numbers.format_percent(number, format=format,
locale=self.locale)
def format_scientific(self, number, format=None):
"""Returns value formatted in scientific notation for the current
locale. Example::
>>> format_scientific(10000, locale='en_US')
u'1E4'
The format pattern can also be specified explicitly::
>>> format_scientific(1234567, u'##0E00', locale='en_US')
u'1.23E06'
:param number:
The number to format.
:param format:
Notation format.
:returns:
Value formatted in scientific notation.
"""
return numbers.format_scientific(number, format=format,
locale=self.locale)
def parse_date(self, string):
"""Parses a date from a string.
This function uses the date format for the locale as a hint to
determine the order in which the date fields appear in the string.
Example::
>>> parse_date('4/1/04', locale='en_US')
datetime.date(2004, 4, 1)
>>> parse_date('01.04.2004', locale='de_DE')
datetime.date(2004, 4, 1)
:param string:
The string containing the date.
:returns:
The parsed date object.
"""
return dates.parse_date(string, locale=self.locale)
def parse_datetime(self, string):
"""Parses a date and time from a string.
This function uses the date and time formats for the locale as a hint
to determine the order in which the time fields appear in the string.
:param string:
The string containing the date and time.
:returns:
The parsed datetime object.
"""
return dates.parse_datetime(string, locale=self.locale)
def parse_time(self, string):
"""Parses a time from a string.
This function uses the time format for the locale as a hint to
determine the order in which the time fields appear in the string.
Example::
>>> parse_time('15:30:00', locale='en_US')
datetime.time(15, 30)
:param string:
The string containing the time.
:returns:
The parsed time object.
"""
return dates.parse_time(string, locale=self.locale)
def parse_number(self, string):
"""Parses localized number string into a long integer. Example::
>>> parse_number('1,099', locale='en_US')
1099L
>>> parse_number('1.099', locale='de_DE')
1099L
When the given string cannot be parsed, an exception is raised::
>>> parse_number('1.099,98', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '1.099,98' is not a valid number
:param string:
The string to parse.
:returns:
The parsed number.
:raises:
``NumberFormatError`` if the string can not be converted to a
number.
"""
return numbers.parse_number(string, locale=self.locale)
def parse_decimal(self, string):
"""Parses localized decimal string into a float. Example::
>>> parse_decimal('1,099.98', locale='en_US')
1099.98
>>> parse_decimal('1.099,98', locale='de')
1099.98
When the given string cannot be parsed, an exception is raised::
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
:param string:
The string to parse.
:returns:
The parsed decimal number.
:raises:
``NumberFormatError`` if the string can not be converted to a
decimal number.
"""
return numbers.parse_decimal(string, locale=self.locale)
def get_timezone_location(self, dt_or_tzinfo):
"""Returns a representation of the given timezone using "location
format".
The result depends on both the local display name of the country and
the city assocaited with the time zone::
>>> from pytz import timezone
>>> tz = timezone('America/St_Johns')
>>> get_timezone_location(tz, locale='de_DE')
u"Kanada (St. John's)"
>>> tz = timezone('America/Mexico_City')
>>> get_timezone_location(tz, locale='de_DE')
u'Mexiko (Mexiko-Stadt)'
If the timezone is associated with a country that uses only a single
timezone, just the localized country name is returned::
>>> tz = timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Deutschland'
:param dt_or_tzinfo:
The ``datetime`` or ``tzinfo`` object that determines
the timezone; if None, the current date and time in UTC is assumed.
:returns:
The localized timezone name using location format.
"""
return dates.get_timezone_name(dt_or_tzinfo, locale=self.locale)
def gettext(string, **variables):
"""See :meth:`I18n.gettext`."""
return get_i18n().gettext(string, **variables)
def ngettext(singular, plural, n, **variables):
"""See :meth:`I18n.ngettext`."""
return get_i18n().ngettext(singular, plural, n, **variables)
def to_local_timezone(datetime):
"""See :meth:`I18n.to_local_timezone`."""
return get_i18n().to_local_timezone(datetime)
def to_utc(datetime):
"""See :meth:`I18n.to_utc`."""
return get_i18n().to_utc(datetime)
def format_date(date=None, format=None, rebase=True):
"""See :meth:`I18n.format_date`."""
return get_i18n().format_date(date, format, rebase)
def format_datetime(datetime=None, format=None, rebase=True):
"""See :meth:`I18n.format_datetime`."""
return get_i18n().format_datetime(datetime, format, rebase)
def format_time(time=None, format=None, rebase=True):
"""See :meth:`I18n.format_time`."""
return get_i18n().format_time(time, format, rebase)
def format_timedelta(datetime_or_timedelta, granularity='second',
threshold=.85):
"""See :meth:`I18n.format_timedelta`."""
return get_i18n().format_timedelta(datetime_or_timedelta,
granularity, threshold)
def format_number(number):
"""See :meth:`I18n.format_number`."""
return get_i18n().format_number(number)
def format_decimal(number, format=None):
"""See :meth:`I18n.format_decimal`."""
return get_i18n().format_decimal(number, format)
def format_currency(number, currency, format=None):
"""See :meth:`I18n.format_currency`."""
return get_i18n().format_currency(number, currency, format)
def format_percent(number, format=None):
"""See :meth:`I18n.format_percent`."""
return get_i18n().format_percent(number, format)
def format_scientific(number, format=None):
"""See :meth:`I18n.format_scientific`."""
return get_i18n().format_scientific(number, format)
def parse_date(string):
"""See :meth:`I18n.parse_date`"""
return get_i18n().parse_date(string)
def parse_datetime(string):
"""See :meth:`I18n.parse_datetime`."""
return get_i18n().parse_datetime(string)
def parse_time(string):
"""See :meth:`I18n.parse_time`."""
return get_i18n().parse_time(string)
def parse_number(string):
"""See :meth:`I18n.parse_number`."""
return get_i18n().parse_number(string)
def parse_decimal(string):
"""See :meth:`I18n.parse_decimal`."""
return get_i18n().parse_decimal(string)
def get_timezone_location(dt_or_tzinfo):
"""See :meth:`I18n.get_timezone_location`."""
return get_i18n().get_timezone_location(dt_or_tzinfo)
def lazy_gettext(string, **variables):
"""A lazy version of :func:`gettext`.
:param string:
The string to be translated.
:param variables:
Variables to format the returned string.
:returns:
A ``babel.support.LazyProxy`` object that when accessed translates
the string.
"""
return support.LazyProxy(gettext, string, **variables)
# Aliases.
_ = gettext
_lazy = lazy_gettext
# Factories -------------------------------------------------------------------
#: Key used to store :class:`I18nStore` in the app registry.
_store_registry_key = 'webapp2_extras.i18n.I18nStore'
#: Key used to store :class:`I18n` in the request registry.
_i18n_registry_key = 'webapp2_extras.i18n.I18n'
def get_store(factory=I18nStore, key=_store_registry_key, app=None):
"""Returns an instance of :class:`I18nStore` from the app registry.
It'll try to get it from the current app registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`I18nStore` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param app:
A :class:`webapp2.WSGIApplication` instance used to store the instance.
The active app is used if it is not set.
"""
app = app or webapp2.get_app()
store = app.registry.get(key)
if not store:
store = app.registry[key] = factory(app)
return store
def set_store(store, key=_store_registry_key, app=None):
"""Sets an instance of :class:`I18nStore` in the app registry.
:param store:
An instance of :class:`I18nStore`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.WSGIApplication` instance used to retrieve the
instance. The active app is used if it is not set.
"""
app = app or webapp2.get_app()
app.registry[key] = store
def get_i18n(factory=I18n, key=_i18n_registry_key, request=None):
"""Returns an instance of :class:`I18n` from the request registry.
It'll try to get it from the current request registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`I18n` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param request:
A :class:`webapp2.Request` instance used to store the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
i18n = request.registry.get(key)
if not i18n:
i18n = request.registry[key] = factory(request)
return i18n
def set_i18n(i18n, key=_i18n_registry_key, request=None):
"""Sets an instance of :class:`I18n` in the request registry.
:param store:
An instance of :class:`I18n`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.Request` instance used to retrieve the instance. The
active request is used if it is not set.
"""
request = request or webapp2.get_request()
request.registry[key] = i18n
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.sessions_memcache
================================
Extended sessions stored in memcache.
App Engine-specific modules were moved to webapp2_extras.appengine.
This module is here for compatibility purposes.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
import warnings
warnings.warn(DeprecationWarning(
'webapp2_extras.sessions_memcache is deprecated. '
'App Engine-specific modules were moved to webapp2_extras.appengine.'),
stacklevel=1)
from webapp2_extras.appengine.sessions_memcache import *
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.mako
===================
Mako template support for webapp2.
Learn more about Mako: http://www.makotemplates.org/
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import absolute_import
from mako import lookup
import webapp2
#: Default configuration values for this module. Keys are:
#:
#: template_path
#: Directory for templates. Default is `templates`.
default_config = {
'template_path': 'templates',
}
class Mako(object):
"""Wrapper for configurable and cached Mako environment.
To used it, set it as a cached property in a base `RequestHandler`::
import webapp2
from webapp2_extras import mako
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def mako(self):
# Returns a Mako renderer cached in the app registry.
return mako.get_mako(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.mako.render_template(_template, **context)
self.response.write(rv)
Then extended handlers can render templates directly::
class MyHandler(BaseHandler):
def get(self):
context = {'message': 'Hello, world!'}
self.render_response('my_template.html', **context)
"""
#: Configuration key.
config_key = __name__
#: Loaded configuration.
config = None
def __init__(self, app, config=None):
self.config = config = app.config.load_config(self.config_key,
default_values=default_config, user_values=config,
required_keys=None)
directories = config.get('template_path')
if isinstance(directories, basestring):
directories = [directories]
self.environment = lookup.TemplateLookup(directories=directories,
output_encoding='utf-8',
encoding_errors='replace')
def render_template(self, _filename, **context):
"""Renders a template and returns a response object.
:param _filename:
The template filename, related to the templates directory.
:param context:
Keyword arguments used as variables in the rendered template.
These will override values set in the request context.
:returns:
A rendered template.
"""
template = self.environment.get_template(_filename)
return template.render_unicode(**context)
# Factories -------------------------------------------------------------------
#: Key used to store :class:`Mako` in the app registry.
_registry_key = 'webapp2_extras.mako.Mako'
def get_mako(factory=Mako, key=_registry_key, app=None):
"""Returns an instance of :class:`Mako` from the app registry.
It'll try to get it from the current app registry, and if it is not
registered it'll be instantiated and registered. A second call to this
function will return the same instance.
:param factory:
The callable used to build and register the instance if it is not yet
registered. The default is the class :class:`Mako` itself.
:param key:
The key used to store the instance in the registry. A default is used
if it is not set.
:param app:
A :class:`webapp2.WSGIApplication` instance used to store the instance.
The active app is used if it is not set.
"""
app = app or webapp2.get_app()
mako = app.registry.get(key)
if not mako:
mako = app.registry[key] = factory(app)
return mako
def set_mako(mako, key=_registry_key, app=None):
"""Sets an instance of :class:`Mako` in the app registry.
:param store:
An instance of :class:`Mako`.
:param key:
The key used to retrieve the instance from the registry. A default
is used if it is not set.
:param request:
A :class:`webapp2.WSGIApplication` instance used to retrieve the
instance. The active app is used if it is not set.
"""
app = app or webapp2.get_app()
app.registry[key] = mako
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.security
=======================
Security related helpers such as secure password hashing tools and a
random token generator.
:copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
:copyright: (c) 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import division
import hashlib
import hmac
import math
import random
import string
import webapp2
_rng = random.SystemRandom()
HEXADECIMAL_DIGITS = string.digits + 'abcdef'
DIGITS = string.digits
LOWERCASE_ALPHA = string.lowercase
UPPERCASE_ALPHA = string.uppercase
LOWERCASE_ALPHANUMERIC = string.lowercase + string.digits
UPPERCASE_ALPHANUMERIC = string.uppercase + string.digits
ALPHA = string.letters
ALPHANUMERIC = string.letters + string.digits
ASCII_PRINTABLE = string.letters + string.digits + string.punctuation
ALL_PRINTABLE = string.printable
PUNCTUATION = string.punctuation
def generate_random_string(length=None, entropy=None, pool=ALPHANUMERIC):
"""Generates a random string using the given sequence pool.
To generate stronger passwords, use ASCII_PRINTABLE as pool.
Entropy is:
H = log2(N**L)
where:
- H is the entropy in bits.
- N is the possible symbol count
- L is length of string of symbols
Entropy chart::
-----------------------------------------------------------------
Symbol set Symbol Count (N) Entropy per symbol (H)
-----------------------------------------------------------------
HEXADECIMAL_DIGITS 16 4.0000 bits
DIGITS 10 3.3219 bits
LOWERCASE_ALPHA 26 4.7004 bits
UPPERCASE_ALPHA 26 4.7004 bits
PUNCTUATION 32 5.0000 bits
LOWERCASE_ALPHANUMERIC 36 5.1699 bits
UPPERCASE_ALPHANUMERIC 36 5.1699 bits
ALPHA 52 5.7004 bits
ALPHANUMERIC 62 5.9542 bits
ASCII_PRINTABLE 94 6.5546 bits
ALL_PRINTABLE 100 6.6438 bits
:param length:
The length of the random sequence. Use this or `entropy`, not both.
:param entropy:
Desired entropy in bits. Use this or `length`, not both.
Use this to generate passwords based on entropy:
http://en.wikipedia.org/wiki/Password_strength
:param pool:
A sequence of characters from which random characters are chosen.
Default to case-sensitive alpha-numeric characters.
:returns:
A string with characters randomly chosen from the pool.
"""
pool = list(set(pool))
if length and entropy:
raise ValueError('Use length or entropy, not both.')
if length <= 0 and entropy <= 0:
raise ValueError('Length or entropy must be greater than 0.')
if entropy:
log_of_2 = 0.6931471805599453
length = long(math.ceil((log_of_2 / math.log(len(pool))) * entropy))
return ''.join(_rng.choice(pool) for _ in xrange(length))
def generate_password_hash(password, method='sha1', length=22, pepper=None):
"""Hashes a password.
The format of the string returned includes the method that was used
so that :func:`check_password_hash` can check the hash.
This method can **not** generate unsalted passwords but it is possible
to set the method to plain to enforce plaintext passwords. If a salt
is used, hmac is used internally to salt the password.
:param password:
The password to hash.
:param method:
The hash method to use (``'md5'`` or ``'sha1'``).
:param length:
Length of the salt to be created.
:param pepper:
A secret constant stored in the application code.
:returns:
A formatted hashed string that looks like this::
method$salt$hash
This function was ported and adapted from `Werkzeug`_.
"""
salt = method != 'plain' and generate_random_string(length) or ''
hashval = hash_password(password, method, salt, pepper)
if hashval is None:
raise TypeError('Invalid method %r.' % method)
return '%s$%s$%s' % (hashval, method, salt)
def check_password_hash(password, pwhash, pepper=None):
"""Checks a password against a given salted and hashed password value.
In order to support unsalted legacy passwords this method supports
plain text passwords, md5 and sha1 hashes (both salted and unsalted).
:param password:
The plaintext password to compare against the hash.
:param pwhash:
A hashed string like returned by :func:`generate_password_hash`.
:param pepper:
A secret constant stored in the application code.
:returns:
`True` if the password matched, `False` otherwise.
This function was ported and adapted from `Werkzeug`_.
"""
if pwhash.count('$') < 2:
return False
hashval, method, salt = pwhash.split('$', 2)
return hash_password(password, method, salt, pepper) == hashval
def hash_password(password, method, salt=None, pepper=None):
"""Hashes a password.
Supports plaintext without salt, unsalted and salted passwords. In case
salted passwords are used hmac is used.
:param password:
The password to be hashed.
:param method:
A method from ``hashlib``, e.g., `sha1` or `md5`, or `plain`.
:param salt:
A random salt string.
:param pepper:
A secret constant stored in the application code.
:returns:
A hashed password.
This function was ported and adapted from `Werkzeug`_.
"""
password = webapp2._to_utf8(password)
if method == 'plain':
return password
method = getattr(hashlib, method, None)
if not method:
return None
if salt:
h = hmac.new(webapp2._to_utf8(salt), password, method)
else:
h = method(password)
if pepper:
h = hmac.new(webapp2._to_utf8(pepper), h.hexdigest(), method)
return h.hexdigest()
def compare_hashes(a, b):
"""Checks if two hash strings are identical.
The intention is to make the running time be less dependant on the size of
the string.
:param a:
String 1.
:param b:
String 2.
:returns:
True if both strings are equal, False otherwise.
"""
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
# Old names.
create_token = generate_random_string
create_password_hash = generate_password_hash
| Python |
# -*- coding: utf-8 -*-
"""
webapp2_extras.config
=====================
Configuration object for webapp2.
This module is deprecated. See :class:`webapp2.WSGIApplication.config`.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import absolute_import
import warnings
import webapp2
warnings.warn(DeprecationWarning(
'webapp2_extras.config is deprecated. '
'The WSGIApplication uses webapp2.Config instead.'),
stacklevel=1)
#: Value used for missing default values.
DEFAULT_VALUE = object()
#: Value used for required values.
REQUIRED_VALUE = object()
class Config(dict):
"""A simple configuration dictionary keyed by module name. This is a
dictionary of dictionaries. It requires all values to be dictionaries
and applies updates and default values to the inner dictionaries instead
of the first level one.
The configuration object can be set as a ``config`` attribute of
:class:`WSGIApplication`::
import webapp2
from webapp2_extras import config as webapp2_config
my_config = {}
my_config['my.module'] = {
'foo': 'bar',
}
app = webapp2.WSGIApplication(routes=[
webapp2.Route('/', name='home', handler=MyHandler)
])
app.config = webapp2_config.Config(my_config)
Then to read configuration values, get them from the app::
class MyHandler(RequestHandler):
def get(self):
foo = self.app.config['my.module']['foo']
# ...
"""
#: Loaded module configurations.
loaded = None
def __init__(self, values=None, defaults=None):
"""Initializes the configuration object.
:param values:
A dictionary of configuration dictionaries for modules.
:param defaults:
A dictionary of configuration dictionaries for initial default
values. These modules are marked as loaded.
"""
self.loaded = []
if values is not None:
assert isinstance(values, dict)
for module, config in values.iteritems():
self.update(module, config)
if defaults is not None:
assert isinstance(defaults, dict)
for module, config in defaults.iteritems():
self.setdefault(module, config)
self.loaded.append(module)
def __getitem__(self, module):
"""Returns the configuration for a module. If it is not already
set, loads a ``default_config`` variable from the given module and
updates the configuration with those default values
Every module that allows some kind of configuration sets a
``default_config`` global variable that is loaded by this function,
cached and used in case the requested configuration was not defined
by the user.
:param module:
The module name.
:returns:
A configuration value.
"""
if module not in self.loaded:
# Load default configuration and update config.
values = webapp2.import_string(module + '.default_config',
silent=True)
if values:
self.setdefault(module, values)
self.loaded.append(module)
try:
return dict.__getitem__(self, module)
except KeyError:
raise KeyError('Module %r is not configured.' % module)
def __setitem__(self, module, values):
"""Sets a configuration for a module, requiring it to be a dictionary.
:param module:
A module name for the configuration, e.g.: `webapp2.ext.i18n`.
:param values:
A dictionary of configurations for the module.
"""
assert isinstance(values, dict), 'Module configuration must be a dict.'
dict.__setitem__(self, module, SubConfig(module, values))
def get(self, module, default=DEFAULT_VALUE):
"""Returns a configuration for a module. If default is not provided,
returns an empty dict if the module is not configured.
:param module:
The module name.
:params default:
Default value to return if the module is not configured. If not
set, returns an empty dict.
:returns:
A module configuration.
"""
if default is DEFAULT_VALUE:
default = {}
return dict.get(self, module, default)
def setdefault(self, module, values):
"""Sets a default configuration dictionary for a module.
:param module:
The module to set default configuration, e.g.: `webapp2.ext.i18n`.
:param values:
A dictionary of configurations for the module.
:returns:
The module configuration dictionary.
"""
assert isinstance(values, dict), 'Module configuration must be a dict.'
if module not in self:
dict.__setitem__(self, module, SubConfig(module))
module_dict = dict.__getitem__(self, module)
for key, value in values.iteritems():
module_dict.setdefault(key, value)
return module_dict
def update(self, module, values):
"""Updates the configuration dictionary for a module.
:param module:
The module to update the configuration, e.g.: `webapp2.ext.i18n`.
:param values:
A dictionary of configurations for the module.
"""
assert isinstance(values, dict), 'Module configuration must be a dict.'
if module not in self:
dict.__setitem__(self, module, SubConfig(module))
dict.__getitem__(self, module).update(values)
def get_config(self, module, key=None, default=REQUIRED_VALUE):
"""Returns a configuration value for a module and optionally a key.
Will raise a KeyError if they the module is not configured or the key
doesn't exist and a default is not provided.
:param module:
The module name.
:params key:
The configuration key.
:param default:
Default value to return if the key doesn't exist.
:returns:
A module configuration.
"""
module_dict = self.__getitem__(module)
if key is None:
return module_dict
return module_dict.get(key, default)
class SubConfig(dict):
def __init__(self, module, values=None):
dict.__init__(self, values or ())
self.module = module
def __getitem__(self, key):
try:
value = dict.__getitem__(self, key)
except KeyError:
raise KeyError('Module %r does not have the config key %r' %
(self.module, key))
if value is REQUIRED_VALUE:
raise KeyError('Module %r requires the config key %r to be '
'set.' % (self.module, key))
return value
def get(self, key, default=None):
if key not in self:
value = default
else:
value = dict.__getitem__(self, key)
if value is REQUIRED_VALUE:
raise KeyError('Module %r requires the config key %r to be '
'set.' % (self.module, key))
return value
| Python |
# -*- coding: utf-8 -*-
import os
import webapp2
from webapp2_extras import jinja2
import test_base
current_dir = os.path.abspath(os.path.dirname(__file__))
template_path = os.path.join(current_dir, 'resources', 'jinja2_templates')
compiled_path = os.path.join(current_dir, 'resources',
'jinja2_templates_compiled')
class TestJinja2(test_base.BaseTestCase):
def test_render_template_with_i18n(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.jinja2': {
'template_path': template_path,
'environment_args': {
'autoescape': True,
'extensions': [
'jinja2.ext.autoescape',
'jinja2.ext.with_',
'jinja2.ext.i18n',
],
},
},
})
req = webapp2.Request.blank('/')
app.set_globals(app=app, request=req)
j = jinja2.Jinja2(app)
message = 'Hello, i18n World!'
res = j.render_template('template2.html', message=message)
self.assertEqual(res, message)
def test_render_template_globals_filters(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.jinja2': {
'template_path': template_path,
'globals': dict(foo='fooglobal'),
'filters': dict(foo=lambda x: x + '-foofilter'),
},
})
req = webapp2.Request.blank('/')
app.set_globals(app=app, request=req)
j = jinja2.Jinja2(app)
message = 'fooglobal-foofilter'
res = j.render_template('template3.html', message=message)
self.assertEqual(res, message)
def test_render_template_force_compiled(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.jinja2': {
'template_path': template_path,
'compiled_path': compiled_path,
'force_compiled': True,
}
})
req = webapp2.Request.blank('/')
app.set_globals(app=app, request=req)
j = jinja2.Jinja2(app)
message = 'Hello, World!'
res = j.render_template('template1.html', message=message)
self.assertEqual(res, message)
def test_get_template_attribute(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.jinja2': {
'template_path': template_path,
}
})
j = jinja2.Jinja2(app)
hello = j.get_template_attribute('hello.html', 'hello')
self.assertEqual(hello('World'), 'Hello, World!')
def test_set_jinja2(self):
app = webapp2.WSGIApplication()
self.assertEqual(len(app.registry), 0)
jinja2.set_jinja2(jinja2.Jinja2(app), app=app)
self.assertEqual(len(app.registry), 1)
j = jinja2.get_jinja2(app=app)
self.assertTrue(isinstance(j, jinja2.Jinja2))
def test_get_jinja2(self):
app = webapp2.WSGIApplication()
self.assertEqual(len(app.registry), 0)
j = jinja2.get_jinja2(app=app)
self.assertEqual(len(app.registry), 1)
self.assertTrue(isinstance(j, jinja2.Jinja2))
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
from google.appengine.api import datastore_errors
from google.appengine.api import memcache
import webapp2
from webapp2_extras import sessions
from webapp2_extras import sessions_ndb
import test_base
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'my-super-secret',
},
})
class TestNdbSession(test_base.BaseTestCase):
#factory = sessions_ndb.DatastoreSessionFactory
def setUp(self):
super(TestNdbSession, self).setUp()
self.register_model('Session', sessions_ndb.Session)
def test_get_save_session(self):
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
rsp = webapp2.Response()
# Nothing changed, we want to test anyway.
store.save_sessions(rsp)
session['a'] = 'b'
session['c'] = 'd'
session['e'] = 'f'
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
session['g'] = 'h'
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 3 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
self.assertEqual(session['g'], 'h')
# Round 4 -------------------------------------------------------------
# For this attempt we don't want the memcache backup.
sid = session.container.sid
memcache.delete(sid)
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
self.assertEqual(session['g'], 'h')
def test_flashes(self):
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
flashes = session.get_flashes()
self.assertEqual(flashes, [])
session.add_flash('foo')
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
flashes = session.get_flashes()
self.assertEqual(flashes, [(u'foo', None)])
flashes = session.get_flashes()
self.assertEqual(flashes, [])
session.add_flash('bar')
session.add_flash('baz', 'important')
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 3 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
flashes = session.get_flashes()
self.assertEqual(flashes, [(u'bar', None), (u'baz', 'important')])
flashes = session.get_flashes()
self.assertEqual(flashes, [])
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 4 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='datastore')
flashes = session.get_flashes()
self.assertEqual(flashes, [])
def test_misc(self):
s = sessions_ndb.Session(id='foo')
key = s.put()
s = key.get()
self.assertEqual(s.data, None)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webapp2
from webapp2_extras import config as app_config
import test_base
class TestConfig(test_base.BaseTestCase):
def tearDown(self):
pass
def test_get(self):
config = app_config.Config({'foo': {
'bar': 'baz',
'doo': 'ding',
}})
self.assertEqual(config.get('foo'), {
'bar': 'baz',
'doo': 'ding',
})
self.assertEqual(config.get('bar'), {})
def test_get_existing_keys(self):
config = app_config.Config({'foo': {
'bar': 'baz',
'doo': 'ding',
}})
self.assertEqual(config.get_config('foo', 'bar'), 'baz')
self.assertEqual(config.get_config('foo', 'doo'), 'ding')
def test_get_existing_keys_from_default(self):
config = app_config.Config({}, {'foo': {
'bar': 'baz',
'doo': 'ding',
}})
self.assertEqual(config.get_config('foo', 'bar'), 'baz')
self.assertEqual(config.get_config('foo', 'doo'), 'ding')
def test_get_non_existing_keys(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'foo', 'bar')
def test_get_dict_existing_keys(self):
config = app_config.Config({'foo': {
'bar': 'baz',
'doo': 'ding',
}})
self.assertEqual(config.get_config('foo'), {
'bar': 'baz',
'doo': 'ding',
})
def test_get_dict_non_existing_keys(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'bar')
def test_get_with_default(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'foo', 'bar', 'ooops')
self.assertRaises(KeyError, config.get_config, 'foo', 'doo', 'wooo')
def test_get_with_default_and_none(self):
config = app_config.Config({'foo': {
'bar': None,
}})
self.assertEqual(config.get_config('foo', 'bar', 'ooops'), None)
def test_update(self):
config = app_config.Config({'foo': {
'bar': 'baz',
'doo': 'ding',
}})
self.assertEqual(config.get_config('foo', 'bar'), 'baz')
self.assertEqual(config.get_config('foo', 'doo'), 'ding')
config.update('foo', {'bar': 'other'})
self.assertEqual(config.get_config('foo', 'bar'), 'other')
self.assertEqual(config.get_config('foo', 'doo'), 'ding')
def test_setdefault(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'foo')
config.setdefault('foo', {
'bar': 'baz',
'doo': 'ding',
})
self.assertEqual(config.get_config('foo', 'bar'), 'baz')
self.assertEqual(config.get_config('foo', 'doo'), 'ding')
def test_setdefault2(self):
config = app_config.Config({'foo': {
'bar': 'baz',
}})
self.assertEqual(config.get_config('foo'), {
'bar': 'baz',
})
config.setdefault('foo', {
'bar': 'wooo',
'doo': 'ding',
})
self.assertEqual(config.get_config('foo', 'bar'), 'baz')
self.assertEqual(config.get_config('foo', 'doo'), 'ding')
def test_setitem(self):
config = app_config.Config()
config['foo'] = {'bar': 'baz'}
self.assertEqual(config, {'foo': {'bar': 'baz'}})
self.assertEqual(config['foo'], {'bar': 'baz'})
def test_init_no_dict_values(self):
self.assertRaises(AssertionError, app_config.Config, {'foo': 'bar'})
self.assertRaises(AssertionError, app_config.Config, {'foo': None})
self.assertRaises(AssertionError, app_config.Config, 'foo')
def test_init_no_dict_default(self):
self.assertRaises(AssertionError, app_config.Config, {}, {'foo': 'bar'})
self.assertRaises(AssertionError, app_config.Config, {}, {'foo': None})
self.assertRaises(AssertionError, app_config.Config, {}, 'foo')
def test_update_no_dict_values(self):
config = app_config.Config()
self.assertRaises(AssertionError, config.update, {'foo': 'bar'}, 'baz')
self.assertRaises(AssertionError, config.update, {'foo': None}, 'baz')
self.assertRaises(AssertionError, config.update, 'foo', 'bar')
def test_setdefault_no_dict_values(self):
config = app_config.Config()
self.assertRaises(AssertionError, config.setdefault, 'foo', 'bar')
self.assertRaises(AssertionError, config.setdefault, 'foo', None)
def test_setitem_no_dict_values(self):
config = app_config.Config()
def setitem(key, value):
config[key] = value
return config
self.assertRaises(AssertionError, setitem, 'foo', 'bar')
self.assertRaises(AssertionError, setitem, 'foo', None)
class TestLoadConfig(test_base.BaseTestCase):
def tearDown(self):
pass
def test_default_config(self):
config = app_config.Config()
from resources.template import default_config as template_config
from resources.i18n import default_config as i18n_config
self.assertEqual(config.get_config('resources.template', 'templates_dir'), template_config['templates_dir'])
self.assertEqual(config.get_config('resources.i18n', 'locale'), i18n_config['locale'])
self.assertEqual(config.get_config('resources.i18n', 'timezone'), i18n_config['timezone'])
def test_default_config_with_non_existing_key(self):
config = app_config.Config()
from resources.i18n import default_config as i18n_config
# In the first time the module config will be loaded normally.
self.assertEqual(config.get_config('resources.i18n', 'locale'), i18n_config['locale'])
# In the second time it won't be loaded, but won't find the value and then use the default.
self.assertEqual(config.get_config('resources.i18n', 'i_dont_exist', 'foo'), 'foo')
def test_override_config(self):
config = app_config.Config({
'resources.template': {
'templates_dir': 'apps/templates'
},
'resources.i18n': {
'locale': 'pt_BR',
'timezone': 'America/Sao_Paulo',
},
})
self.assertEqual(config.get_config('resources.template', 'templates_dir'), 'apps/templates')
self.assertEqual(config.get_config('resources.i18n', 'locale'), 'pt_BR')
self.assertEqual(config.get_config('resources.i18n', 'timezone'), 'America/Sao_Paulo')
def test_override_config2(self):
config = app_config.Config({
'resources.i18n': {
'timezone': 'America/Sao_Paulo',
},
})
self.assertEqual(config.get_config('resources.i18n', 'locale'), 'en_US')
self.assertEqual(config.get_config('resources.i18n', 'timezone'), 'America/Sao_Paulo')
def test_get(self):
config = app_config.Config({'foo': {
'bar': 'baz',
}})
self.assertEqual(config.get_config('foo', 'bar'), 'baz')
def test_get_with_default(self):
config = app_config.Config()
self.assertEqual(config.get_config('resources.i18n', 'bar', 'baz'), 'baz')
def test_get_with_default_and_none(self):
config = app_config.Config({'foo': {
'bar': None,
}})
self.assertEqual(config.get_config('foo', 'bar', 'ooops'), None)
def test_get_with_default_and_module_load(self):
config = app_config.Config()
self.assertEqual(config.get_config('resources.i18n', 'locale'), 'en_US')
self.assertEqual(config.get_config('resources.i18n', 'locale', 'foo'), 'en_US')
def test_required_config(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'resources.i18n', 'foo')
def test_missing_module(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'i_dont_exist', 'i_dont_exist')
def test_missing_module2(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'i_dont_exist')
def test_missing_key(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'resources.i18n', 'i_dont_exist')
def test_missing_default_config(self):
config = app_config.Config()
self.assertRaises(KeyError, config.get_config, 'tipfy', 'foo')
class TestLoadConfigGetItem(test_base.BaseTestCase):
def tearDown(self):
pass
def test_default_config(self):
config = app_config.Config()
from resources.template import default_config as template_config
from resources.i18n import default_config as i18n_config
self.assertEqual(config['resources.template']['templates_dir'], template_config['templates_dir'])
self.assertEqual(config['resources.i18n']['locale'], i18n_config['locale'])
self.assertEqual(config['resources.i18n']['timezone'], i18n_config['timezone'])
def test_default_config_with_non_existing_key(self):
config = app_config.Config()
from resources.i18n import default_config as i18n_config
# In the first time the module config will be loaded normally.
self.assertEqual(config['resources.i18n']['locale'], i18n_config['locale'])
# In the second time it won't be loaded, but won't find the value and then use the default.
self.assertEqual(config['resources.i18n'].get('i_dont_exist', 'foo'), 'foo')
def test_override_config(self):
config = app_config.Config({
'resources.template': {
'templates_dir': 'apps/templates'
},
'resources.i18n': {
'locale': 'pt_BR',
'timezone': 'America/Sao_Paulo',
},
})
self.assertEqual(config['resources.template']['templates_dir'], 'apps/templates')
self.assertEqual(config['resources.i18n']['locale'], 'pt_BR')
self.assertEqual(config['resources.i18n']['timezone'], 'America/Sao_Paulo')
def test_override_config2(self):
config = app_config.Config({
'resources.i18n': {
'timezone': 'America/Sao_Paulo',
},
})
self.assertEqual(config['resources.i18n']['locale'], 'en_US')
self.assertEqual(config['resources.i18n']['timezone'], 'America/Sao_Paulo')
def test_get(self):
config = app_config.Config({'foo': {
'bar': 'baz',
}})
self.assertEqual(config['foo']['bar'], 'baz')
def test_get_with_default(self):
config = app_config.Config()
self.assertEqual(config['resources.i18n'].get('bar', 'baz'), 'baz')
def test_get_with_default_and_none(self):
config = app_config.Config({'foo': {
'bar': None,
}})
self.assertEqual(config['foo'].get('bar', 'ooops'), None)
def test_get_with_default_and_module_load(self):
config = app_config.Config()
self.assertEqual(config['resources.i18n']['locale'], 'en_US')
self.assertEqual(config['resources.i18n'].get('locale', 'foo'), 'en_US')
def test_required_config(self):
config = app_config.Config()
self.assertRaises(KeyError, config['resources.i18n'].__getitem__, 'foo')
self.assertRaises(KeyError, config['resources.i18n'].__getitem__, 'required')
def test_missing_module(self):
config = app_config.Config()
self.assertRaises(KeyError, config.__getitem__, 'i_dont_exist')
def test_missing_key(self):
config = app_config.Config()
self.assertRaises(KeyError, config['resources.i18n'].__getitem__, 'i_dont_exist')
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webapp2
from webapp2_extras import local_app
import test_base
class TestLocalApp(test_base.BaseTestCase):
def test_dispatch(self):
def hello_handler(request, *args, **kwargs):
return webapp2.Response('Hello, World!')
app = local_app.WSGIApplication([('/', hello_handler)])
rsp = app.get_response('/')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, World!')
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import base64
from webapp2_extras import xsrf
import test_base
class TestXSRFToken(test_base.BaseTestCase):
def test_verify_timeout(self):
token = xsrf.XSRFToken('user@example.com',
'secret',
current_time=1354160000)
token_string = token.generate_token_string()
token.verify_token_string(token_string,
timeout=10,
current_time=1354160010)
self.assertRaises(xsrf.XSRFTokenExpiredException,
token.verify_token_string,
token_string,
timeout=10,
current_time=1354160011)
def test_verify_no_action(self):
token = xsrf.XSRFToken('user@example.com',
'secret',
current_time=1354160000)
token_string = token.generate_token_string()
token.verify_token_string(token_string)
self.assertRaises(
xsrf.XSRFTokenInvalid,
token.verify_token_string,
xsrf.XSRFToken('user@example.com',
'differentsecret',
current_time=1354160000).generate_token_string())
self.assertRaises(
xsrf.XSRFTokenInvalid,
token.verify_token_string,
xsrf.XSRFToken('user@example.com',
'secret',
current_time=1354160000).generate_token_string(
'action'))
def test_verify_action(self):
token = xsrf.XSRFToken('user@example.com',
'secret',
current_time=1354160000)
token_string = token.generate_token_string('action')
token.verify_token_string(token_string, 'action')
self.assertRaises(
xsrf.XSRFTokenInvalid,
token.verify_token_string,
xsrf.XSRFToken('user@example.com',
'differentsecret',
current_time=1354160000).generate_token_string())
def test_verify_substring(self):
"""Tests that a substring of the correct token fails to verify."""
token = xsrf.XSRFToken('user@example.com',
'secret',
current_time=1354160000)
token_string = token.generate_token_string()
test_token, test_time = base64.urlsafe_b64decode(token_string).split('|')
test_string = base64.urlsafe_b64encode('|'.join([test_token[:-1],
test_time]))
self.assertRaises(xsrf.XSRFTokenInvalid,
token.verify_token_string,
test_string)
def test_verify_bad_base_64(self):
token = xsrf.XSRFToken('user@example.com',
'secret')
self.assertRaises(
xsrf.XSRFTokenMalformed,
token.verify_token_string,
'wrong!!')
def test_verify_no_delimiter(self):
token = xsrf.XSRFToken('user@example.com',
'secret')
self.assertRaises(
xsrf.XSRFTokenMalformed,
token.verify_token_string,
base64.b64encode('NODELIMITER'))
def test_verify_time_not_int(self):
token = xsrf.XSRFToken('user@example.com',
'secret')
self.assertRaises(
xsrf.XSRFTokenMalformed,
token.verify_token_string,
base64.b64encode('NODE|NOTINT'))
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import random
import webapp2
from webapp2 import BaseRoute, RedirectHandler, Request, Route, Router
import test_base
class TestRoute(test_base.BaseTestCase):
def test_no_variable(self):
route = Route(r'/hello', None)
route, args, kwargs = route.match(Request.blank('/hello'))
self.assertEqual(kwargs, {})
url = route.build(Request.blank('/'), (), {})
self.assertEqual(url, '/hello')
route = Route(r'/hello/world/', None)
route, args, kwargs = route.match(Request.blank('/hello/world/'))
self.assertEqual(kwargs, {})
url = route.build(Request.blank('/'), (), {})
self.assertEqual(url, '/hello/world/')
def test_repetition_operator(self):
route = Route(r'/<:\d>', None)
self.assertEqual(route.match(Request.blank('/1')), (route, ('1',), {}))
self.assertEqual(route.match(Request.blank('/2')), (route, ('2',), {}))
route = Route(r'/<:\d{2,3}>', None)
self.assertEqual(route.match(Request.blank('/11')), (route, ('11',), {}))
self.assertEqual(route.match(Request.blank('/111')), (route, ('111',), {}))
self.assertEqual(route.match(Request.blank('/1111')), None)
def test_unnamed_variable(self):
route = Route(r'/<:\d{4}>', None)
self.assertEqual(route.match(Request.blank('/2010')), (route, ('2010',), {}))
self.assertEqual(route.match(Request.blank('/aaaa')), None)
route = Route(r'/<:\d{2}>.<:\d{2}>', None)
self.assertEqual(route.match(Request.blank('/98.99')), (route, ('98', '99'), {}))
self.assertEqual(route.match(Request.blank('/aa.aa')), None)
route = Route(r'/<:\d{2}>.<:\d{2}>/<foo>', None)
self.assertEqual(route.match(Request.blank('/98.99/test')), (route, ('98', '99'), {'foo': 'test'}))
self.assertEqual(route.match(Request.blank('/aa.aa/test')), None)
def test_simple_variable(self):
route = Route(r'/<foo>', None)
self.assertEqual(route.match(Request.blank('/bar')), (route, (), {'foo': 'bar'}))
url = route.build(Request.blank('/'), (), dict(foo='baz'))
self.assertEqual(url, '/baz')
def test_expr_variable(self):
route = Route(r'/<year:\d{4}>', None)
self.assertEqual(route.match(Request.blank('/bar')), None)
self.assertEqual(route.match(Request.blank('/2010')), (route, (), {'year': '2010'}))
self.assertEqual(route.match(Request.blank('/1900')), (route, (), {'year': '1900'}))
url = route.build(Request.blank('/'), (), dict(year='2010'))
self.assertEqual(url, '/2010')
def test_expr_variable2(self):
route = Route(r'/<year:\d{4}>/foo/', None)
url = route.build(Request.blank('/'), (), dict(year='2010'))
self.assertEqual(url, '/2010/foo/')
def test_build_missing_argument(self):
route = Route(r'/<:\d{4}>', None)
self.assertRaises(KeyError, route.build, Request.blank('/'), (), {})
route = Route(r'/<:\d{4}>/<:\d{2}>', None)
self.assertRaises(KeyError, route.build, Request.blank('/'), (2010,), {})
def test_build_invalid_argument(self):
route = Route(r'/<:\d{4}>', None)
self.assertRaises(ValueError, route.build, Request.blank('/'), ('20100',), {})
def test_build_invalid_argument2(self):
route = Route(r'/<:\d{4}>', None)
self.assertRaises(ValueError, route.build, Request.blank('/'), ('201a',), {})
def test_build_missing_keyword(self):
route = Route(r'/<year:\d{4}>', None)
self.assertRaises(KeyError, route.build, Request.blank('/'), (), {})
def test_build_missing_keyword2(self):
route = Route(r'/<year:\d{4}>/<month:\d{2}>', None)
self.assertRaises(KeyError, route.build, Request.blank('/'), (), dict(year='2010'))
def test_build_invalid_keyword(self):
route = Route(r'/<year:\d{4}>', None)
self.assertRaises(ValueError, route.build, Request.blank('/'), (), dict(year='20100'))
def test_build_invalid_keyword2(self):
route = Route(r'/<year:\d{4}>', None)
self.assertRaises(ValueError, route.build, Request.blank('/'), (), dict(year='201a'))
def test_build_with_unnamed_variable(self):
route = Route(r'/<:\d{4}>/<month:\d{2}>', None)
url = route.build(Request.blank('/'), (2010,), dict(month=10))
self.assertEqual(url, '/2010/10')
url = route.build(Request.blank('/'), ('1999',), dict(month='07'))
self.assertEqual(url, '/1999/07')
def test_build_default_keyword(self):
route = Route(r'/<year:\d{4}>/<month:\d{2}>', None,
defaults={'month': 10})
url = route.build(Request.blank('/'), (), dict(year='2010'))
self.assertEqual(url, '/2010/10')
route = Route(r'/<year:\d{4}>/<month:\d{2}>', None,
defaults={'year': 1900})
url = route.build(Request.blank('/'), (), dict(month='07'))
self.assertEqual(url, '/1900/07')
def test_build_extra_keyword(self):
route = Route(r'/<year:\d{4}>', None)
url = route.build(Request.blank('/'), (), dict(year='2010', foo='bar'))
self.assertEqual(url, '/2010?foo=bar')
# Arguments are sorted.
url = route.build(Request.blank('/'), (), dict(year='2010', foo='bar', baz='ding'))
self.assertEqual(url, '/2010?baz=ding&foo=bar')
def test_build_extra_positional_keyword(self):
route = Route(r'/<year:\d{4}>/<:\d{2}>', None)
url = route.build(Request.blank('/'), ('08', 'i-should-be-ignored', 'me-too'), dict(year='2010', foo='bar'))
self.assertEqual(url, '/2010/08?foo=bar')
url = route.build(Request.blank('/'), ('08', 'i-should-be-ignored', 'me-too'), dict(year='2010', foo='bar', baz='ding'))
self.assertEqual(url, '/2010/08?baz=ding&foo=bar')
def test_build_int_keyword(self):
route = Route(r'/<year:\d{4}>', None)
url = route.build(Request.blank('/'), (), dict(year=2010))
self.assertEqual(url, '/2010')
def test_build_int_variable(self):
route = Route(r'/<:\d{4}>', None)
url = route.build(Request.blank('/'), (2010,), {})
self.assertEqual(url, '/2010')
def test_router_build_error(self):
router = Router(None)
router.add(Route('/<year:\d{4}>', None, name='year-page'))
url = router.build(Request.blank('/'), 'year-page', (), dict(year='2010'))
self.assertEqual(url, '/2010')
self.assertRaises(KeyError, router.build, Request.blank('/'), 'i-dont-exist', (), dict(year='2010'))
def test_reverse_template(self):
route = Route('/foo', None)
# Access route.regex just to set the lazy properties.
regex = route.regex
self.assertEqual(route.reverse_template, '/foo')
route = Route('/foo/<bar>', None)
# Access route.regex just to set the lazy properties.
regex = route.regex
self.assertEqual(route.reverse_template, '/foo/%(bar)s')
route = Route('/foo/<bar>/<baz:\d>', None)
# Access route.regex just to set the lazy properties.
regex = route.regex
self.assertEqual(route.reverse_template, '/foo/%(bar)s/%(baz)s')
def test_invalid_template(self):
# To break it:
# <>foo:><bar<:baz>
route = Route('/<foo/<:bar', None)
# Access route.regex just to set the lazy properties.
regex = route.regex
self.assertEqual(route.reverse_template, '/<foo/<:bar')
def test_build_full_without_request(self):
router = Router(None)
router.add(Route(r'/hello', None, name='hello'))
self.assertRaises(AttributeError, router.build, None, 'hello', (), dict(_full=True))
self.assertRaises(AttributeError, router.build, None, 'hello', (), dict(_scheme='https'))
def test_positions(self):
template = '/<:\d+>' * 98
args = tuple(str(i) for i in range(98))
url_res = '/' + '/'.join(args)
route = Route(template, None)
self.assertEqual(route.match(Request.blank(url_res)), (route, args, {}))
url = route.build(Request.blank('/'), args, {})
self.assertEqual(url_res, url)
args = [str(i) for i in range(1000)]
random.shuffle(args)
args = tuple(args[:98])
url_res = '/' + '/'.join(args)
self.assertEqual(route.match(Request.blank(url_res)), (route, args, {}))
url = route.build(Request.blank('/'), args, {})
self.assertEqual(url_res, url)
def test_build_only_without_name(self):
self.assertRaises(ValueError, Route, r'/<foo>', None, build_only=True)
def test_route_repr(self):
self.assertEqual(Route(r'/<foo>', None).__repr__(),
"<Route('/<foo>', None, name=None, defaults={}, build_only=False)>")
self.assertEqual(Route(r'/<foo>', None, name='bar', defaults={'baz': 'ding'}, build_only=True).__repr__(),
"<Route('/<foo>', None, name='bar', defaults={'baz': 'ding'}, build_only=True)>")
self.assertEqual(str(Route(r'/<foo>', None)),
"<Route('/<foo>', None, name=None, defaults={}, build_only=False)>")
self.assertEqual(str(Route(r'/<foo>', None, name='bar', defaults={'baz': 'ding'}, build_only=True)),
"<Route('/<foo>', None, name='bar', defaults={'baz': 'ding'}, build_only=True)>")
def test_router_repr(self):
router = Router(None)
router.add(Route(r'/hello', None, name='hello', build_only=True))
router.add(Route(r'/world', None))
self.assertEqual(router.__repr__(), "<Router([<Route('/world', None, name=None, defaults={}, build_only=False)>, <Route('/hello', None, name='hello', defaults={}, build_only=True)>])>")
def test_base_route(self):
route = BaseRoute('foo', 'bar')
self.assertRaises(NotImplementedError, route.match, None)
def test_set_matcher(self):
req = Request.blank('/')
def custom_matcher(router, request):
self.assertEqual(request, req)
router = Router(None)
router.set_matcher(custom_matcher)
router.match(req)
def test_set_builder(self):
req = Request.blank('/')
def custom_builder(router, request, name, args, kwargs):
self.assertEqual(request, req)
return 'http://www.google.com'
router = Router(None)
router.set_builder(custom_builder)
res = router.build(req, '', (), {})
self.assertEqual(res, 'http://www.google.com')
def test_set_adapter(self):
def custom_adapter(router, handler):
class MyAdapter(webapp2.BaseHandlerAdapter):
def __call__(self, request, response):
response.write('hello my adapter')
return MyAdapter(handler)
def myhandler(request, *args, **kwargs):
return webapp2.Response('hello')
app = webapp2.WSGIApplication([('/', myhandler)])
app.router.set_adapter(custom_adapter)
rsp = app.get_response('/')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'hello my adapter')
def test_methods(self):
route = Route(r'/', methods=['GET', 'POST'])
router = Router([route])
req = Request.blank('/')
req.method = 'GET'
self.assertTrue(router.match(req) is not None)
req.method = 'POST'
self.assertTrue(router.match(req) is not None)
req.method = 'PUT'
self.assertRaises(webapp2.exc.HTTPMethodNotAllowed, router.match, req)
def test_schemes(self):
route = Route(r'/', schemes=['http'])
req = Request.blank('http://mydomain.com/')
self.assertTrue(route.match(req) is not None)
req = Request.blank('https://mydomain.com/')
self.assertTrue(route.match(req) is None)
route = Route(r'/', schemes=['https'])
req = Request.blank('https://mydomain.com/')
self.assertTrue(route.match(req) is not None)
req = Request.blank('http://mydomain.com/')
self.assertTrue(route.match(req) is None)
class TestSimpleRoute(test_base.BaseTestCase):
def test_no_variable(self):
router = webapp2.Router([(r'/', 'my_handler')])
matched_route, args, kwargs = router.match(webapp2.Request.blank('/'))
self.assertEqual(args, ())
self.assertEqual(kwargs, {})
def test_simple_variables(self):
router = webapp2.Router([(r'/(\d{4})/(\d{2})', 'my_handler')])
matched_route, args, kwargs = router.match(webapp2.Request.blank('/2007/10'))
self.assertEqual(args, ('2007', '10'))
self.assertEqual(kwargs, {})
def test_build(self):
route = webapp2.SimpleRoute('/', None)
self.assertRaises(NotImplementedError, route.build, None, None, None)
def test_route_repr(self):
self.assertEqual(webapp2.SimpleRoute(r'/<foo>', None).__repr__(), "<SimpleRoute('/<foo>', None)>")
self.assertEqual(str(webapp2.SimpleRoute(r'/<foo>', None)), "<SimpleRoute('/<foo>', None)>")
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webapp2
from webapp2_extras import sessions
import test_base
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'my-super-secret',
},
})
class TestSecureCookieSession(test_base.BaseTestCase):
factory = sessions.SecureCookieSessionFactory
def test_config(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
self.assertRaises(Exception, sessions.SessionStore, req)
# Just to set a special config.
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req, config={
'secret_key': 'my-super-secret',
'cookie_name': 'foo'
})
session = store.get_session(factory=self.factory)
session['bar'] = 'bar'
rsp = webapp2.Response()
store.save_sessions(rsp)
self.assertTrue(rsp.headers['Set-Cookie'].startswith('foo='))
def test_get_save_session(self):
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
rsp = webapp2.Response()
# Nothing changed, we want to test anyway.
store.save_sessions(rsp)
session['a'] = 'b'
session['c'] = 'd'
session['e'] = 'f'
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
session['g'] = 'h'
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 3 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
self.assertEqual(session['g'], 'h')
self.assertRaises(KeyError, session.pop, 'foo')
def test_flashes(self):
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
flashes = session.get_flashes()
self.assertEqual(flashes, [])
session.add_flash('foo')
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
flashes = session.get_flashes()
self.assertEqual(flashes, [[u'foo', None]])
flashes = session.get_flashes()
self.assertEqual(flashes, [])
session.add_flash('bar')
session.add_flash('baz', 'important')
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 3 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
flashes = session.get_flashes()
self.assertEqual(flashes, [[u'bar', None], [u'baz', 'important']])
flashes = session.get_flashes()
self.assertEqual(flashes, [])
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 4 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(factory=self.factory)
flashes = session.get_flashes()
self.assertEqual(flashes, [])
def test_set_secure_cookie(self):
rsp = webapp2.Response()
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
store.set_secure_cookie('foo', {'bar': 'baz'})
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
res = store.get_secure_cookie('foo')
self.assertEqual(res, {'bar': 'baz'})
def test_set_session_store(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'my-super-secret',
}
})
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
self.assertEqual(len(req.registry), 0)
sessions.set_store(store, request=req)
self.assertEqual(len(req.registry), 1)
s = sessions.get_store(request=req)
self.assertTrue(isinstance(s, sessions.SessionStore))
def test_get_session_store(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'my-super-secret',
}
})
req = webapp2.Request.blank('/')
req.app = app
self.assertEqual(len(req.registry), 0)
s = sessions.get_store(request=req)
self.assertEqual(len(req.registry), 1)
self.assertTrue(isinstance(s, sessions.SessionStore))
def test_not_implemented(self):
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
f = sessions.BaseSessionFactory('foo', store)
self.assertRaises(NotImplementedError, f.get_session)
self.assertRaises(NotImplementedError, f.save_session, None)
f = sessions.CustomBackendSessionFactory('foo', store)
self.assertRaises(NotImplementedError, f._get_by_sid, None)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webob
import webob.exc
import webapp2
import test_base
class TestMiscellaneous(test_base.BaseTestCase):
def test_abort(self):
self.assertRaises(webob.exc.HTTPOk, webapp2.abort, 200)
self.assertRaises(webob.exc.HTTPCreated, webapp2.abort, 201)
self.assertRaises(webob.exc.HTTPAccepted, webapp2.abort, 202)
self.assertRaises(webob.exc.HTTPNonAuthoritativeInformation, webapp2.abort, 203)
self.assertRaises(webob.exc.HTTPNoContent, webapp2.abort, 204)
self.assertRaises(webob.exc.HTTPResetContent, webapp2.abort, 205)
self.assertRaises(webob.exc.HTTPPartialContent, webapp2.abort, 206)
self.assertRaises(webob.exc.HTTPMultipleChoices, webapp2.abort, 300)
self.assertRaises(webob.exc.HTTPMovedPermanently, webapp2.abort, 301)
self.assertRaises(webob.exc.HTTPFound, webapp2.abort, 302)
self.assertRaises(webob.exc.HTTPSeeOther, webapp2.abort, 303)
self.assertRaises(webob.exc.HTTPNotModified, webapp2.abort, 304)
self.assertRaises(webob.exc.HTTPUseProxy, webapp2.abort, 305)
self.assertRaises(webob.exc.HTTPTemporaryRedirect, webapp2.abort, 307)
self.assertRaises(webob.exc.HTTPClientError, webapp2.abort, 400)
self.assertRaises(webob.exc.HTTPUnauthorized, webapp2.abort, 401)
self.assertRaises(webob.exc.HTTPPaymentRequired, webapp2.abort, 402)
self.assertRaises(webob.exc.HTTPForbidden, webapp2.abort, 403)
self.assertRaises(webob.exc.HTTPNotFound, webapp2.abort, 404)
self.assertRaises(webob.exc.HTTPMethodNotAllowed, webapp2.abort, 405)
self.assertRaises(webob.exc.HTTPNotAcceptable, webapp2.abort, 406)
self.assertRaises(webob.exc.HTTPProxyAuthenticationRequired, webapp2.abort, 407)
self.assertRaises(webob.exc.HTTPRequestTimeout, webapp2.abort, 408)
self.assertRaises(webob.exc.HTTPConflict, webapp2.abort, 409)
self.assertRaises(webob.exc.HTTPGone, webapp2.abort, 410)
self.assertRaises(webob.exc.HTTPLengthRequired, webapp2.abort, 411)
self.assertRaises(webob.exc.HTTPPreconditionFailed, webapp2.abort, 412)
self.assertRaises(webob.exc.HTTPRequestEntityTooLarge, webapp2.abort, 413)
self.assertRaises(webob.exc.HTTPRequestURITooLong, webapp2.abort, 414)
self.assertRaises(webob.exc.HTTPUnsupportedMediaType, webapp2.abort, 415)
self.assertRaises(webob.exc.HTTPRequestRangeNotSatisfiable, webapp2.abort, 416)
self.assertRaises(webob.exc.HTTPExpectationFailed, webapp2.abort, 417)
self.assertRaises(webob.exc.HTTPInternalServerError, webapp2.abort, 500)
self.assertRaises(webob.exc.HTTPNotImplemented, webapp2.abort, 501)
self.assertRaises(webob.exc.HTTPBadGateway, webapp2.abort, 502)
self.assertRaises(webob.exc.HTTPServiceUnavailable, webapp2.abort, 503)
self.assertRaises(webob.exc.HTTPGatewayTimeout, webapp2.abort, 504)
self.assertRaises(webob.exc.HTTPVersionNotSupported, webapp2.abort, 505)
# Invalid use 500 as default.
self.assertRaises(KeyError, webapp2.abort, 0)
self.assertRaises(KeyError, webapp2.abort, 999999)
self.assertRaises(KeyError, webapp2.abort, 'foo')
def test_import_string(self):
self.assertEqual(webapp2.import_string('webob.exc'), webob.exc)
self.assertEqual(webapp2.import_string('webob'), webob)
self.assertEqual(webapp2.import_string('asdfg', silent=True), None)
self.assertEqual(webapp2.import_string('webob.asdfg', silent=True), None)
self.assertRaises(webapp2.ImportStringError, webapp2.import_string, 'asdfg')
self.assertRaises(webapp2.ImportStringError, webapp2.import_string, 'webob.asdfg')
def test_to_utf8(self):
res = webapp2._to_utf8('ábcdéf'.decode('utf-8'))
self.assertEqual(isinstance(res, str), True)
res = webapp2._to_utf8('abcdef')
self.assertEqual(isinstance(res, str), True)
'''
# removed to simplify the codebase.
def test_to_unicode(self):
res = webapp2.to_unicode(unicode('foo'))
self.assertEqual(isinstance(res, unicode), True)
res = webapp2.to_unicode('foo')
self.assertEqual(isinstance(res, unicode), True)
'''
def test_http_status_message(self):
self.assertEqual(webapp2.Response.http_status_message(404), 'Not Found')
self.assertEqual(webapp2.Response.http_status_message(500), 'Internal Server Error')
self.assertRaises(KeyError, webapp2.Response.http_status_message, 9999)
def test_cached_property(self):
count = [0]
class Foo(object):
@webapp2.cached_property
def bar(self):
count[0] += 1
return count[0]
self.assertTrue(isinstance(Foo.bar, webapp2.cached_property))
foo = Foo()
self.assertEqual(foo.bar, 1)
self.assertEqual(foo.bar, 1)
self.assertEqual(foo.bar, 1)
def test_redirect(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
app.set_globals(app=app, request=req)
rsp = webapp2.redirect('http://www.google.com/', code=301, body='Weee')
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, 'Weee')
self.assertEqual(rsp.headers.get('Location'), 'http://www.google.com/')
def test_redirect_to(self):
app = webapp2.WSGIApplication([
webapp2.Route('/home', handler='', name='home'),
])
req = webapp2.Request.blank('/')
req.app = app
app.set_globals(app=app, request=req)
rsp = webapp2.redirect_to('home', _code=301, _body='Weee')
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, 'Weee')
self.assertEqual(rsp.headers.get('Location'), 'http://localhost/home')
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webapp2
from webapp2_extras.routes import (DomainRoute, HandlerPrefixRoute,
RedirectRoute, NamePrefixRoute, PathPrefixRoute)
import test_base
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
self.response.out.write('home sweet home')
app = webapp2.WSGIApplication([
#RedirectRoute('/', name='home', handler=HomeHandler),
RedirectRoute('/redirect-me-easily', redirect_to='/i-was-redirected-easily'),
RedirectRoute('/redirect-me-easily2', redirect_to='/i-was-redirected-easily', defaults={'_code': 302}),
RedirectRoute('/redirect-me-easily3', redirect_to='/i-was-redirected-easily', defaults={'_permanent': False}),
RedirectRoute('/strict-foo', HomeHandler, 'foo-strict', strict_slash=True),
RedirectRoute('/strict-bar/', HomeHandler, 'bar-strict', strict_slash=True),
RedirectRoute('/redirect-to-name-destination', name='redirect-to-name-destination', handler=HomeHandler),
RedirectRoute('/redirect-to-name', redirect_to_name='redirect-to-name-destination'),
])
class TestRedirectRoute(test_base.BaseTestCase):
def test_route_redirect_to(self):
route = RedirectRoute('/foo', redirect_to='/bar')
router = webapp2.Router([route])
route_match, args, kwargs = router.match(webapp2.Request.blank('/foo'))
self.assertEqual(route_match, route)
self.assertEqual(args, ())
self.assertEqual(kwargs, {'_uri': '/bar'})
def test_easy_redirect_to(self):
req = webapp2.Request.blank('/redirect-me-easily')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/i-was-redirected-easily')
req = webapp2.Request.blank('/redirect-me-easily2')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/i-was-redirected-easily')
req = webapp2.Request.blank('/redirect-me-easily3')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/i-was-redirected-easily')
def test_redirect_to_name(self):
req = webapp2.Request.blank('/redirect-to-name')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/redirect-to-name-destination')
def test_strict_slash(self):
req = webapp2.Request.blank('/strict-foo')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home')
req = webapp2.Request.blank('/strict-bar/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home')
# Now the non-strict...
req = webapp2.Request.blank('/strict-foo/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/strict-foo')
req = webapp2.Request.blank('/strict-bar')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/strict-bar/')
# Strict slash routes must have a name.
self.assertRaises(ValueError, RedirectRoute, '/strict-bar/', handler=HomeHandler, strict_slash=True)
def test_build_only(self):
self.assertRaises(ValueError, RedirectRoute, '/', handler=HomeHandler, build_only=True)
class TestPrefixRoutes(test_base.BaseTestCase):
def test_simple(self):
router = webapp2.Router([
PathPrefixRoute('/a', [
webapp2.Route('/', 'a', 'name-a'),
webapp2.Route('/b', 'a/b', 'name-a/b'),
webapp2.Route('/c', 'a/c', 'name-a/c'),
PathPrefixRoute('/d', [
webapp2.Route('/', 'a/d', 'name-a/d'),
webapp2.Route('/b', 'a/d/b', 'name-a/d/b'),
webapp2.Route('/c', 'a/d/c', 'name-a/d/c'),
]),
])
])
path = '/a/'
match = ((), {})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'name-a', match[0], match[1]), path)
path = '/a/b'
match = ((), {})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'name-a/b', match[0], match[1]), path)
path = '/a/c'
match = ((), {})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'name-a/c', match[0], match[1]), path)
path = '/a/d/'
match = ((), {})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'name-a/d', match[0], match[1]), path)
path = '/a/d/b'
match = ((), {})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'name-a/d/b', match[0], match[1]), path)
path = '/a/d/c'
match = ((), {})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'name-a/d/c', match[0], match[1]), path)
def test_with_variables_name_and_handler(self):
router = webapp2.Router([
PathPrefixRoute('/user/<username:\w+>', [
HandlerPrefixRoute('apps.users.', [
NamePrefixRoute('user-', [
webapp2.Route('/', 'UserOverviewHandler', 'overview'),
webapp2.Route('/profile', 'UserProfileHandler', 'profile'),
webapp2.Route('/projects', 'UserProjectsHandler', 'projects'),
]),
]),
])
])
path = '/user/calvin/'
match = ((), {'username': 'calvin'})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'user-overview', match[0], match[1]), path)
path = '/user/calvin/profile'
match = ((), {'username': 'calvin'})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'user-profile', match[0], match[1]), path)
path = '/user/calvin/projects'
match = ((), {'username': 'calvin'})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
self.assertEqual(router.build(webapp2.Request.blank('/'), 'user-projects', match[0], match[1]), path)
class TestDomainRoute(test_base.BaseTestCase):
def test_simple(self):
router = webapp2.Router([
DomainRoute('<subdomain>.<:.*>', [
webapp2.Route('/foo', 'FooHandler', 'subdomain-thingie'),
])
])
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank('/foo'))
match = router.match(webapp2.Request.blank('http://my-subdomain.app-id.appspot.com/foo'))
self.assertEqual(match[1:], ((), {'subdomain': 'my-subdomain'}))
match = router.match(webapp2.Request.blank('http://another-subdomain.app-id.appspot.com/foo'))
self.assertEqual(match[1:], ((), {'subdomain': 'another-subdomain'}))
url = router.build(webapp2.Request.blank('/'), 'subdomain-thingie', (), {'_netloc': 'another-subdomain.app-id.appspot.com'})
self.assertEqual(url, 'http://another-subdomain.app-id.appspot.com/foo')
def test_with_variables_name_and_handler(self):
router = webapp2.Router([
DomainRoute('<subdomain>.<:.*>', [
PathPrefixRoute('/user/<username:\w+>', [
HandlerPrefixRoute('apps.users.', [
NamePrefixRoute('user-', [
webapp2.Route('/', 'UserOverviewHandler', 'overview'),
webapp2.Route('/profile', 'UserProfileHandler', 'profile'),
webapp2.Route('/projects', 'UserProjectsHandler', 'projects'),
]),
]),
])
]),
])
path = 'http://my-subdomain.app-id.appspot.com/user/calvin/'
match = ((), {'username': 'calvin', 'subdomain': 'my-subdomain'})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
match[1].pop('subdomain')
match[1]['_netloc'] = 'my-subdomain.app-id.appspot.com'
self.assertEqual(router.build(webapp2.Request.blank('/'), 'user-overview', match[0], match[1]), path)
path = 'http://my-subdomain.app-id.appspot.com/user/calvin/profile'
match = ((), {'username': 'calvin', 'subdomain': 'my-subdomain'})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
match[1].pop('subdomain')
match[1]['_netloc'] = 'my-subdomain.app-id.appspot.com'
self.assertEqual(router.build(webapp2.Request.blank('/'), 'user-profile', match[0], match[1]), path)
path = 'http://my-subdomain.app-id.appspot.com/user/calvin/projects'
match = ((), {'username': 'calvin', 'subdomain': 'my-subdomain'})
self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match)
match[1].pop('subdomain')
match[1]['_netloc'] = 'my-subdomain.app-id.appspot.com'
self.assertEqual(router.build(webapp2.Request.blank('/'), 'user-projects', match[0], match[1]), path)
def test_guide_examples(self):
router = webapp2.Router([
DomainRoute(r'www.mydomain.com', [
webapp2.Route('/path1', 'Path1', 'path1'),
]),
DomainRoute(r'<subdomain:(?!www\.)[^.]+>.mydomain.com', [
webapp2.Route('/path2', 'Path2', 'path2'),
]),
DomainRoute(r'<:(app-id\.appspot\.com|www\.mydomain\.com)>', [
webapp2.Route('/path3', 'Path3', 'path3'),
]),
DomainRoute(r'<subdomain:(?!www)[^.]+>.<:(app-id\.appspot\.com|mydomain\.com)>', [
webapp2.Route('/path4', 'Path4', 'path4'),
]),
])
uri1a = 'http://www.mydomain.com/path1'
uri1b = 'http://sub.mydomain.com/path1'
uri1c = 'http://www.mydomain.com/invalid-path'
uri2a = 'http://sub.mydomain.com/path2'
uri2b = 'http://www.mydomain.com/path2'
uri2c = 'http://sub.mydomain.com/invalid-path'
uri2d = 'http://www.mydomain.com/invalid-path'
uri3a = 'http://app-id.appspot.com/path3'
uri3b = 'http://www.mydomain.com/path3'
uri3c = 'http://sub.app-id.appspot.com/path3'
uri3d = 'http://sub.mydomain.com/path3'
uri3e = 'http://app-id.appspot.com/invalid-path'
uri3f = 'http://www.mydomain.com/invalid-path'
uri4a = 'http://sub.app-id.appspot.com/path4'
uri4b = 'http://sub.mydomain.com/path4'
uri4c = 'http://app-id.appspot.com/path4'
uri4d = 'http://www.app-id.appspot.com/path4'
uri4e = 'http://www.mydomain.com/path4'
uri4f = 'http://sub.app-id.appspot.com/invalid-path'
uri4g = 'http://sub.mydomain.com/invalid-path'
self.assertEqual(router.match(webapp2.Request.blank(uri1a))[1:], ((), {}))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri1b))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri1c))
self.assertEqual(router.match(webapp2.Request.blank(uri2a))[1:], ((), {'subdomain': 'sub'}))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri2b))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri2c))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri2d))
self.assertEqual(router.match(webapp2.Request.blank(uri3a))[1:], ((), {}))
self.assertEqual(router.match(webapp2.Request.blank(uri3b))[1:], ((), {}))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri3c))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri3d))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri3e))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri3f))
self.assertEqual(router.match(webapp2.Request.blank(uri4a))[1:], ((), {'subdomain': 'sub'}))
self.assertEqual(router.match(webapp2.Request.blank(uri4b))[1:], ((), {'subdomain': 'sub'}))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri4c))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri4d))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri4e))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri4f))
self.assertRaises(webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank(uri4g))
if __name__ == '__main__':
test_base.main() | Python |
# -*- coding: utf-8 -*-
import os
import webapp2
from webapp2_extras import mako
import test_base
current_dir = os.path.abspath(os.path.dirname(__file__))
template_path = os.path.join(current_dir, 'resources', 'mako_templates')
class TestMako(test_base.BaseTestCase):
def test_render_template(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.mako': {
'template_path': template_path,
},
})
req = webapp2.Request.blank('/')
app.set_globals(app=app, request=req)
m = mako.Mako(app)
message = 'Hello, World!'
res = m.render_template( 'template1.html', message=message)
self.assertEqual(res, message + '\n')
def test_set_mako(self):
app = webapp2.WSGIApplication()
self.assertEqual(len(app.registry), 0)
mako.set_mako(mako.Mako(app), app=app)
self.assertEqual(len(app.registry), 1)
j = mako.get_mako(app=app)
self.assertTrue(isinstance(j, mako.Mako))
def test_get_mako(self):
app = webapp2.WSGIApplication()
self.assertEqual(len(app.registry), 0)
j = mako.get_mako(app=app)
self.assertEqual(len(app.registry), 1)
self.assertTrue(isinstance(j, mako.Mako))
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
"""
Tests for webapp2 webapp2.RequestHandler
"""
import os
import StringIO
import sys
import urllib
import webapp2
import test_base
class BareHandler(object):
def __init__(self, request, response):
self.response = response
response.write('I am not a RequestHandler but I work.')
def dispatch(self):
return self.response
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
self.response.out.write('home sweet home')
def post(self, **kwargs):
self.response.out.write('home sweet home - POST')
class MethodsHandler(HomeHandler):
def put(self, **kwargs):
self.response.out.write('home sweet home - PUT')
def delete(self, **kwargs):
self.response.out.write('home sweet home - DELETE')
def head(self, **kwargs):
self.response.out.write('home sweet home - HEAD')
def trace(self, **kwargs):
self.response.out.write('home sweet home - TRACE')
def options(self, **kwargs):
self.response.out.write('home sweet home - OPTIONS')
class RedirectToHandler(webapp2.RequestHandler):
def get(self, **kwargs):
return self.redirect_to('route-test', _fragment='my-anchor', year='2010',
month='07', name='test', foo='bar')
class RedirectAbortHandler(webapp2.RequestHandler):
def get(self, **kwargs):
self.redirect('/somewhere', abort=True)
class BrokenHandler(webapp2.RequestHandler):
def get(self, **kwargs):
raise ValueError('booo!')
class BrokenButFixedHandler(BrokenHandler):
def handle_exception(self, exception, debug_mode):
# Let's fix it.
self.response.set_status(200)
self.response.out.write('that was close!')
def handle_404(request, response, exception):
response.out.write('404 custom handler')
response.set_status(404)
def handle_405(request, response, exception):
response.out.write('405 custom handler')
response.set_status(405, 'Custom Error Message')
response.headers['Allow'] = 'GET'
def handle_500(request, response, exception):
response.out.write('500 custom handler')
response.set_status(500)
class PositionalHandler(webapp2.RequestHandler):
def get(self, month, day, slug=None):
self.response.out.write('%s:%s:%s' % (month, day, slug))
class HandlerWithError(webapp2.RequestHandler):
def get(self, **kwargs):
self.response.out.write('bla bla bla bla bla bla')
self.error(403)
class InitializeHandler(webapp2.RequestHandler):
def __init__(self):
pass
def get(self):
self.response.out.write('Request method: %s' % self.request.method)
class WebDavHandler(webapp2.RequestHandler):
def version_control(self):
self.response.out.write('Method: VERSION-CONTROL')
def unlock(self):
self.response.out.write('Method: UNLOCK')
def propfind(self):
self.response.out.write('Method: PROPFIND')
class AuthorizationHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write('nothing here')
class HandlerWithEscapedArg(webapp2.RequestHandler):
def get(self, name):
self.response.out.write(urllib.unquote_plus(name))
def get_redirect_url(handler, **kwargs):
return handler.uri_for('methods')
app = webapp2.WSGIApplication([
('/bare', BareHandler),
webapp2.Route('/', HomeHandler, name='home'),
webapp2.Route('/methods', MethodsHandler, name='methods'),
webapp2.Route('/broken', BrokenHandler),
webapp2.Route('/broken-but-fixed', BrokenButFixedHandler),
webapp2.Route('/<year:\d{4}>/<month:\d{1,2}>/<name>', None, name='route-test'),
webapp2.Route('/<:\d\d>/<:\d{2}>/<:\w+>', PositionalHandler, name='positional'),
webapp2.Route('/redirect-me', webapp2.RedirectHandler, defaults={'_uri': '/broken'}),
webapp2.Route('/redirect-me2', webapp2.RedirectHandler, defaults={'_uri': get_redirect_url}),
webapp2.Route('/redirect-me3', webapp2.RedirectHandler, defaults={'_uri': '/broken', '_permanent': False}),
webapp2.Route('/redirect-me4', webapp2.RedirectHandler, defaults={'_uri': get_redirect_url, '_permanent': False}),
webapp2.Route('/redirect-me5', RedirectToHandler),
webapp2.Route('/redirect-me6', RedirectAbortHandler),
webapp2.Route('/lazy', 'resources.handlers.LazyHandler'),
webapp2.Route('/error', HandlerWithError),
webapp2.Route('/initialize', InitializeHandler),
webapp2.Route('/webdav', WebDavHandler),
webapp2.Route('/authorization', AuthorizationHandler),
webapp2.Route('/escape/<name:.*>', HandlerWithEscapedArg, 'escape'),
], debug=False)
DEFAULT_RESPONSE = """Status: 404 Not Found
content-type: text/html; charset=utf8
Content-Length: 52
404 Not Found
The resource could not be found.
"""
class TestHandler(test_base.BaseTestCase):
def tearDown(self):
super(TestHandler, self).tearDown()
app.error_handlers = {}
def test_200(self):
rsp = app.get_response('/')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home')
def test_404(self):
req = webapp2.Request.blank('/nowhere')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 404)
def test_405(self):
req = webapp2.Request.blank('/')
req.method = 'PUT'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 405)
self.assertEqual(rsp.headers.get('Allow'), 'GET, POST')
def test_500(self):
req = webapp2.Request.blank('/broken')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 500)
def test_500_but_fixed(self):
req = webapp2.Request.blank('/broken-but-fixed')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'that was close!')
def test_501(self):
# 501 Not Implemented
req = webapp2.Request.blank('/methods')
req.method = 'FOOBAR'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 501)
def test_lazy_handler(self):
req = webapp2.Request.blank('/lazy')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'I am a laaazy view.')
def test_handler_with_error(self):
req = webapp2.Request.blank('/error')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 403)
self.assertEqual(rsp.body, '')
def test_debug_mode(self):
app = webapp2.WSGIApplication([
webapp2.Route('/broken', BrokenHandler),
], debug=True)
req = webapp2.Request.blank('/broken')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 500)
def test_custom_error_handlers(self):
app.error_handlers = {
404: handle_404,
405: handle_405,
500: handle_500,
}
req = webapp2.Request.blank('/nowhere')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 404)
self.assertEqual(rsp.body, '404 custom handler')
req = webapp2.Request.blank('/')
req.method = 'PUT'
rsp = req.get_response(app)
self.assertEqual(rsp.status, '405 Custom Error Message')
self.assertEqual(rsp.body, '405 custom handler')
self.assertEqual(rsp.headers.get('Allow'), 'GET')
req = webapp2.Request.blank('/broken')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 500)
self.assertEqual(rsp.body, '500 custom handler')
def test_methods(self):
app.debug = True
req = webapp2.Request.blank('/methods')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home')
req = webapp2.Request.blank('/methods')
req.method = 'POST'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home - POST')
req = webapp2.Request.blank('/methods')
req.method = 'PUT'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home - PUT')
req = webapp2.Request.blank('/methods')
req.method = 'DELETE'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home - DELETE')
req = webapp2.Request.blank('/methods')
req.method = 'HEAD'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, '')
req = webapp2.Request.blank('/methods')
req.method = 'OPTIONS'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home - OPTIONS')
req = webapp2.Request.blank('/methods')
req.method = 'TRACE'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'home sweet home - TRACE')
app.debug = False
def test_positional(self):
req = webapp2.Request.blank('/07/31/test')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, '07:31:test')
req = webapp2.Request.blank('/10/18/wooohooo')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, '10:18:wooohooo')
def test_redirect(self):
req = webapp2.Request.blank('/redirect-me')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/broken')
def test_redirect_with_callable(self):
req = webapp2.Request.blank('/redirect-me2')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 301)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/methods')
def test_redirect_not_permanent(self):
req = webapp2.Request.blank('/redirect-me3')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/broken')
def test_redirect_with_callable_not_permanent(self):
req = webapp2.Request.blank('/redirect-me4')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/methods')
def test_redirect_to(self):
req = webapp2.Request.blank('/redirect-me5')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.body, '')
self.assertEqual(rsp.headers['Location'], 'http://localhost/2010/07/test?foo=bar#my-anchor')
def test_redirect_abort(self):
req = webapp2.Request.blank('/redirect-me6')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.body, """302 Moved Temporarily
The resource was found at http://localhost/somewhere; you should be redirected automatically. """)
self.assertEqual(rsp.headers['Location'], 'http://localhost/somewhere')
def test_run(self):
os.environ['REQUEST_METHOD'] = 'GET'
app.run()
#self.assertEqual(sys.stdout.read(), DEFAULT_RESPONSE)
def test_run_bare(self):
os.environ['REQUEST_METHOD'] = 'GET'
app.run(bare=True)
#self.assertEqual(sys.stdout.read(), DEFAULT_RESPONSE)
def test_run_debug(self):
debug = app.debug
app.debug = True
os.environ['REQUEST_METHOD'] = 'GET'
os.environ['PATH_INFO'] = '/'
res = app.run(bare=True)
#self.assertEqual(sys.stdout.read(), DEFAULT_RESPONSE)
app.debug = debug
'''
def test_get_valid_methods(self):
req = webapp2.Request.blank('http://localhost:80/')
req.app = app
app.set_globals(app=app, request=req)
handler = BrokenHandler(req, None)
handler.app = app
self.assertEqual(handler.get_valid_methods().sort(), ['GET'].sort())
handler = HomeHandler(req, None)
handler.app = app
self.assertEqual(handler.get_valid_methods().sort(),
['GET', 'POST'].sort())
handler = MethodsHandler(req, None)
handler.app = app
self.assertEqual(handler.get_valid_methods().sort(),
['GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'].sort())
'''
def test_uri_for(self):
class Handler(webapp2.RequestHandler):
def get(self, *args, **kwargs):
pass
req = webapp2.Request.blank('http://localhost:80/')
req.route = webapp2.Route('')
req.route_args = tuple()
req.route_kwargs = {}
req.app = app
app.set_globals(app=app, request=req)
handler = Handler(req, webapp2.Response())
handler.app = app
for func in (handler.uri_for,):
self.assertEqual(func('home'), '/')
self.assertEqual(func('home', foo='bar'), '/?foo=bar')
self.assertEqual(func('home', _fragment='my-anchor', foo='bar'), '/?foo=bar#my-anchor')
self.assertEqual(func('home', _fragment='my-anchor'), '/#my-anchor')
self.assertEqual(func('home', _full=True), 'http://localhost:80/')
self.assertEqual(func('home', _full=True, _fragment='my-anchor'), 'http://localhost:80/#my-anchor')
self.assertEqual(func('home', _scheme='https'), 'https://localhost:80/')
self.assertEqual(func('home', _scheme='https', _full=False), 'https://localhost:80/')
self.assertEqual(func('home', _scheme='https', _fragment='my-anchor'), 'https://localhost:80/#my-anchor')
self.assertEqual(func('methods'), '/methods')
self.assertEqual(func('methods', foo='bar'), '/methods?foo=bar')
self.assertEqual(func('methods', _fragment='my-anchor', foo='bar'), '/methods?foo=bar#my-anchor')
self.assertEqual(func('methods', _fragment='my-anchor'), '/methods#my-anchor')
self.assertEqual(func('methods', _full=True), 'http://localhost:80/methods')
self.assertEqual(func('methods', _full=True, _fragment='my-anchor'), 'http://localhost:80/methods#my-anchor')
self.assertEqual(func('methods', _scheme='https'), 'https://localhost:80/methods')
self.assertEqual(func('methods', _scheme='https', _full=False), 'https://localhost:80/methods')
self.assertEqual(func('methods', _scheme='https', _fragment='my-anchor'), 'https://localhost:80/methods#my-anchor')
self.assertEqual(func('route-test', year='2010', month='0', name='test'), '/2010/0/test')
self.assertEqual(func('route-test', year='2010', month='07', name='test'), '/2010/07/test')
self.assertEqual(func('route-test', year='2010', month='07', name='test', foo='bar'), '/2010/07/test?foo=bar')
self.assertEqual(func('route-test', _fragment='my-anchor', year='2010', month='07', name='test', foo='bar'), '/2010/07/test?foo=bar#my-anchor')
self.assertEqual(func('route-test', _fragment='my-anchor', year='2010', month='07', name='test'), '/2010/07/test#my-anchor')
self.assertEqual(func('route-test', _full=True, year='2010', month='07', name='test'), 'http://localhost:80/2010/07/test')
self.assertEqual(func('route-test', _full=True, _fragment='my-anchor', year='2010', month='07', name='test'), 'http://localhost:80/2010/07/test#my-anchor')
self.assertEqual(func('route-test', _scheme='https', year='2010', month='07', name='test'), 'https://localhost:80/2010/07/test')
self.assertEqual(func('route-test', _scheme='https', _full=False, year='2010', month='07', name='test'), 'https://localhost:80/2010/07/test')
self.assertEqual(func('route-test', _scheme='https', _fragment='my-anchor', year='2010', month='07', name='test'), 'https://localhost:80/2010/07/test#my-anchor')
def test_extra_request_methods(self):
allowed_methods_backup = app.allowed_methods
webdav_methods = ('VERSION-CONTROL', 'UNLOCK', 'PROPFIND')
for method in webdav_methods:
# It is still not possible to use WebDav methods...
req = webapp2.Request.blank('/webdav')
req.method = method
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 501)
# Let's extend ALLOWED_METHODS with some WebDav methods.
app.allowed_methods = tuple(app.allowed_methods) + webdav_methods
#self.assertEqual(sorted(webapp2.get_valid_methods(WebDavHandler)), sorted(list(webdav_methods)))
# Now we can use WebDav methods...
for method in webdav_methods:
req = webapp2.Request.blank('/webdav')
req.method = method
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Method: %s' % method)
# Restore initial values.
app.allowed_methods = allowed_methods_backup
self.assertEqual(len(app.allowed_methods), 7)
def test_escaping(self):
def get_req(uri):
req = webapp2.Request.blank(uri)
app.set_globals(app=app, request=req)
handler = webapp2.RequestHandler(req, None)
handler.app = req.app = app
return req, handler
req, handler = get_req('http://localhost:80/')
uri = webapp2.uri_for('escape', name='with space')
req, handler = get_req(uri)
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'with space')
req, handler = get_req('http://localhost:80/')
uri = webapp2.uri_for('escape', name='with+plus')
req, handler = get_req(uri)
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'with plus')
req, handler = get_req('http://localhost:80/')
uri = webapp2.uri_for('escape', name='with/slash')
req, handler = get_req(uri)
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'with/slash')
def test_handle_exception_with_error(self):
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
raise TypeError()
def handle_exception(request, response, exception):
raise ValueError()
app = webapp2.WSGIApplication([
webapp2.Route('/', HomeHandler, name='home'),
], debug=False)
app.error_handlers[500] = handle_exception
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 500)
def test_handle_exception_with_error_debug(self):
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
raise TypeError()
def handle_exception(request, response, exception):
raise ValueError()
app = webapp2.WSGIApplication([
webapp2.Route('/', HomeHandler, name='home'),
], debug=True)
app.error_handlers[500] = handle_exception
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 500)
def test_function_handler(self):
def my_view(request, *args, **kwargs):
return webapp2.Response('Hello, function world!')
def other_view(request, *args, **kwargs):
return webapp2.Response('Hello again, function world!')
'''
def one_more_view(request, response):
self.assertEqual(request.route_args, ())
self.assertEqual(request.route_kwargs, {'foo': 'bar'})
response.write('Hello you too, deprecated arguments world!')
'''
def one_more_view(request, *args, **kwargs):
self.assertEqual(args, ())
self.assertEqual(kwargs, {'foo': 'bar'})
return webapp2.Response('Hello you too!')
app = webapp2.WSGIApplication([
webapp2.Route('/', my_view),
webapp2.Route('/other', other_view),
webapp2.Route('/one-more/<foo>', one_more_view),
#webapp2.Route('/one-more/<foo>', one_more_view),
])
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, function world!')
# Twice to test factory.
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, function world!')
req = webapp2.Request.blank('/other')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello again, function world!')
# Twice to test factory.
req = webapp2.Request.blank('/other')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello again, function world!')
req = webapp2.Request.blank('/one-more/bar')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello you too!')
def test_custom_method(self):
class MyHandler(webapp2.RequestHandler):
def my_method(self):
self.response.out.write('Hello, custom method world!')
def my_other_method(self):
self.response.out.write('Hello again, custom method world!')
app = webapp2.WSGIApplication([
webapp2.Route('/', MyHandler, handler_method='my_method'),
webapp2.Route('/other', MyHandler, handler_method='my_other_method'),
])
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, custom method world!')
req = webapp2.Request.blank('/other')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello again, custom method world!')
def test_custom_method_with_string(self):
app = webapp2.WSGIApplication([
webapp2.Route('/', handler='resources.handlers.CustomMethodHandler:custom_method'),
webapp2.Route('/bleh', handler='resources.handlers.CustomMethodHandler:custom_method'),
])
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'I am a custom method.')
req = webapp2.Request.blank('/bleh')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'I am a custom method.')
self.assertRaises(ValueError, webapp2.Route, '/', handler='resources.handlers.CustomMethodHandler:custom_method', handler_method='custom_method')
def test_factory_1(self):
app.debug = True
rsp = app.get_response('/bare')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'I am not a RequestHandler but I work.')
app.debug = False
def test_factory_2(self):
"""Very crazy stuff. Please ignore it."""
class MyHandler(object):
def __init__(self, request, response):
self.request = request
self.response = response
def __new__(cls, *args, **kwargs):
return cls.create_instance(*args, **kwargs)()
@classmethod
def create_instance(cls, *args, **kwargs):
obj = object.__new__(cls)
if isinstance(obj, cls):
obj.__init__(*args, **kwargs)
return obj
def __call__(self):
return self
def dispatch(self):
self.response.write('hello')
app = webapp2.WSGIApplication([
webapp2.Route('/', handler=MyHandler),
])
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'hello')
def test_encoding(self):
class PostHandler(webapp2.RequestHandler):
def post(self):
foo = self.request.POST['foo']
if not foo:
foo = 'empty'
self.response.write(foo)
app = webapp2.WSGIApplication([
webapp2.Route('/', PostHandler),
], debug=True)
# foo with umlauts in the vowels.
value = 'f\xc3\xb6\xc3\xb6'
rsp = app.get_response('/', POST={'foo': value},
headers=[('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')])
self.assertEqual(rsp.body, 'föö')
rsp = app.get_response('/', POST={'foo': value},
headers=[('Content-Type', 'application/x-www-form-urlencoded')])
self.assertEqual(rsp.body, 'föö')
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
from webapp2_extras import json
import test_base
class TestJson(test_base.BaseTestCase):
def test_encode(self):
self.assertEqual(json.encode(
'<script>alert("hello")</script>'),
'"<script>alert(\\"hello\\")<\\/script>"')
def test_decode(self):
self.assertEqual(json.decode(
'"<script>alert(\\"hello\\")<\\/script>"'),
'<script>alert("hello")</script>')
def test_b64encode(self):
self.assertEqual(json.b64encode(
'<script>alert("hello")</script>'),
'IjxzY3JpcHQ+YWxlcnQoXCJoZWxsb1wiKTxcL3NjcmlwdD4i')
def test_b64decode(self):
self.assertEqual(json.b64decode(
'IjxzY3JpcHQ+YWxlcnQoXCJoZWxsb1wiKTxcL3NjcmlwdD4i'),
'<script>alert("hello")</script>')
def test_quote(self):
self.assertEqual(json.quote('<script>alert("hello")</script>'),
'%22%3Cscript%3Ealert%28%5C%22hello%5C%22%29%3C%5C/script%3E%22')
def test_unquote(self):
self.assertEqual(json.unquote('%22%3Cscript%3Ealert%28%5C%22hello%5C%22%29%3C%5C/script%3E%22'),
'<script>alert("hello")</script>')
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import StringIO
import webapp2
import test_base
def _norm_req(s):
return '\r\n'.join(s.strip().replace('\r','').split('\n'))
_test_req = """
POST /webob/ HTTP/1.0
Accept: */*
Cache-Control: max-age=0
Content-Type: multipart/form-data; boundary=----------------------------deb95b63e42a
Host: pythonpaste.org
User-Agent: UserAgent/1.0 (identifier-version) library/7.0 otherlibrary/0.8
------------------------------deb95b63e42a
Content-Disposition: form-data; name="foo"
foo
------------------------------deb95b63e42a
Content-Disposition: form-data; name="bar"; filename="bar.txt"
Content-type: application/octet-stream
these are the contents of the file 'bar.txt'
------------------------------deb95b63e42a--
"""
_test_req2 = """
POST / HTTP/1.0
Content-Length: 0
"""
_test_req = _norm_req(_test_req)
_test_req2 = _norm_req(_test_req2) + '\r\n'
class TestRequest(test_base.BaseTestCase):
def test_charset(self):
req = webapp2.Request.blank('/', environ={
'CONTENT_TYPE': 'text/html; charset=ISO-8859-4',
})
self.assertEqual(req.content_type, 'text/html')
self.assertEqual(req.charset.lower(), 'iso-8859-4')
req = webapp2.Request.blank('/', environ={
'CONTENT_TYPE': 'application/json; charset="ISO-8859-1"',
})
self.assertEqual(req.content_type, 'application/json')
self.assertEqual(req.charset.lower(), 'iso-8859-1')
req = webapp2.Request.blank('/', environ={
'CONTENT_TYPE': 'application/json',
})
self.assertEqual(req.content_type, 'application/json')
self.assertEqual(req.charset.lower(), 'utf-8')
match = webapp2._charset_re.search('text/html')
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
self.assertEqual(charset, 'utf-8')
match = webapp2._charset_re.search('text/html; charset=ISO-8859-4')
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
self.assertEqual(charset, 'iso-8859-4')
match = webapp2._charset_re.search('text/html; charset="ISO-8859-4"')
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
self.assertEqual(charset, 'iso-8859-4')
match = webapp2._charset_re.search('text/html; charset= " ISO-8859-4 " ')
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
self.assertEqual(charset, 'iso-8859-4')
def test_unicode(self):
req = webapp2.Request.blank('/?1=2', POST='3=4')
res = req.GET.get('1')
self.assertEqual(res, '2')
self.assertTrue(isinstance(res, unicode))
res = req.POST.get('3')
self.assertEqual(res, '4')
self.assertTrue(isinstance(res, unicode))
def test_cookie_unicode(self):
import urllib
import base64
# With base64 ---------------------------------------------------------
value = base64.b64encode(u'á'.encode('utf-8'))
rsp = webapp2.Response()
rsp.set_cookie('foo', value)
cookie = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookie)])
self.assertEqual(req.cookies.get('foo'), value)
self.assertEqual(base64.b64decode(req.cookies.get('foo')).decode('utf-8'), u'á')
# Without quote -------------------------------------------------------
# Most recent WebOb versions take care of quoting.
# (not the version available on App Engine though)
value = u'föö=bär; föo, bär, bäz=dïng;'
rsp = webapp2.Response()
rsp.set_cookie('foo', value)
cookie = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookie)])
self.assertEqual(req.cookies.get('foo'), value)
# With quote, hard way ------------------------------------------------
# Here is our test value.
x = u'föö'
# We must store cookies quoted. To quote unicode, we need to encode it.
y = urllib.quote(x.encode('utf8'))
# The encoded, quoted string looks ugly.
self.assertEqual(y, 'f%C3%B6%C3%B6')
# But it is easy to get it back to our initial value.
z = urllib.unquote(y).decode('utf8')
# And it is indeed the same value.
self.assertEqual(z, x)
# Set a cookie using the encoded/quoted value.
rsp = webapp2.Response()
rsp.set_cookie('foo', y)
cookie = rsp.headers.get('Set-Cookie')
self.assertEqual(cookie, 'foo=f%C3%B6%C3%B6; Path=/')
# Get the cookie back.
req = webapp2.Request.blank('/', headers=[('Cookie', cookie)])
self.assertEqual(req.cookies.get('foo'), y)
# Here is our original value, again. Problem: the value is decoded
# before we had a chance to unquote it.
w = urllib.unquote(req.cookies.get('foo').encode('utf8')).decode('utf8')
# And it is indeed the same value.
self.assertEqual(w, x)
# With quote, easy way ------------------------------------------------
value = u'föö=bär; föo, bär, bäz=dïng;'
quoted_value = urllib.quote(value.encode('utf8'))
rsp = webapp2.Response()
rsp.set_cookie('foo', quoted_value)
cookie = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookie)])
cookie_value = req.cookies.get('foo')
unquoted_cookie_value = urllib.unquote(cookie_value.encode('utf8')).decode('utf8')
self.assertEqual(cookie_value, quoted_value)
self.assertEqual(unquoted_cookie_value, value)
def test_get(self):
req = webapp2.Request.blank('/?1=2&1=3&3=4', POST='5=6&7=8')
res = req.get('1')
self.assertEqual(res, '2')
res = req.get_all('1')
self.assertEqual(res, ['2', '3'])
res = req.get('8')
self.assertEqual(res, '')
res = req.get_all('8')
self.assertEqual(res, [])
res = req.get('8', default_value='9')
self.assertEqual(res, '9')
def test_get_with_POST(self):
req = webapp2.Request.blank('/?1=2&1=3&3=4', POST={5: 6, 7: 8},
unicode_errors='ignore')
res = req.get('1')
self.assertEqual(res, '2')
res = req.get_all('1')
self.assertEqual(res, ['2', '3'])
res = req.get('8')
self.assertEqual(res, '')
res = req.get_all('8')
self.assertEqual(res, [])
res = req.get('8', default_value='9')
self.assertEqual(res, '9')
def test_arguments(self):
req = webapp2.Request.blank('/?1=2&3=4', POST='5=6&7=8')
res = req.arguments()
self.assertEqual(res, ['1', '3', '5', '7'])
def test_get_range(self):
req = webapp2.Request.blank('/')
res = req.get_range('1', min_value=None, max_value=None, default=None)
self.assertEqual(res, None)
req = webapp2.Request.blank('/?1=2')
res = req.get_range('1', min_value=None, max_value=None, default=0)
self.assertEqual(res, 2)
req = webapp2.Request.blank('/?1=foo')
res = req.get_range('1', min_value=1, max_value=99, default=100)
self.assertEqual(res, 99)
req = webapp2.Request.blank('/?a=4')
res = req.get_range('a', min_value=10, max_value=20, default=100)
self.assertEqual(res, 10)
def test_issue_3426(self):
"""When the content-type is 'application/x-www-form-urlencoded' and
POST data is empty the content-type is dropped by Google appengine.
"""
req = webapp2.Request.blank('/', environ={
'REQUEST_METHOD': 'GET',
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
})
self.assertEqual(req.method, 'GET')
self.assertEqual(req.content_type, 'application/x-www-form-urlencoded')
# XXX: These tests fail when request charset is set to utf-8 by default.
# Otherwise they pass.
'''
def test_get_with_FieldStorage(self):
if not test_base.check_webob_version(1.0):
return
# A valid request without a Content-Length header should still read
# the full body.
# Also test parity between as_string and from_string / from_file.
import cgi
req = webapp2.Request.from_string(_test_req)
self.assertTrue(isinstance(req, webapp2.Request))
self.assertTrue(not repr(req).endswith('(invalid WSGI environ)>'))
self.assertTrue('\n' not in req.http_version or '\r' in req.http_version)
self.assertTrue(',' not in req.host)
self.assertTrue(req.content_length is not None)
self.assertEqual(req.content_length, 337)
self.assertTrue('foo' in req.body)
bar_contents = "these are the contents of the file 'bar.txt'\r\n"
self.assertTrue(bar_contents in req.body)
self.assertEqual(req.params['foo'], 'foo')
bar = req.params['bar']
self.assertTrue(isinstance(bar, cgi.FieldStorage))
self.assertEqual(bar.type, 'application/octet-stream')
bar.file.seek(0)
self.assertEqual(bar.file.read(), bar_contents)
bar = req.get_all('bar')
self.assertEqual(bar[0], bar_contents)
# out should equal contents, except for the Content-Length header,
# so insert that.
_test_req_copy = _test_req.replace('Content-Type',
'Content-Length: 337\r\nContent-Type')
self.assertEqual(str(req), _test_req_copy)
req2 = webapp2.Request.from_string(_test_req2)
self.assertTrue('host' not in req2.headers)
self.assertEqual(str(req2), _test_req2.rstrip())
self.assertRaises(ValueError,
webapp2.Request.from_string, _test_req2 + 'xx')
def test_issue_5118(self):
"""Unable to read POST variables ONCE self.request.body is read."""
if not test_base.check_webob_version(1.0):
return
import cgi
req = webapp2.Request.from_string(_test_req)
fieldStorage = req.POST.get('bar')
self.assertTrue(isinstance(fieldStorage, cgi.FieldStorage))
self.assertEqual(fieldStorage.type, 'application/octet-stream')
# Double read.
fieldStorage = req.POST.get('bar')
self.assertTrue(isinstance(fieldStorage, cgi.FieldStorage))
self.assertEqual(fieldStorage.type, 'application/octet-stream')
# Now read the body.
x = req.body
fieldStorage = req.POST.get('bar')
self.assertTrue(isinstance(fieldStorage, cgi.FieldStorage))
self.assertEqual(fieldStorage.type, 'application/octet-stream')
'''
if __name__ == '__main__':
test_base.main()
| Python |
import webapp2
from webapp2_extras import sessions
from webapp2_extras import auth
from webapp2_extras.appengine.auth import models
from google.appengine.ext.ndb import model
import test_base
class TestAuth(test_base.BaseTestCase):
def setUp(self):
super(TestAuth, self).setUp()
self.register_model('User', models.User)
self.register_model('UserToken', models.UserToken)
self.register_model('Unique', models.Unique)
def _check_token(self, user_id, token, subject='auth'):
rv = models.UserToken.get(user=user_id, subject=subject, token=token)
return rv is not None
def test_get_user_by_session(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'foo',
}
})
req = webapp2.Request.blank('/')
rsp = webapp2.Response()
req.app = app
s = auth.get_store(app=app)
a = auth.Auth(request=req)
session_store = sessions.get_store(request=req)
# This won't work.
a.set_session_data({})
self.assertEqual(a.session.get('_user'), None)
# This won't work.
a.session['_user'] = {}
self.assertEqual(a.get_session_data(), None)
self.assertEqual(a.session.get('_user'), None)
# Create a user.
m = models.User
success, user = m.create_user(auth_id='auth_id',
password_raw='password')
user_id = user.key.id()
# Get user with session. An anonymous_user is returned.
rv = a.get_user_by_session()
self.assertTrue(rv is None)
# Login with password. User dict is returned.
rv = a.get_user_by_password('auth_id', 'password')
self.assertEqual(rv['user_id'], user_id)
# Save sessions.
session_store.save_sessions(rsp)
# Get user with session. Voila!
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
rsp = webapp2.Response()
req.app = app
a = auth.Auth(request=req)
# only auth_id is returned when there're no
# custom user attributes defined.
rv = a.get_user_by_session()
self.assertEqual(rv['user_id'], user_id)
# If we call get_user_by_token() now, the same user is returned.
rv2 = a.get_user_by_token(rv['user_id'], rv['token'])
self.assertTrue(rv is rv2)
# Let's get it again and check that token is the same.
token = rv['token']
a._user = None
rv = a.get_user_by_session()
self.assertEqual(rv['user_id'], user_id)
self.assertEqual(rv['token'], token)
# Now let's force token to be renewed and check that we have a new one.
s.config['token_new_age'] = -300
a._user = None
rv = a.get_user_by_session()
self.assertEqual(rv['user_id'], user_id)
self.assertNotEqual(rv['token'], token)
# Now let's force token to be invalid.
s.config['token_max_age'] = -300
a._user = None
rv = a.get_user_by_session()
self.assertEqual(rv, None)
def test_get_user_by_password(self):
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'foo',
}
})
req = webapp2.Request.blank('/')
req.app = app
s = auth.get_store(app=app)
a = auth.get_auth(request=req)
session_store = sessions.get_store(request=req)
m = models.User
success, user = m.create_user(auth_id='auth_id',
password_raw='password')
user_id = user.key.id()
# Lets test the cookie max_age when we use remember=True or False.
rv = a.get_user_by_password('auth_id', 'password', remember=True)
self.assertEqual(rv['user_id'], user_id)
self.assertEqual(session_store.sessions['auth'].session_args['max_age'],
86400 * 7 * 3)
# Now remember=False.
rv = a.get_user_by_password('auth_id', 'password')
self.assertEqual(rv['user_id'], user_id)
self.assertEqual(session_store.sessions['auth'].session_args['max_age'],
None)
# User was set so getting it from session will return the same one.
rv = a.get_user_by_session()
self.assertEqual(rv['user_id'], user_id)
# Now try a failed password submission: user will be unset.
rv = a.get_user_by_password('auth_id', 'password_2', silent=True)
self.assertTrue(rv is None)
# And getting by session will no longer work.
rv = a.get_user_by_session()
self.assertTrue(rv is None)
def test_validate_password(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
s = auth.get_store(app=app)
m = models.User
success, user = m.create_user(auth_id='auth_id',
password_raw='foo')
u = s.validate_password('auth_id', 'foo')
self.assertEqual(u, s.user_to_dict(user))
self.assertRaises(auth.InvalidPasswordError,
s.validate_password, 'auth_id', 'bar')
self.assertRaises(auth.InvalidAuthIdError,
s.validate_password, 'auth_id_2', 'foo')
def test_validate_token(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
s = auth.get_store(app=app)
rv = s.validate_token('auth_id', 'token')
self.assertEqual(rv, (None, None))
# Expired timestamp.
rv = s.validate_token('auth_id', 'token', -300)
self.assertEqual(rv, (None, None))
m = models.User
success, user = m.create_user(auth_id='auth_id',
password_raw='foo')
user_id = user.key.id()
token = m.create_auth_token(user_id)
rv = s.validate_token(user_id, token)
self.assertEqual(rv, (s.user_to_dict(user), token))
# Token must still be there.
self.assertTrue(self._check_token(user_id, token))
# Expired timestamp.
token = m.create_auth_token(user_id)
rv = s.validate_token(user_id, token, -300)
self.assertEqual(rv, (None, None))
# Token must have been deleted.
self.assertFalse(self._check_token(user_id, token))
# Force expiration.
token = m.create_auth_token(user_id)
s.config['token_max_age'] = -300
rv = s.validate_token(user_id, token)
self.assertEqual(rv, (None, None))
# Token must have been deleted.
self.assertFalse(self._check_token(user_id, token))
# Revert expiration, force renewal.
token = m.create_auth_token(user_id)
s.config['token_max_age'] = 86400 * 7 * 3
s.config['token_new_age'] = -300
rv = s.validate_token(user_id, token)
self.assertEqual(rv, (s.user_to_dict(user), None))
# Token must have been deleted.
self.assertFalse(self._check_token(user_id, token))
def test_set_auth_store(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
store = auth.AuthStore(app)
self.assertEqual(len(app.registry), 0)
auth.set_store(store, app=app)
self.assertEqual(len(app.registry), 1)
s = auth.get_store(app=app)
self.assertTrue(isinstance(s, auth.AuthStore))
def test_get_auth_store(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
self.assertEqual(len(app.registry), 0)
s = auth.get_store(app=app)
self.assertEqual(len(app.registry), 1)
self.assertTrue(isinstance(s, auth.AuthStore))
def test_set_auth(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
a = auth.Auth(req)
self.assertEqual(len(req.registry), 0)
auth.set_auth(a, request=req)
self.assertEqual(len(req.registry), 1)
a = auth.get_auth(request=req)
self.assertTrue(isinstance(a, auth.Auth))
def test_get_auth(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
self.assertEqual(len(req.registry), 0)
a = auth.get_auth(request=req)
self.assertEqual(len(req.registry), 1)
self.assertTrue(isinstance(a, auth.Auth))
'''
def test_set_callables(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
s = auth.get_store(app=app)
def validate_password(store, auth_id, password):
self.assertTrue(store is s)
self.assertEqual(auth_id, 'auth_id')
self.assertEqual(password, 'password')
return 'validate_password'
def validate_token(store, auth_id, token, token_ts=None):
self.assertTrue(store is s)
self.assertEqual(auth_id, 'auth_id')
self.assertEqual(token, 'token')
self.assertEqual(token_ts, 'token_ts')
return 'validate_token'
s.set_password_validator(validate_password)
rv = s.validate_password('auth_id', 'password')
self.assertEqual(rv, 'validate_password')
s.set_token_validator(validate_token)
rv = s.validate_token('auth_id', 'token', 'token_ts')
self.assertEqual(rv, 'validate_token')
'''
def test_extended_user(self):
class MyUser(models.User):
newsletter = model.BooleanProperty()
age = model.IntegerProperty()
auth_id = 'own:username'
success, info = MyUser.create_user(auth_id, newsletter=True, age=22)
self.assertTrue(success)
app = webapp2.WSGIApplication(config={
'webapp2_extras.auth': {
'user_model': MyUser,
}
})
s = auth.get_store(app=app)
user = s.user_model.get_by_auth_id(auth_id)
self.assertEqual(info, user)
self.assertEqual(user.age, 22)
self.assertTrue(user.newsletter is True)
if __name__ == '__main__':
test_base.main()
| Python |
from __future__ import division
from jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, TemplateNotFound
name = 'template1.html'
def root(context):
l_message = context.resolve('message')
if 0: yield None
yield to_string(l_message)
blocks = {}
debug_info = '1=8' | Python |
from protorpc import messages
from protorpc import remote
class BonjourRequest(messages.Message):
my_name = messages.StringField(1, required=True)
class BonjourResponse(messages.Message):
hello = messages.StringField(1, required=True)
class BonjourService(remote.Service):
@remote.method(BonjourRequest, BonjourResponse)
def bonjour(self, request):
return BonjourResponse(hello='Bonjour, %s!' %
request.my_name)
class CiaoRequest(messages.Message):
my_name = messages.StringField(1, required=True)
class CiaoResponse(messages.Message):
hello = messages.StringField(1, required=True)
class CiaoService(remote.Service):
@remote.method(CiaoRequest, CiaoResponse)
def ciao(self, request):
return CiaoResponse(hello='Ciao, %s!' %
request.my_name)
| Python |
default_config = {
'templates_dir': 'templates',
}
| Python |
import webapp2
class LazyHandler(webapp2.RequestHandler):
def get(self, **kwargs):
self.response.out.write('I am a laaazy view.')
class CustomMethodHandler(webapp2.RequestHandler):
def custom_method(self):
self.response.out.write('I am a custom method.')
def handle_exception(request, response, exception):
return webapp2.Response(body='Hello, custom response world!')
| Python |
from webapp2_extras import config
from webapp2_extras import i18n
default_config = {
'locale': 'en_US',
'timezone': 'America/Chicago',
'required': config.REQUIRED_VALUE,
}
def locale_selector(store, request):
return i18n.get_store().default_locale
def timezone_selector(store, request):
return i18n.get_store().default_timezone
| Python |
from webapp2_extras import auth
from webapp2_extras.appengine.auth import models
from google.appengine.ext.ndb import model
import test_base
class UniqueConstraintViolation(Exception):
pass
class User(model.Model):
username = model.StringProperty(required=True)
auth_id = model.StringProperty()
email = model.StringProperty()
class TestAuthModels(test_base.BaseTestCase):
def setUp(self):
super(TestAuthModels, self).setUp()
self.register_model('User', models.User)
self.register_model('UserToken', models.UserToken)
self.register_model('Unique', models.Unique)
def test_get(self):
m = models.User
success, user = m.create_user(auth_id='auth_id_1', password_raw='foo')
self.assertEqual(success, True)
self.assertTrue(user is not None)
self.assertTrue(user.password is not None)
# user.key.id() is required to retrieve the auth token
user_id = user.key.id()
token = m.create_auth_token(user_id)
self.assertEqual(m.get_by_auth_id('auth_id_1'), user)
self.assertEqual(m.get_by_auth_id('auth_id_2'), None)
u, ts = m.get_by_auth_token(user_id, token)
self.assertEqual(u, user)
u, ts = m.get_by_auth_token('fake_user_id', token)
self.assertEqual(u, None)
u = m.get_by_auth_password('auth_id_1', 'foo')
self.assertEqual(u, user)
self.assertRaises(auth.InvalidPasswordError,
m.get_by_auth_password, 'auth_id_1', 'bar')
self.assertRaises(auth.InvalidAuthIdError,
m.get_by_auth_password, 'auth_id_2', 'foo')
def test_create_user(self):
m = models.User
success, info = m.create_user(auth_id='auth_id_1', password_raw='foo')
self.assertEqual(success, True)
self.assertTrue(info is not None)
self.assertTrue(info.password is not None)
success, info = m.create_user(auth_id='auth_id_1')
self.assertEqual(success, False)
self.assertEqual(info, ['auth_id'])
# 3 extras and unique properties; plus 1 extra and not unique.
extras = ['foo', 'bar', 'baz']
values = dict((v, v + '_value') for v in extras)
values['ding'] = 'ding_value'
success, info = m.create_user(auth_id='auth_id_2',
unique_properties=extras, **values)
self.assertEqual(success, True)
self.assertTrue(info is not None)
for prop in extras:
self.assertEqual(getattr(info, prop), prop + '_value')
self.assertEqual(info.ding, 'ding_value')
# Let's do it again.
success, info = m.create_user(auth_id='auth_id_3',
unique_properties=extras, **values)
self.assertEqual(success, False)
self.assertEqual(info, extras)
def test_add_auth_ids(self):
m = models.User
success, new_user = m.create_user(auth_id='auth_id_1', password_raw='foo')
self.assertEqual(success, True)
self.assertTrue(new_user is not None)
self.assertTrue(new_user.password is not None)
success, new_user_2 = m.create_user(auth_id='auth_id_2', password_raw='foo')
self.assertEqual(success, True)
self.assertTrue(new_user is not None)
self.assertTrue(new_user.password is not None)
success, info = new_user.add_auth_id('auth_id_3')
self.assertEqual(success, True)
self.assertEqual(info.auth_ids, ['auth_id_1', 'auth_id_3'])
success, info = new_user.add_auth_id('auth_id_2')
self.assertEqual(success, False)
self.assertEqual(info, ['auth_id'])
def test_token(self):
m = models.UserToken
auth_id = 'foo'
subject = 'bar'
token_1 = m.create(auth_id, subject, token=None)
token = token_1.token
token_2 = m.get(user=auth_id, subject=subject, token=token)
self.assertEqual(token_2, token_1)
token_3 = m.get(subject=subject, token=token)
self.assertEqual(token_3, token_1)
m.get_key(auth_id, subject, token).delete()
token_2 = m.get(user=auth_id, subject=subject, token=token)
self.assertEqual(token_2, None)
token_3 = m.get(subject=subject, token=token)
self.assertEqual(token_3, None)
def test_user_token(self):
m = models.User
auth_id = 'foo'
token = m.create_auth_token(auth_id)
self.assertTrue(m.validate_auth_token(auth_id, token))
m.delete_auth_token(auth_id, token)
self.assertFalse(m.validate_auth_token(auth_id, token))
token = m.create_signup_token(auth_id)
self.assertTrue(m.validate_signup_token(auth_id, token))
m.delete_signup_token(auth_id, token)
self.assertFalse(m.validate_signup_token(auth_id, token))
class TestUniqueModel(test_base.BaseTestCase):
def setUp(self):
super(TestUniqueModel, self).setUp()
self.register_model('Unique', models.Unique)
def test_single(self):
def create_user(username):
# Assemble the unique scope/value combinations.
unique_username = 'User.username:%s' % username
# Create the unique username, auth_id and email.
success = models.Unique.create(unique_username)
if success:
user = User(username=username)
user.put()
return user
else:
raise UniqueConstraintViolation('Username %s already '
'exists' % username)
user = create_user('username_1')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_1')
user = create_user('username_2')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_2')
def test_multi(self):
def create_user(username, auth_id, email):
# Assemble the unique scope/value combinations.
unique_username = 'User.username:%s' % username
unique_auth_id = 'User.auth_id:%s' % auth_id
unique_email = 'User.email:%s' % email
# Create the unique username, auth_id and email.
uniques = [unique_username, unique_auth_id, unique_email]
success, existing = models.Unique.create_multi(uniques)
if success:
user = User(username=username, auth_id=auth_id, email=email)
user.put()
return user
else:
if unique_username in existing:
raise UniqueConstraintViolation('Username %s already '
'exists' % username)
if unique_auth_id in existing:
raise UniqueConstraintViolation('Auth id %s already '
'exists' % auth_id)
if unique_email in existing:
raise UniqueConstraintViolation('Email %s already '
'exists' % email)
user = create_user('username_1', 'auth_id_1', 'email_1')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_1', 'auth_id_2', 'email_2')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_2', 'auth_id_1', 'email_2')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_2', 'auth_id_2', 'email_1')
user = create_user('username_2', 'auth_id_2', 'email_2')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_2', 'auth_id_1', 'email_1')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_1', 'auth_id_2', 'email_1')
self.assertRaises(UniqueConstraintViolation, create_user, 'username_1', 'auth_id_1', 'email_2')
def test_delete_multi(self):
rv = models.Unique.create_multi(('foo', 'bar', 'baz'))
self.assertEqual(rv, (True, []))
rv = models.Unique.create_multi(('foo', 'bar', 'baz'))
self.assertEqual(rv, (False, ['foo', 'bar', 'baz']))
models.Unique.delete_multi(('foo', 'bar', 'baz'))
rv = models.Unique.create_multi(('foo', 'bar', 'baz'))
self.assertEqual(rv, (True, []))
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webapp2
from webapp2_extras import sessions
from webapp2_extras import sessions_memcache
import test_base
app = webapp2.WSGIApplication(config={
'webapp2_extras.sessions': {
'secret_key': 'my-super-secret',
},
})
class TestMemcacheSession(test_base.BaseTestCase):
#factory = sessions_memcache.MemcacheSessionFactory
def test_get_save_session(self):
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
rsp = webapp2.Response()
# Nothing changed, we want to test anyway.
store.save_sessions(rsp)
session['a'] = 'b'
session['c'] = 'd'
session['e'] = 'f'
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
session['g'] = 'h'
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 3 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
self.assertEqual(session['a'], 'b')
self.assertEqual(session['c'], 'd')
self.assertEqual(session['e'], 'f')
self.assertEqual(session['g'], 'h')
def test_flashes(self):
# Round 1 -------------------------------------------------------------
req = webapp2.Request.blank('/')
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
flashes = session.get_flashes()
self.assertEqual(flashes, [])
session.add_flash('foo')
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 2 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
flashes = session.get_flashes()
self.assertEqual(flashes, [(u'foo', None)])
flashes = session.get_flashes()
self.assertEqual(flashes, [])
session.add_flash('bar')
session.add_flash('baz', 'important')
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 3 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
flashes = session.get_flashes()
self.assertEqual(flashes, [(u'bar', None), (u'baz', 'important')])
flashes = session.get_flashes()
self.assertEqual(flashes, [])
rsp = webapp2.Response()
store.save_sessions(rsp)
# Round 4 -------------------------------------------------------------
cookies = rsp.headers.get('Set-Cookie')
req = webapp2.Request.blank('/', headers=[('Cookie', cookies)])
req.app = app
store = sessions.SessionStore(req)
session = store.get_session(backend='memcache')
flashes = session.get_flashes()
self.assertEqual(flashes, [])
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import datetime
import gettext as gettext_stdlib
import os
from babel.numbers import NumberFormatError
from pytz.gae import pytz
import webapp2
from webapp2_extras import i18n
import test_base
class I18nTestCase(test_base.BaseTestCase):
def setUp(self):
super(I18nTestCase, self).setUp()
app = webapp2.WSGIApplication()
request = webapp2.Request.blank('/')
request.app = app
app.set_globals(app=app, request=request)
self.app = app
self.request = request
#==========================================================================
# _(), gettext(), ngettext(), lazy_gettext(), lazy_ngettext()
#==========================================================================
def test_translations_not_set(self):
# We release it here because it is set on setUp()
self.app.clear_globals()
self.assertRaises(AssertionError, i18n.gettext, 'foo')
def test_gettext(self):
self.assertEqual(i18n.gettext('foo'), u'foo')
def test_gettext_(self):
self.assertEqual(i18n._('foo'), u'foo')
def test_gettext_with_variables(self):
self.assertEqual(i18n.gettext('foo %(foo)s'), u'foo %(foo)s')
self.assertEqual(i18n.gettext('foo %(foo)s') % {'foo': 'bar'}, u'foo bar')
self.assertEqual(i18n.gettext('foo %(foo)s', foo='bar'), u'foo bar')
def test_ngettext(self):
self.assertEqual(i18n.ngettext('One foo', 'Many foos', 1), u'One foo')
self.assertEqual(i18n.ngettext('One foo', 'Many foos', 2), u'Many foos')
def test_ngettext_with_variables(self):
self.assertEqual(i18n.ngettext('One foo %(foo)s', 'Many foos %(foo)s', 1), u'One foo %(foo)s')
self.assertEqual(i18n.ngettext('One foo %(foo)s', 'Many foos %(foo)s', 2), u'Many foos %(foo)s')
self.assertEqual(i18n.ngettext('One foo %(foo)s', 'Many foos %(foo)s', 1, foo='bar'), u'One foo bar')
self.assertEqual(i18n.ngettext('One foo %(foo)s', 'Many foos %(foo)s', 2, foo='bar'), u'Many foos bar')
self.assertEqual(i18n.ngettext('One foo %(foo)s', 'Many foos %(foo)s', 1) % {'foo': 'bar'}, u'One foo bar')
self.assertEqual(i18n.ngettext('One foo %(foo)s', 'Many foos %(foo)s', 2) % {'foo': 'bar'}, u'Many foos bar')
def test_lazy_gettext(self):
self.assertEqual(i18n.lazy_gettext('foo'), u'foo')
#==========================================================================
# Date formatting
#==========================================================================
def test_format_date(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_date(value, format='short'), u'11/10/09')
self.assertEqual(i18n.format_date(value, format='medium'), u'Nov 10, 2009')
self.assertEqual(i18n.format_date(value, format='long'), u'November 10, 2009')
self.assertEqual(i18n.format_date(value, format='full'), u'Tuesday, November 10, 2009')
def test_format_date_no_format(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_date(value), u'Nov 10, 2009')
'''
def test_format_date_no_format_but_configured(self):
app = App(config={
'tipfy.sessions': {
'secret_key': 'secret',
},
'tipfy.i18n': {
'timezone': 'UTC',
'date_formats': {
'time': 'medium',
'date': 'medium',
'datetime': 'medium',
'time.short': None,
'time.medium': None,
'time.full': None,
'time.long': None,
'date.short': None,
'date.medium': 'full',
'date.full': None,
'date.long': None,
'datetime.short': None,
'datetime.medium': None,
'datetime.full': None,
'datetime.long': None,
}
}
})
local.request = request = Request.from_values('/')
request.app = app
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_date(value), u'Tuesday, November 10, 2009')
'''
def test_format_date_pt_BR(self):
i18n.get_i18n().set_locale('pt_BR')
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_date(value, format='short'), u'10/11/09')
self.assertEqual(i18n.format_date(value, format='medium'), u'10/11/2009')
self.assertEqual(i18n.format_date(value, format='long'), u'10 de novembro de 2009')
self.assertEqual(i18n.format_date(value, format='full'), u'terça-feira, 10 de novembro de 2009')
def test_format_datetime(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_datetime(value, format='short'), u'11/10/09 4:36 PM')
self.assertEqual(i18n.format_datetime(value, format='medium'), u'Nov 10, 2009 4:36:05 PM')
self.assertEqual(i18n.format_datetime(value, format='long'), u'November 10, 2009 4:36:05 PM +0000')
#self.assertEqual(i18n.format_datetime(value, format='full'), u'Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time')
self.assertEqual(i18n.format_datetime(value, format='full'), u'Tuesday, November 10, 2009 4:36:05 PM GMT+00:00')
i18n.get_i18n().set_timezone('America/Chicago')
self.assertEqual(i18n.format_datetime(value, format='short'), u'11/10/09 10:36 AM')
def test_format_datetime_no_format(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_datetime(value), u'Nov 10, 2009 4:36:05 PM')
def test_format_datetime_pt_BR(self):
i18n.get_i18n().set_locale('pt_BR')
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_datetime(value, format='short'), u'10/11/09 16:36')
self.assertEqual(i18n.format_datetime(value, format='medium'), u'10/11/2009 16:36:05')
#self.assertEqual(i18n.format_datetime(value, format='long'), u'10 de novembro de 2009 16:36:05 +0000')
self.assertEqual(i18n.format_datetime(value, format='long'), u'10 de novembro de 2009 16h36min05s +0000')
#self.assertEqual(i18n.format_datetime(value, format='full'), u'terça-feira, 10 de novembro de 2009 16h36min05s Horário Mundo (GMT)')
self.assertEqual(i18n.format_datetime(value, format='full'), u'ter\xe7a-feira, 10 de novembro de 2009 16h36min05s GMT+00:00')
def test_format_time(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_time(value, format='short'), u'4:36 PM')
self.assertEqual(i18n.format_time(value, format='medium'), u'4:36:05 PM')
self.assertEqual(i18n.format_time(value, format='long'), u'4:36:05 PM +0000')
#self.assertEqual(i18n.format_time(value, format='full'), u'4:36:05 PM World (GMT) Time')
self.assertEqual(i18n.format_time(value, format='full'), u'4:36:05 PM GMT+00:00')
def test_format_time_no_format(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_time(value), u'4:36:05 PM')
def test_format_time_pt_BR(self):
i18n.get_i18n().set_locale('pt_BR')
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_time(value, format='short'), u'16:36')
self.assertEqual(i18n.format_time(value, format='medium'), u'16:36:05')
#self.assertEqual(i18n.format_time(value, format='long'), u'16:36:05 +0000')
self.assertEqual(i18n.format_time(value, format='long'), u'16h36min05s +0000')
#self.assertEqual(i18n.format_time(value, format='full'), u'16h36min05s Horário Mundo (GMT)')
self.assertEqual(i18n.format_time(value, format='full'), u'16h36min05s GMT+00:00')
i18n.get_i18n().set_timezone('America/Chicago')
self.assertEqual(i18n.format_time(value, format='short'), u'10:36')
def test_parse_date(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.parse_date('4/1/04'), datetime.date(2004, 4, 1))
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.parse_date('01.04.2004'), datetime.date(2004, 4, 1))
def test_parse_datetime(self):
i18n.get_i18n().set_locale('en_US')
self.assertRaises(NotImplementedError, i18n.parse_datetime, '4/1/04 16:08:09')
def test_parse_time(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.parse_time('18:08:09'), datetime.time(18, 8, 9))
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.parse_time('18:08:09'), datetime.time(18, 8, 9))
def test_format_timedelta(self):
# This is only present in Babel dev, so skip if not available.
if not getattr(i18n, 'format_timedelta', None):
return
i18n.get_i18n().set_locale('en_US')
# ???
# self.assertEqual(i18n.format_timedelta(datetime.timedelta(weeks=12)), u'3 months')
self.assertEqual(i18n.format_timedelta(datetime.timedelta(weeks=12)), u'3 mths')
i18n.get_i18n().set_locale('es')
# self.assertEqual(i18n.format_timedelta(datetime.timedelta(seconds=1)), u'1 segundo')
self.assertEqual(i18n.format_timedelta(datetime.timedelta(seconds=1)), u'1 s')
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.format_timedelta(datetime.timedelta(hours=3), granularity='day'), u'1 day')
self.assertEqual(i18n.format_timedelta(datetime.timedelta(hours=23), threshold=0.9), u'1 day')
# self.assertEqual(i18n.format_timedelta(datetime.timedelta(hours=23), threshold=1.1), u'23 hours')
self.assertEqual(i18n.format_timedelta(datetime.timedelta(hours=23), threshold=1.1), u'23 hrs')
self.assertEqual(i18n.format_timedelta(datetime.datetime.now() - datetime.timedelta(days=5)), u'5 days')
def test_format_iso(self):
value = datetime.datetime(2009, 11, 10, 16, 36, 05)
self.assertEqual(i18n.format_date(value, format='iso'), u'2009-11-10')
self.assertEqual(i18n.format_time(value, format='iso'), u'16:36:05')
self.assertEqual(i18n.format_datetime(value, format='iso'), u'2009-11-10T16:36:05+0000')
#==========================================================================
# Timezones
#==========================================================================
def test_set_timezone(self):
i18n.get_i18n().set_timezone('UTC')
self.assertEqual(i18n.get_i18n().tzinfo.zone, 'UTC')
i18n.get_i18n().set_timezone('America/Chicago')
self.assertEqual(i18n.get_i18n().tzinfo.zone, 'America/Chicago')
i18n.get_i18n().set_timezone('America/Sao_Paulo')
self.assertEqual(i18n.get_i18n().tzinfo.zone, 'America/Sao_Paulo')
def test_to_local_timezone(self):
i18n.get_i18n().set_timezone('US/Eastern')
format = '%Y-%m-%d %H:%M:%S %Z%z'
# Test datetime with timezone set
base = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=pytz.UTC)
localtime = i18n.to_local_timezone(base)
result = localtime.strftime(format)
self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')
# Test naive datetime - no timezone set
base = datetime.datetime(2002, 10, 27, 6, 0, 0)
localtime = i18n.to_local_timezone(base)
result = localtime.strftime(format)
self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')
def test_to_utc(self):
i18n.get_i18n().set_timezone('US/Eastern')
format = '%Y-%m-%d %H:%M:%S'
# Test datetime with timezone set
base = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=pytz.UTC)
localtime = i18n.to_utc(base)
result = localtime.strftime(format)
self.assertEqual(result, '2002-10-27 06:00:00')
# Test naive datetime - no timezone set
base = datetime.datetime(2002, 10, 27, 6, 0, 0)
localtime = i18n.to_utc(base)
result = localtime.strftime(format)
self.assertEqual(result, '2002-10-27 11:00:00')
def test_get_timezone_location(self):
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/St_Johns')), u'Kanada (St. John\'s)')
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/Mexico_City')), u'Mexiko (Mexiko-Stadt)')
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.get_timezone_location(pytz.timezone('Europe/Berlin')), u'Deutschland')
#==========================================================================
# Number formatting
#==========================================================================
def test_format_number(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.format_number(1099), u'1,099')
def test_format_decimal(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.format_decimal(1.2345), u'1.234')
self.assertEqual(i18n.format_decimal(1.2346), u'1.235')
self.assertEqual(i18n.format_decimal(-1.2346), u'-1.235')
self.assertEqual(i18n.format_decimal(12345.5), u'12,345.5')
i18n.get_i18n().set_locale('sv_SE')
self.assertEqual(i18n.format_decimal(1.2345), u'1,234')
i18n.get_i18n().set_locale('de')
self.assertEqual(i18n.format_decimal(12345), u'12.345')
def test_format_currency(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.format_currency(1099.98, 'USD'), u'$1,099.98')
self.assertEqual(i18n.format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00'), u'EUR 1,099.98')
i18n.get_i18n().set_locale('es_CO')
self.assertEqual(i18n.format_currency(1099.98, 'USD'), u'US$\xa01.099,98')
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.format_currency(1099.98, 'EUR'), u'1.099,98\xa0\u20ac')
def test_format_percent(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.format_percent(0.34), u'34%')
self.assertEqual(i18n.format_percent(25.1234), u'2,512%')
self.assertEqual(i18n.format_percent(25.1234, u'#,##0\u2030'), u'25,123\u2030')
i18n.get_i18n().set_locale('sv_SE')
self.assertEqual(i18n.format_percent(25.1234), u'2\xa0512\xa0%')
def test_format_scientific(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.format_scientific(10000), u'1E4')
self.assertEqual(i18n.format_scientific(1234567, u'##0E00'), u'1.23E06')
def test_parse_number(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.parse_number('1,099'), 1099L)
i18n.get_i18n().set_locale('de_DE')
self.assertEqual(i18n.parse_number('1.099'), 1099L)
def test_parse_number2(self):
i18n.get_i18n().set_locale('de')
self.assertRaises(NumberFormatError, i18n.parse_number, '1.099,98')
def test_parse_decimal(self):
i18n.get_i18n().set_locale('en_US')
self.assertEqual(i18n.parse_decimal('1,099.98'), 1099.98)
i18n.get_i18n().set_locale('de')
self.assertEqual(i18n.parse_decimal('1.099,98'), 1099.98)
def test_parse_decimal_error(self):
i18n.get_i18n().set_locale('de')
self.assertRaises(NumberFormatError, i18n.parse_decimal, '2,109,998')
def test_set_i18n_store(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
store = i18n.I18nStore(app)
self.assertEqual(len(app.registry), 0)
i18n.set_store(store, app=app)
self.assertEqual(len(app.registry), 1)
s = i18n.get_store(app=app)
self.assertTrue(isinstance(s, i18n.I18nStore))
def test_get_i18n_store(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
self.assertEqual(len(app.registry), 0)
s = i18n.get_store(app=app)
self.assertEqual(len(app.registry), 1)
self.assertTrue(isinstance(s, i18n.I18nStore))
def test_set_i18n(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
store = i18n.I18n(req)
self.assertEqual(len(app.registry), 1)
self.assertEqual(len(req.registry), 0)
i18n.set_i18n(store, request=req)
self.assertEqual(len(app.registry), 1)
self.assertEqual(len(req.registry), 1)
i = i18n.get_i18n(request=req)
self.assertTrue(isinstance(i, i18n.I18n))
def test_get_i18n(self):
app = webapp2.WSGIApplication()
req = webapp2.Request.blank('/')
req.app = app
self.assertEqual(len(app.registry), 0)
self.assertEqual(len(req.registry), 0)
i = i18n.get_i18n(request=req)
self.assertEqual(len(app.registry), 1)
self.assertEqual(len(req.registry), 1)
self.assertTrue(isinstance(i, i18n.I18n))
def test_set_locale_selector(self):
i18n.get_store().set_locale_selector(
'resources.i18n.locale_selector')
def test_set_timezone_selector(self):
i18n.get_store().set_timezone_selector(
'resources.i18n.timezone_selector')
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import re
from webapp2_extras import security
import test_base
class TestSecurity(test_base.BaseTestCase):
def test_generate_random_string(self):
self.assertRaises(ValueError, security.generate_random_string, None)
self.assertRaises(ValueError, security.generate_random_string, 0)
self.assertRaises(ValueError, security.generate_random_string, -1)
self.assertRaises(ValueError, security.generate_random_string, 1, 1)
token = security.generate_random_string(16)
self.assertTrue(re.match(r'^\w{16}$', token) is not None)
token = security.generate_random_string(32)
self.assertTrue(re.match(r'^\w{32}$', token) is not None)
token = security.generate_random_string(64)
self.assertTrue(re.match(r'^\w{64}$', token) is not None)
token = security.generate_random_string(128)
self.assertTrue(re.match(r'^\w{128}$', token) is not None)
def test_create_check_password_hash(self):
self.assertRaises(TypeError, security.generate_password_hash, 'foo',
'bar')
password = 'foo'
hashval = security.generate_password_hash(password, 'sha1')
self.assertTrue(security.check_password_hash(password, hashval))
hashval = security.generate_password_hash(password, 'sha1', pepper='bar')
self.assertTrue(security.check_password_hash(password, hashval,
pepper='bar'))
hashval = security.generate_password_hash(password, 'md5')
self.assertTrue(security.check_password_hash(password, hashval))
hashval = security.generate_password_hash(password, 'plain')
self.assertTrue(security.check_password_hash(password, hashval))
hashval = security.generate_password_hash(password, 'plain')
self.assertFalse(security.check_password_hash(password, ''))
hashval1 = security.hash_password(unicode(password), 'sha1', u'bar')
hashval2 = security.hash_password(unicode(password), 'sha1', u'bar')
self.assertTrue(hashval1 is not None)
self.assertEqual(hashval1, hashval2)
hashval1 = security.hash_password(unicode(password), 'md5', None)
hashval2 = security.hash_password(unicode(password), 'md5', None)
self.assertTrue(hashval1 is not None)
self.assertEqual(hashval1, hashval2)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import os
import webapp2
from webapp2_extras import users
import test_base
def set_current_user(email, user_id, is_admin=False):
os.environ['USER_EMAIL'] = email or ''
os.environ['USER_ID'] = user_id or ''
os.environ['USER_IS_ADMIN'] = '1' if is_admin else '0'
class LoginRequiredHandler(webapp2.RequestHandler):
@users.login_required
def get(self):
self.response.write('You are logged in.')
@users.login_required
def post(self):
self.response.write('You are logged in.')
class AdminRequiredHandler(webapp2.RequestHandler):
@users.admin_required
def get(self):
self.response.write('You are admin.')
@users.admin_required
def post(self):
self.response.write('You are admin.')
app = webapp2.WSGIApplication([
('/login_required', LoginRequiredHandler),
('/admin_required', AdminRequiredHandler),
])
class TestUsers(test_base.BaseTestCase):
def test_login_required_allowed(self):
set_current_user('foo@bar.com', 'foo@bar.com')
req = webapp2.Request.blank('/login_required')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'You are logged in.')
def test_login_required_302(self):
req = webapp2.Request.blank('/login_required')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.headers.get('Location'),
'https://www.google.com/accounts/Login?continue=http%3A//localhost/login_required')
def test_login_required_post(self):
req = webapp2.Request.blank('/login_required')
req.method = 'POST'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 400)
def test_admin_required_allowed(self):
set_current_user('foo@bar.com', 'foo@bar.com', is_admin=True)
req = webapp2.Request.blank('/admin_required')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'You are admin.')
def test_admin_required_not_admin(self):
set_current_user('foo@bar.com', 'foo@bar.com')
req = webapp2.Request.blank('/admin_required')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 403)
def test_admin_required_302(self):
req = webapp2.Request.blank('/admin_required')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 302)
self.assertEqual(rsp.headers.get('Location'),
'https://www.google.com/accounts/Login?continue=http%3A//localhost/admin_required')
def test_admin_required_post(self):
req = webapp2.Request.blank('/admin_required')
req.method = 'POST'
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 400)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
import webapp2
import test_base
class NoStringOrUnicodeConversion(object):
pass
class StringConversion(object):
def __str__(self):
return 'foo'.encode('utf-8')
class UnicodeConversion(object):
def __unicode__(self):
return 'bar'.decode('utf-8')
class TestResponse(test_base.BaseTestCase):
def test_write(self):
var_1 = NoStringOrUnicodeConversion()
var_2 = StringConversion()
var_3 = UnicodeConversion()
rsp = webapp2.Response()
rsp.write(var_1)
rsp.write(var_2)
rsp.write(var_3)
self.assertEqual(rsp.body, '%rfoobar' % var_1)
rsp = webapp2.Response()
rsp.write(var_1)
rsp.write(var_3)
rsp.write(var_2)
self.assertEqual(rsp.body, '%rbarfoo' % var_1)
rsp = webapp2.Response()
rsp.write(var_2)
rsp.write(var_1)
rsp.write(var_3)
self.assertEqual(rsp.body, 'foo%rbar' % var_1)
rsp = webapp2.Response()
rsp.write(var_2)
rsp.write(var_3)
rsp.write(var_1)
self.assertEqual(rsp.body, 'foobar%r' % var_1)
rsp = webapp2.Response()
rsp.write(var_3)
rsp.write(var_1)
rsp.write(var_2)
self.assertEqual(rsp.body, 'bar%rfoo' % var_1)
rsp = webapp2.Response()
rsp.write(var_3)
rsp.write(var_2)
rsp.write(var_1)
self.assertEqual(rsp.body, 'barfoo%r' % var_1)
def test_write2(self):
rsp = webapp2.Response()
rsp.charset = None
rsp.write(u'foo')
self.assertEqual(rsp.body, u'foo')
self.assertEqual(rsp.charset, 'utf-8')
def test_status(self):
rsp = webapp2.Response()
self.assertEqual(rsp.status, '200 OK')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.status_message, 'OK')
rsp.status = u'200 OK'
self.assertEqual(rsp.status, '200 OK')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.status_message, 'OK')
rsp.status_message = 'Weee'
self.assertEqual(rsp.status, '200 Weee')
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.status_message, 'Weee')
rsp.status = 404
self.assertEqual(rsp.status, '404 Not Found')
self.assertEqual(rsp.status_int, 404)
self.assertEqual(rsp.status_message, 'Not Found')
rsp.status = '403 Wooo'
self.assertEqual(rsp.status, '403 Wooo')
self.assertEqual(rsp.status_int, 403)
self.assertEqual(rsp.status_message, 'Wooo')
rsp.status_int = 500
self.assertEqual(rsp.status, '500 Internal Server Error')
self.assertEqual(rsp.status_int, 500)
self.assertEqual(rsp.status_message, 'Internal Server Error')
self.assertRaises(TypeError, rsp._set_status, ())
def test_has_error(self):
rsp = webapp2.Response()
self.assertFalse(rsp.has_error())
rsp.status = 400
self.assertTrue(rsp.has_error())
rsp.status = 404
self.assertTrue(rsp.has_error())
rsp.status = 500
self.assertTrue(rsp.has_error())
rsp.status = 200
self.assertFalse(rsp.has_error())
rsp.status = 302
self.assertFalse(rsp.has_error())
def test_wsgi_write(self):
res = []
def write(status, headers, body):
return res.extend([status, headers, body])
def start_response(status, headers):
return lambda body: write(status, headers, body)
rsp = webapp2.Response(body='Page not found!', status=404)
rsp.wsgi_write(start_response)
rsp = webapp2.Response(status=res[0], body=res[2], headers=res[1])
self.assertEqual(rsp.status, '404 Not Found')
self.assertEqual(rsp.body, 'Page not found!')
'''
# webob >= 1.0
self.assertEqual(res, [
'404 Not Found',
[
('Content-Type', 'text/html; charset=utf-8'),
('Cache-Control', 'no-cache'),
('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'),
('Content-Length', '15')
],
'Page not found!'
])
'''
def test_get_all(self):
rsp = webapp2.Response()
rsp.headers.add('Set-Cookie', 'foo=bar;')
rsp.headers.add('Set-Cookie', 'baz=ding;')
self.assertEqual(rsp.headers.get_all('set-cookie'),
['foo=bar;', 'baz=ding;'])
rsp = webapp2.Response()
rsp.headers = {'Set-Cookie': 'foo=bar;'}
self.assertEqual(rsp.headers.get_all('set-cookie'), ['foo=bar;'])
def test_add_header(self):
rsp = webapp2.Response()
rsp.headers.add_header('Content-Disposition', 'attachment',
filename='bud.gif')
self.assertEqual(rsp.headers.get('content-disposition'),
'attachment; filename="bud.gif"')
rsp = webapp2.Response()
rsp.headers.add_header('Content-Disposition', 'attachment',
filename=None)
self.assertEqual(rsp.headers.get('content-disposition'),
'attachment; filename')
rsp = webapp2.Response()
rsp.headers.add_header('Set-Cookie', '', foo='')
self.assertEqual(rsp.headers.get_all('set-cookie'), ['; foo'])
rsp = webapp2.Response()
rsp.headers.add_header('Set-Cookie', '', foo=';')
self.assertEqual(rsp.headers.get_all('set-cookie'), ['; foo=";"'])
# Tests from Python source: wsgiref.headers.Headers
def test_headers_MappingInterface(self):
rsp = webapp2.Response()
test = [('x','y')]
self.assertEqual(len(rsp.headers), 3)
rsp.headers = test[:]
self.assertEqual(len(rsp.headers), 1)
self.assertEqual(rsp.headers.keys(), ['x'])
self.assertEqual(rsp.headers.values(), ['y'])
self.assertEqual(rsp.headers.items(), test)
rsp.headers = test
self.assertFalse(rsp.headers.items() is test) # must be copy!
rsp = webapp2.Response()
h = rsp.headers
# this doesn't raise an error in wsgiref.headers.Headers
# del h['foo']
h['Foo'] = 'bar'
for m in h.has_key, h.__contains__, h.get, h.get_all, h.__getitem__:
self.assertTrue(m('foo'))
self.assertTrue(m('Foo'))
self.assertTrue(m('FOO'))
# this doesn't raise an error in wsgiref.headers.Headers
# self.assertFalse(m('bar'))
self.assertEqual(h['foo'],'bar')
h['foo'] = 'baz'
self.assertEqual(h['FOO'],'baz')
self.assertEqual(h.get_all('foo'),['baz'])
self.assertEqual(h.get("foo","whee"), "baz")
self.assertEqual(h.get("zoo","whee"), "whee")
self.assertEqual(h.setdefault("foo","whee"), "baz")
self.assertEqual(h.setdefault("zoo","whee"), "whee")
self.assertEqual(h["foo"],"baz")
self.assertEqual(h["zoo"],"whee")
def test_headers_RequireList(self):
def set_headers():
rsp = webapp2.Response()
rsp.headers = 'foo'
return rsp.headers
self.assertRaises(TypeError, set_headers)
def test_headers_Extras(self):
rsp = webapp2.Response()
rsp.headers = []
h = rsp.headers
self.assertEqual(str(h),'\r\n')
h.add_header('foo','bar',baz="spam")
self.assertEqual(h['foo'], 'bar; baz="spam"')
self.assertEqual(str(h),'foo: bar; baz="spam"\r\n\r\n')
h.add_header('Foo','bar',cheese=None)
self.assertEqual(h.get_all('foo'),
['bar; baz="spam"', 'bar; cheese'])
self.assertEqual(str(h),
'foo: bar; baz="spam"\r\n'
'Foo: bar; cheese\r\n'
'\r\n'
)
class TestReturnResponse(test_base.BaseTestCase):
def test_function_that_returns_response(self):
def myfunction(request, *args, **kwargs):
return webapp2.Response('Hello, custom response world!')
app = webapp2.WSGIApplication([
('/', myfunction),
])
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, custom response world!')
def test_function_that_returns_string(self):
def myfunction(request, *args, **kwargs):
return 'Hello, custom response world!'
app = webapp2.WSGIApplication([
('/', myfunction),
])
def custom_dispatcher(router, request, response):
response_str = router.default_dispatcher(request, response)
return request.app.response_class(response_str)
app.router.set_dispatcher(custom_dispatcher)
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, custom response world!')
def test_function_that_returns_tuple(self):
def myfunction(request, *args, **kwargs):
return 'Hello, custom response world!', 404
app = webapp2.WSGIApplication([
('/', myfunction),
])
def custom_dispatcher(router, request, response):
response_tuple = router.default_dispatcher(request, response)
return request.app.response_class(*response_tuple)
app.router.set_dispatcher(custom_dispatcher)
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 404)
self.assertEqual(rsp.body, 'Hello, custom response world!')
def test_handle_exception_that_returns_response(self):
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
raise TypeError()
app = webapp2.WSGIApplication([
webapp2.Route('/', HomeHandler, name='home'),
])
app.error_handlers[500] = 'resources.handlers.handle_exception'
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'Hello, custom response world!')
def test_return_is_not_wsgi_app(self):
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
return ''
app = webapp2.WSGIApplication([
webapp2.Route('/', HomeHandler, name='home'),
], debug=False)
req = webapp2.Request.blank('/')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 500)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
from webapp2_extras import securecookie
import test_base
class TestSecureCookie(test_base.BaseTestCase):
def test_secure_cookie_serializer(self):
serializer = securecookie.SecureCookieSerializer('secret-key')
serializer._get_timestamp = lambda: 1
value = ['a', 'b', 'c']
result = 'WyJhIiwiYiIsImMiXQ==|1|38837d6af8ac1ded9292b83924fc8521ce76f47e'
rv = serializer.serialize('foo', value)
self.assertEqual(rv, result)
rv = serializer.deserialize('foo', result)
self.assertEqual(rv, value)
# no value
rv = serializer.deserialize('foo', None)
self.assertEqual(rv, None)
# not 3 parts
rv = serializer.deserialize('foo', 'a|b')
self.assertEqual(rv, None)
# bad signature
rv = serializer.deserialize('foo', result + 'foo')
self.assertEqual(rv, None)
# too old
rv = serializer.deserialize('foo', result, max_age=-86400)
self.assertEqual(rv, None)
# not correctly encoded
serializer2 = securecookie.SecureCookieSerializer('foo')
serializer2._encode = lambda x: 'foo'
result2 = serializer2.serialize('foo', value)
rv2 = serializer2.deserialize('foo', result2)
self.assertEqual(rv2, None)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
from google.appengine.ext import webapp
import webapp2
import test_base
# Old WSGIApplication, new RequestHandler.
class NewStyleHandler(webapp2.RequestHandler):
def get(self, text):
self.response.out.write(text)
app = webapp.WSGIApplication([
(r'/test/(.*)', NewStyleHandler),
])
# New WSGIApplication, old RequestHandler.
class OldStyleHandler(webapp.RequestHandler):
def get(self, text):
self.response.out.write(text)
class OldStyleHandler2(webapp.RequestHandler):
def get(self, text=None):
self.response.out.write(text)
class OldStyleHandlerWithError(webapp.RequestHandler):
def get(self, text):
raise ValueError()
def handle_exception(self, e, debug):
self.response.set_status(500)
self.response.out.write('ValueError!')
app2 = webapp2.WSGIApplication([
(r'/test/error', OldStyleHandlerWithError),
(r'/test/(.*)', OldStyleHandler),
webapp2.Route(r'/test2/<text>', OldStyleHandler2),
])
class TestWebapp1(test_base.BaseTestCase):
def test_old_app_new_handler(self):
req = webapp2.Request.blank('/test/foo')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'foo')
req = webapp2.Request.blank('/test/bar')
rsp = req.get_response(app)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'bar')
self.assertTrue(issubclass(OldStyleHandler, webapp.RequestHandler))
def test_new_app_old_handler(self):
req = webapp2.Request.blank('/test/foo')
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'foo')
req = webapp2.Request.blank('/test/bar')
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'bar')
def test_new_app_old_handler_405(self):
req = webapp2.Request.blank('/test/foo')
req.method = 'POST'
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 405)
self.assertEqual(rsp.headers.get('Allow'), None)
def test_new_app_old_handler_501(self):
app2.allowed_methods = list(app2.allowed_methods) + ['NEW_METHOD']
req = webapp2.Request.blank('/test/foo')
req.method = 'NEW_METHOD'
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 501)
def test_new_app_old_handler_501_2(self):
req = webapp2.Request.blank('/test/foo')
req.method = 'WHATMETHODISTHIS'
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 501)
def test_new_app_old_handler_with_error(self):
req = webapp2.Request.blank('/test/error')
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 500)
self.assertEqual(rsp.body, 'ValueError!')
def test_new_app_old_kwargs(self):
req = webapp2.Request.blank('/test2/foo')
rsp = req.get_response(app2)
self.assertEqual(rsp.status_int, 200)
self.assertEqual(rsp.body, 'foo')
def test_unicode_cookie(self):
# see http://stackoverflow.com/questions/6839922/unicodedecodeerror-is-raised-when-getting-a-cookie-in-google-app-engine
import urllib
# This is the value we want to set.
initial_value = u'äëïöü'
# WebOb version that comes with SDK doesn't quote cookie values.
# So we have to do it.
quoted_value = urllib.quote(initial_value.encode('utf-8'))
rsp = webapp.Response()
rsp.headers['Set-Cookie'] = 'app=%s; Path=/' % quoted_value
cookie = rsp.headers.get('Set-Cookie')
req = webapp.Request.blank('/', headers=[('Cookie', cookie)])
# The stored value is the same quoted value from before.
stored_value = req.cookies.get('app')
self.assertEqual(stored_value, quoted_value)
# And we can get the initial value unquoting and decoding.
final_value = urllib.unquote(stored_value.encode('utf-8')).decode('utf-8')
self.assertEqual(final_value, initial_value)
if __name__ == '__main__':
test_base.main()
| Python |
# -*- coding: utf-8 -*-
"""
webapp2
=======
Taking Google App Engine's webapp to the next level!
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import with_statement
import cgi
import inspect
import logging
import os
import re
import sys
import threading
import traceback
import urllib
import urlparse
from wsgiref import handlers
import webob
from webob import exc
_webapp = _webapp_util = _local = None
try: # pragma: no cover
# WebOb < 1.0 (App Engine Python 2.5).
from webob.statusreasons import status_reasons
from webob.headerdict import HeaderDict as BaseResponseHeaders
except ImportError: # pragma: no cover
# WebOb >= 1.0.
from webob.util import status_reasons
from webob.headers import ResponseHeaders as BaseResponseHeaders
# google.appengine.ext.webapp imports webapp2 in the
# App Engine Python 2.7 runtime.
if os.environ.get('APPENGINE_RUNTIME') != 'python27': # pragma: no cover
try:
from google.appengine.ext import webapp as _webapp
except ImportError: # pragma: no cover
# Running webapp2 outside of GAE.
pass
try: # pragma: no cover
# Thread-local variables container.
from webapp2_extras import local
_local = local.Local()
except ImportError: # pragma: no cover
logging.warning("webapp2_extras.local is not available "
"so webapp2 won't be thread-safe!")
__version_info__ = (2, 5, 2)
__version__ = '.'.join(str(n) for n in __version_info__)
#: Base HTTP exception, set here as public interface.
HTTPException = exc.HTTPException
#: Regex for route definitions.
_route_re = re.compile(r"""
\< # The exact character "<"
([a-zA-Z_]\w*)? # The optional variable name
(?:\:([^\>]*))? # The optional :regex part
\> # The exact character ">"
""", re.VERBOSE)
#: Regex extract charset from environ.
_charset_re = re.compile(r';\s*charset=([^;]*)', re.I)
#: To show exceptions in debug mode.
_debug_template = """<html>
<head>
<title>Internal Server Error</title>
<style>
body {
padding: 20px;
font-family: arial, sans-serif;
font-size: 14px;
}
pre {
background: #F2F2F2;
padding: 10px;
}
</style>
</head>
<body>
<h1>Internal Server Error</h1>
<p>The server has either erred or is incapable of performing
the requested operation.</p>
<pre>%s</pre>
</body>
</html>"""
# Set same default messages from webapp plus missing ones.
_webapp_status_reasons = {
203: 'Non-Authoritative Information',
302: 'Moved Temporarily',
306: 'Unused',
408: 'Request Time-out',
414: 'Request-URI Too Large',
504: 'Gateway Time-out',
505: 'HTTP Version not supported',
}
status_reasons.update(_webapp_status_reasons)
for code, message in _webapp_status_reasons.iteritems():
cls = exc.status_map.get(code)
if cls:
cls.title = message
class Request(webob.Request):
"""Abstraction for an HTTP request.
Most extra methods and attributes are ported from webapp. Check the
`WebOb`_ documentation for the ones not listed here.
"""
#: A reference to the active :class:`WSGIApplication` instance.
app = None
#: A reference to the active :class:`Response` instance.
response = None
#: A reference to the matched :class:`Route`.
route = None
#: The matched route positional arguments.
route_args = None
#: The matched route keyword arguments.
route_kwargs = None
#: A dictionary to register objects used during the request lifetime.
registry = None
# Attributes from webapp.
request_body_tempfile_limit = 0
uri = property(lambda self: self.url)
query = property(lambda self: self.query_string)
def __init__(self, environ, *args, **kwargs):
"""Constructs a Request object from a WSGI environment.
:param environ:
A WSGI-compliant environment dictionary.
"""
if kwargs.get('charset') is None and not hasattr(webob, '__version__'):
# webob 0.9 didn't have a __version__ attribute and also defaulted
# to None rather than UTF-8 if no charset was provided. Providing a
# default charset is required for backwards compatibility.
match = _charset_re.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
kwargs['charset'] = charset
super(Request, self).__init__(environ, *args, **kwargs)
self.registry = {}
def get(self, argument_name, default_value='', allow_multiple=False):
"""Returns the query or POST argument with the given name.
We parse the query string and POST payload lazily, so this will be a
slower operation on the first call.
:param argument_name:
The name of the query or POST argument.
:param default_value:
The value to return if the given argument is not present.
:param allow_multiple:
Return a list of values with the given name (deprecated).
:returns:
If allow_multiple is False (which it is by default), we return
the first value with the given name given in the request. If it
is True, we always return a list.
"""
param_value = self.get_all(argument_name)
if allow_multiple:
logging.warning('allow_multiple is a deprecated param. '
'Please use the Request.get_all() method instead.')
if len(param_value) > 0:
if allow_multiple:
return param_value
return param_value[0]
else:
if allow_multiple and not default_value:
return []
return default_value
def get_all(self, argument_name, default_value=None):
"""Returns a list of query or POST arguments with the given name.
We parse the query string and POST payload lazily, so this will be a
slower operation on the first call.
:param argument_name:
The name of the query or POST argument.
:param default_value:
The value to return if the given argument is not present,
None may not be used as a default, if it is then an empty
list will be returned instead.
:returns:
A (possibly empty) list of values.
"""
if self.charset:
argument_name = argument_name.encode(self.charset)
if default_value is None:
default_value = []
param_value = self.params.getall(argument_name)
if param_value is None or len(param_value) == 0:
return default_value
for i in xrange(len(param_value)):
if isinstance(param_value[i], cgi.FieldStorage):
param_value[i] = param_value[i].value
return param_value
def arguments(self):
"""Returns a list of the arguments provided in the query and/or POST.
The return value is a list of strings.
"""
return list(set(self.params.keys()))
def get_range(self, name, min_value=None, max_value=None, default=0):
"""Parses the given int argument, limiting it to the given range.
:param name:
The name of the argument.
:param min_value:
The minimum int value of the argument (if any).
:param max_value:
The maximum int value of the argument (if any).
:param default:
The default value of the argument if it is not given.
:returns:
An int within the given range for the argument.
"""
value = self.get(name, default)
if value is None:
return value
try:
value = int(value)
except ValueError:
value = default
if value is not None:
if max_value is not None:
value = min(value, max_value)
if min_value is not None:
value = max(value, min_value)
return value
@classmethod
def blank(cls, path, environ=None, base_url=None,
headers=None, **kwargs): # pragma: no cover
"""Adds parameters compatible with WebOb >= 1.0: POST and **kwargs."""
try:
return super(Request, cls).blank(path, environ=environ,
base_url=base_url,
headers=headers, **kwargs)
except TypeError:
if not kwargs:
raise
data = kwargs.pop('POST', None)
if data is not None:
from cStringIO import StringIO
environ = environ or {}
environ['REQUEST_METHOD'] = 'POST'
if hasattr(data, 'items'):
data = data.items()
if not isinstance(data, str):
data = urllib.urlencode(data)
environ['wsgi.input'] = StringIO(data)
environ['webob.is_body_seekable'] = True
environ['CONTENT_LENGTH'] = str(len(data))
environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
base = super(Request, cls).blank(path, environ=environ,
base_url=base_url, headers=headers)
if kwargs:
obj = cls(base.environ, **kwargs)
obj.headers.update(base.headers)
return obj
else:
return base
class ResponseHeaders(BaseResponseHeaders):
"""Implements methods from ``wsgiref.headers.Headers``, used by webapp."""
get_all = BaseResponseHeaders.getall
def add_header(self, _name, _value, **_params):
"""Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example::
h.add_header('content-disposition', 'attachment',
filename='bud.gif')
Note that unlike the corresponding 'email.message' method, this does
*not* handle '(charset, language, value)' tuples: all values must be
strings or None.
"""
parts = []
if _value is not None:
parts.append(_value)
for k, v in _params.items():
k = k.replace('_', '-')
if v is not None and len(v) > 0:
v = v.replace('\\', '\\\\').replace('"', r'\"')
parts.append('%s="%s"' % (k, v))
else:
parts.append(k)
self.add(_name, '; '.join(parts))
def __str__(self):
"""Returns the formatted headers ready for HTTP transmission."""
return '\r\n'.join(['%s: %s' % v for v in self.items()] + ['', ''])
class Response(webob.Response):
"""Abstraction for an HTTP response.
Most extra methods and attributes are ported from webapp. Check the
`WebOb`_ documentation for the ones not listed here.
Differences from webapp.Response:
- ``out`` is not a ``StringIO.StringIO`` instance. Instead it is the
response itself, as it has the method ``write()``.
- As in WebOb, ``status`` is the code plus message, e.g., '200 OK', while
in webapp it is the integer code. The status code as an integer is
available in ``status_int``, and the status message is available in
``status_message``.
- ``response.headers`` raises an exception when a key that doesn't exist
is accessed or deleted, differently from ``wsgiref.headers.Headers``.
"""
#: Default charset as in webapp.
default_charset = 'utf-8'
def __init__(self, *args, **kwargs):
"""Constructs a response with the default settings."""
super(Response, self).__init__(*args, **kwargs)
self.headers['Cache-Control'] = 'no-cache'
@property
def out(self):
"""A reference to the Response instance itself, for compatibility with
webapp only: webapp uses `Response.out.write()`, so we point `out` to
`self` and it will use `Response.write()`.
"""
return self
def write(self, text):
"""Appends a text to the response body."""
# webapp uses StringIO as Response.out, so we need to convert anything
# that is not str or unicode to string to keep same behavior.
if not isinstance(text, basestring):
text = unicode(text)
if isinstance(text, unicode) and not self.charset:
self.charset = self.default_charset
super(Response, self).write(text)
def _set_status(self, value):
"""The status string, including code and message."""
message = None
# Accept long because urlfetch in App Engine returns codes as longs.
if isinstance(value, (int, long)):
code = int(value)
else:
if isinstance(value, unicode):
# Status messages have to be ASCII safe, so this is OK.
value = str(value)
if not isinstance(value, str):
raise TypeError(
'You must set status to a string or integer (not %s)' %
type(value))
parts = value.split(' ', 1)
code = int(parts[0])
if len(parts) == 2:
message = parts[1]
message = message or Response.http_status_message(code)
self._status = '%d %s' % (code, message)
def _get_status(self):
return self._status
status = property(_get_status, _set_status, doc=_set_status.__doc__)
def set_status(self, code, message=None):
"""Sets the HTTP status code of this response.
:param code:
The HTTP status string to use
:param message:
A status string. If none is given, uses the default from the
HTTP/1.1 specification.
"""
if message:
self.status = '%d %s' % (code, message)
else:
self.status = code
def _get_status_message(self):
"""The response status message, as a string."""
return self.status.split(' ', 1)[1]
def _set_status_message(self, message):
self.status = '%d %s' % (self.status_int, message)
status_message = property(_get_status_message, _set_status_message,
doc=_get_status_message.__doc__)
def _get_headers(self):
"""The headers as a dictionary-like object."""
if self._headers is None:
self._headers = ResponseHeaders.view_list(self.headerlist)
return self._headers
def _set_headers(self, value):
if hasattr(value, 'items'):
value = value.items()
elif not isinstance(value, list):
raise TypeError('Response headers must be a list or dictionary.')
self.headerlist = value
self._headers = None
headers = property(_get_headers, _set_headers, doc=_get_headers.__doc__)
def has_error(self):
"""Indicates whether the response was an error response."""
return self.status_int >= 400
def clear(self):
"""Clears all data written to the output stream so that it is empty."""
self.body = ''
def wsgi_write(self, start_response):
"""Writes this response using using the given WSGI function.
This is only here for compatibility with ``webapp.WSGIApplication``.
:param start_response:
The WSGI-compatible start_response function.
"""
if (self.headers.get('Cache-Control') == 'no-cache' and
not self.headers.get('Expires')):
self.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'
self.headers['Content-Length'] = str(len(self.body))
write = start_response(self.status, self.headerlist)
write(self.body)
@staticmethod
def http_status_message(code):
"""Returns the default HTTP status message for the given code.
:param code:
The HTTP code for which we want a message.
"""
message = status_reasons.get(code)
if not message:
raise KeyError('Invalid HTTP status code: %d' % code)
return message
class RequestHandler(object):
"""Base HTTP request handler.
Implements most of ``webapp.RequestHandler`` interface.
"""
#: A :class:`Request` instance.
request = None
#: A :class:`Response` instance.
response = None
#: A :class:`WSGIApplication` instance.
app = None
def __init__(self, request=None, response=None):
"""Initializes this request handler with the given WSGI application,
Request and Response.
When instantiated by ``webapp.WSGIApplication``, request and response
are not set on instantiation. Instead, initialize() is called right
after the handler is created to set them.
Also in webapp dispatching is done by the WSGI app, while webapp2
does it here to allow more flexibility in extended classes: handlers
can wrap :meth:`dispatch` to check for conditions before executing the
requested method and/or post-process the response.
.. note::
Parameters are optional only to support webapp's constructor which
doesn't take any arguments. Consider them as required.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.initialize(request, response)
def initialize(self, request, response):
"""Initializes this request handler with the given WSGI application,
Request and Response.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.request = request
self.response = response
self.app = WSGIApplication.active_instance
def dispatch(self):
"""Dispatches the request.
This will first check if there's a handler_method defined in the
matched route, and if not it'll use the method correspondent to the
request method (``get()``, ``post()`` etc).
"""
request = self.request
method_name = request.route.handler_method
if not method_name:
method_name = _normalize_handler_method(request.method)
method = getattr(self, method_name, None)
if method is None:
# 405 Method Not Allowed.
# The response MUST include an Allow header containing a
# list of valid methods for the requested resource.
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6
valid = ', '.join(_get_handler_methods(self))
self.abort(405, headers=[('Allow', valid)])
# The handler only receives *args if no named variables are set.
args, kwargs = request.route_args, request.route_kwargs
if kwargs:
args = ()
try:
return method(*args, **kwargs)
except Exception, e:
return self.handle_exception(e, self.app.debug)
def error(self, code):
"""Clears the response and sets the given HTTP status code.
This doesn't stop code execution; for this, use :meth:`abort`.
:param code:
HTTP status error code (e.g., 501).
"""
self.response.status = code
self.response.clear()
def abort(self, code, *args, **kwargs):
"""Raises an :class:`HTTPException`.
This stops code execution, leaving the HTTP exception to be handled
by an exception handler.
:param code:
HTTP status code (e.g., 404).
:param args:
Positional arguments to be passed to the exception class.
:param kwargs:
Keyword arguments to be passed to the exception class.
"""
abort(code, *args, **kwargs)
def redirect(self, uri, permanent=False, abort=False, code=None,
body=None):
"""Issues an HTTP redirect to the given relative URI.
The arguments are described in :func:`redirect`.
"""
return redirect(uri, permanent=permanent, abort=abort, code=code,
body=body, request=self.request,
response=self.response)
def redirect_to(self, _name, _permanent=False, _abort=False, _code=None,
_body=None, *args, **kwargs):
"""Convenience method mixing :meth:`redirect` and :meth:`uri_for`.
The arguments are described in :func:`redirect` and :func:`uri_for`.
"""
uri = self.uri_for(_name, *args, **kwargs)
return self.redirect(uri, permanent=_permanent, abort=_abort,
code=_code, body=_body)
def uri_for(self, _name, *args, **kwargs):
"""Returns a URI for a named :class:`Route`.
.. seealso:: :meth:`Router.build`.
"""
return self.app.router.build(self.request, _name, args, kwargs)
# Alias.
url_for = uri_for
def handle_exception(self, exception, debug):
"""Called if this handler throws an exception during execution.
The default behavior is to re-raise the exception to be handled by
:meth:`WSGIApplication.handle_exception`.
:param exception:
The exception that was thrown.
:param debug_mode:
True if the web application is running in debug mode.
"""
raise
class RedirectHandler(RequestHandler):
"""Redirects to the given URI for all GET requests.
This is intended to be used when defining URI routes. You must provide at
least the keyword argument *url* in the route default values. Example::
def get_redirect_url(handler, *args, **kwargs):
return handler.uri_for('new-route-name')
app = WSGIApplication([
Route('/old-url', RedirectHandler, defaults={'_uri': '/new-url'}),
Route('/other-old-url', RedirectHandler, defaults={
'_uri': get_redirect_url}),
])
Based on idea from `Tornado`_.
"""
def get(self, *args, **kwargs):
"""Performs a redirect.
Two keyword arguments can be passed through the URI route:
- **_uri**: A URI string or a callable that returns a URI. The callable
is called passing ``(handler, *args, **kwargs)`` as arguments.
- **_code**: The redirect status code. Default is 301 (permanent
redirect).
"""
uri = kwargs.pop('_uri', '/')
permanent = kwargs.pop('_permanent', True)
code = kwargs.pop('_code', None)
func = getattr(uri, '__call__', None)
if func:
uri = func(self, *args, **kwargs)
self.redirect(uri, permanent=permanent, code=code)
class cached_property(object):
"""A decorator that converts a function into a lazy property.
The function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
the value::
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a `__dict__` in order for this property to
work.
.. note:: Implementation detail: this property is implemented as non-data
descriptor. non-data descriptors are only invoked if there is
no entry with the same name in the instance's __dict__.
this allows us to completely get rid of the access function call
overhead. If one choses to invoke __get__ by hand the property
will still work as expected because the lookup logic is replicated
in __get__ for manual invocation.
This class was ported from `Werkzeug`_ and `Flask`_.
"""
_default_value = object()
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
self.lock = threading.RLock()
def __get__(self, obj, type=None):
if obj is None:
return self
with self.lock:
value = obj.__dict__.get(self.__name__, self._default_value)
if value is self._default_value:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
class BaseRoute(object):
"""Interface for URI routes."""
#: The regex template.
template = None
#: Route name, used to build URIs.
name = None
#: True if this route is only used for URI generation and never matches.
build_only = False
#: The handler or string in dotted notation to be lazily imported.
handler = None
#: The custom handler method, if handler is a class.
handler_method = None
#: The handler, imported and ready for dispatching.
handler_adapter = None
def __init__(self, template, handler=None, name=None, build_only=False):
"""Initializes this route.
:param template:
A regex to be matched.
:param handler:
A callable or string in dotted notation to be lazily imported,
e.g., ``'my.module.MyHandler'`` or ``'my.module.my_function'``.
:param name:
The name of this route, used to build URIs based on it.
:param build_only:
If True, this route never matches and is used only to build URIs.
"""
if build_only and name is None:
raise ValueError(
"Route %r is build_only but doesn't have a name." % self)
self.template = template
self.handler = handler
self.name = name
self.build_only = build_only
def match(self, request):
"""Matches all routes against a request object.
The first one that matches is returned.
:param request:
A :class:`Request` instance.
:returns:
A tuple ``(route, args, kwargs)`` if a route matched, or None.
"""
raise NotImplementedError()
def build(self, request, args, kwargs):
"""Returns a URI for this route.
:param request:
The current :class:`Request` object.
:param args:
Tuple of positional arguments to build the URI.
:param kwargs:
Dictionary of keyword arguments to build the URI.
:returns:
An absolute or relative URI.
"""
raise NotImplementedError()
def get_routes(self):
"""Generator to get all routes from a route.
:yields:
This route or all nested routes that it contains.
"""
yield self
def get_match_routes(self):
"""Generator to get all routes that can be matched from a route.
Match routes must implement :meth:`match`.
:yields:
This route or all nested routes that can be matched.
"""
if not self.build_only:
yield self
def get_build_routes(self):
"""Generator to get all routes that can be built from a route.
Build routes must implement :meth:`build`.
:yields:
A tuple ``(name, route)`` for all nested routes that can be built.
"""
if self.name is not None:
yield self.name, self
class SimpleRoute(BaseRoute):
"""A route that is compatible with webapp's routing mechanism.
URI building is not implemented as webapp has rudimentar support for it,
and this is the most unknown webapp feature anyway.
"""
@cached_property
def regex(self):
"""Lazy regex compiler."""
if not self.template.startswith('^'):
self.template = '^' + self.template
if not self.template.endswith('$'):
self.template += '$'
return re.compile(self.template)
def match(self, request):
"""Matches this route against the current request.
.. seealso:: :meth:`BaseRoute.match`.
"""
match = self.regex.match(urllib.unquote(request.path))
if match:
return self, match.groups(), {}
def __repr__(self):
return '<SimpleRoute(%r, %r)>' % (self.template, self.handler)
class Route(BaseRoute):
"""A route definition that maps a URI path to a handler.
The initial concept was based on `Another Do-It-Yourself Framework`_, by
Ian Bicking.
"""
#: Default parameters values.
defaults = None
#: Sequence of allowed HTTP methods. If not set, all methods are allowed.
methods = None
#: Sequence of allowed URI schemes. If not set, all schemes are allowed.
schemes = None
# Lazy properties extracted from the route template.
regex = None
reverse_template = None
variables = None
args_count = 0
kwargs_count = 0
def __init__(self, template, handler=None, name=None, defaults=None,
build_only=False, handler_method=None, methods=None,
schemes=None):
"""Initializes this route.
:param template:
A route template to match against the request path. A template
can have variables enclosed by ``<>`` that define a name, a
regular expression or both. Examples:
================= ==================================
Format Example
================= ==================================
``<name>`` ``'/blog/<year>/<month>'``
``<:regex>`` ``'/blog/<:\d{4}>/<:\d{2}>'``
``<name:regex>`` ``'/blog/<year:\d{4}>/<month:\d{2}>'``
================= ==================================
The same template can mix parts with name, regular expression or
both.
If the name is set, the value of the matched regular expression
is passed as keyword argument to the handler. Otherwise it is
passed as positional argument.
If only the name is set, it will match anything except a slash.
So these routes are equivalent::
Route('/<user_id>/settings', handler=SettingsHandler,
name='user-settings')
Route('/<user_id:[^/]+>/settings', handler=SettingsHandler,
name='user-settings')
.. note::
The handler only receives ``*args`` if no named variables are
set. Otherwise, the handler only receives ``**kwargs``. This
allows you to set regular expressions that are not captured:
just mix named and unnamed variables and the handler will
only receive the named ones.
:param handler:
A callable or string in dotted notation to be lazily imported,
e.g., ``'my.module.MyHandler'`` or ``'my.module.my_function'``.
It is possible to define a method if the callable is a class,
separating it by a colon: ``'my.module.MyHandler:my_method'``.
This is a shortcut and has the same effect as defining the
`handler_method` parameter.
:param name:
The name of this route, used to build URIs based on it.
:param defaults:
Default or extra keywords to be returned by this route. Values
also present in the route variables are used to build the URI
when they are missing.
:param build_only:
If True, this route never matches and is used only to build URIs.
:param handler_method:
The name of a custom handler method to be called, in case `handler`
is a class. If not defined, the default behavior is to call the
handler method correspondent to the HTTP request method in lower
case (e.g., `get()`, `post()` etc).
:param methods:
A sequence of HTTP methods. If set, the route will only match if
the request method is allowed.
:param schemes:
A sequence of URI schemes, e.g., ``['http']`` or ``['https']``.
If set, the route will only match requests with these schemes.
"""
super(Route, self).__init__(template, handler=handler, name=name,
build_only=build_only)
self.defaults = defaults or {}
self.methods = methods
self.schemes = schemes
if isinstance(handler, basestring) and ':' in handler:
if handler_method:
raise ValueError(
"If handler_method is defined in a Route, handler "
"can't have a colon (got %r)." % handler)
else:
self.handler, self.handler_method = handler.rsplit(':', 1)
else:
self.handler_method = handler_method
@cached_property
def regex(self):
"""Lazy route template parser."""
regex, self.reverse_template, self.args_count, self.kwargs_count, \
self.variables = _parse_route_template(self.template,
default_sufix='[^/]+')
return regex
def match(self, request):
"""Matches this route against the current request.
:raises:
``exc.HTTPMethodNotAllowed`` if the route defines :attr:`methods`
and the request method isn't allowed.
.. seealso:: :meth:`BaseRoute.match`.
"""
match = self.regex.match(urllib.unquote(request.path))
if not match or self.schemes and request.scheme not in self.schemes:
return None
if self.methods and request.method not in self.methods:
# This will be caught by the router, so routes with different
# methods can be tried.
raise exc.HTTPMethodNotAllowed()
args, kwargs = _get_route_variables(match, self.defaults.copy())
return self, args, kwargs
def build(self, request, args, kwargs):
"""Returns a URI for this route.
.. seealso:: :meth:`Router.build`.
"""
scheme = kwargs.pop('_scheme', None)
netloc = kwargs.pop('_netloc', None)
anchor = kwargs.pop('_fragment', None)
full = kwargs.pop('_full', False) and not scheme and not netloc
if full or scheme or netloc:
netloc = netloc or request.host
scheme = scheme or request.scheme
path, query = self._build(args, kwargs)
return _urlunsplit(scheme, netloc, path, query, anchor)
def _build(self, args, kwargs):
"""Returns the URI path for this route.
:returns:
A tuple ``(path, kwargs)`` with the built URI path and extra
keywords to be used as URI query arguments.
"""
# Access self.regex just to set the lazy properties.
regex = self.regex
variables = self.variables
if self.args_count:
for index, value in enumerate(args):
key = '__%d__' % index
if key in variables:
kwargs[key] = value
values = {}
for name, regex in variables.iteritems():
value = kwargs.pop(name, self.defaults.get(name))
if value is None:
raise KeyError('Missing argument "%s" to build URI.' % \
name.strip('_'))
if not isinstance(value, basestring):
value = str(value)
if not regex.match(value):
raise ValueError('URI buiding error: Value "%s" is not '
'supported for argument "%s".' % (value, name.strip('_')))
values[name] = value
return (self.reverse_template % values, kwargs)
def __repr__(self):
return '<Route(%r, %r, name=%r, defaults=%r, build_only=%r)>' % \
(self.template, self.handler, self.name, self.defaults,
self.build_only)
class BaseHandlerAdapter(object):
"""A basic adapter to dispatch a handler.
This is used when the handler is a simple function: it just calls the
handler and returns the resulted response.
"""
#: The handler to be dispatched.
handler = None
def __init__(self, handler):
self.handler = handler
def __call__(self, request, response):
# The handler only receives *args if no named variables are set.
args, kwargs = request.route_args, request.route_kwargs
if kwargs:
args = ()
return self.handler(request, *args, **kwargs)
class WebappHandlerAdapter(BaseHandlerAdapter):
"""An adapter to dispatch a ``webapp.RequestHandler``.
Like in webapp, the handler is constructed, then ``initialize()`` is
called, then the method corresponding to the HTTP request method is called.
"""
def __call__(self, request, response):
handler = self.handler()
handler.initialize(request, response)
method_name = _normalize_handler_method(request.method)
method = getattr(handler, method_name, None)
if not method:
abort(501)
# The handler only receives *args if no named variables are set.
args, kwargs = request.route_args, request.route_kwargs
if kwargs:
args = ()
try:
method(*args, **kwargs)
except Exception, e:
handler.handle_exception(e, request.app.debug)
class Webapp2HandlerAdapter(BaseHandlerAdapter):
"""An adapter to dispatch a ``webapp2.RequestHandler``.
The handler is constructed then ``dispatch()`` is called.
"""
def __call__(self, request, response):
handler = self.handler(request, response)
return handler.dispatch()
class Router(object):
"""A URI router used to match, dispatch and build URIs."""
#: Class used when the route is set as a tuple.
route_class = SimpleRoute
#: All routes that can be matched.
match_routes = None
#: All routes that can be built.
build_routes = None
#: Handler classes imported lazily.
handlers = None
def __init__(self, routes=None):
"""Initializes the router.
:param routes:
A sequence of :class:`Route` instances or, for simple routes,
tuples ``(regex, handler)``.
"""
self.match_routes = []
self.build_routes = {}
self.handlers = {}
if routes:
for route in routes:
self.add(route)
def add(self, route):
"""Adds a route to this router.
:param route:
A :class:`Route` instance or, for simple routes, a tuple
``(regex, handler)``.
"""
if isinstance(route, tuple):
# Exceptional case: simple routes defined as a tuple.
route = self.route_class(*route)
for r in route.get_match_routes():
self.match_routes.append(r)
for name, r in route.get_build_routes():
self.build_routes[name] = r
def set_matcher(self, func):
"""Sets the function called to match URIs.
:param func:
A function that receives ``(router, request)`` and returns
a tuple ``(route, args, kwargs)`` if any route matches, or
raise ``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
"""
# Functions are descriptors, so bind it to this instance with __get__.
self.match = func.__get__(self, self.__class__)
def set_builder(self, func):
"""Sets the function called to build URIs.
:param func:
A function that receives ``(router, request, name, args, kwargs)``
and returns a URI.
"""
self.build = func.__get__(self, self.__class__)
def set_dispatcher(self, func):
"""Sets the function called to dispatch the handler.
:param func:
A function that receives ``(router, request, response)``
and returns the value returned by the dispatched handler.
"""
self.dispatch = func.__get__(self, self.__class__)
def set_adapter(self, func):
"""Sets the function that adapts loaded handlers for dispatching.
:param func:
A function that receives ``(router, handler)`` and returns a
handler callable.
"""
self.adapt = func.__get__(self, self.__class__)
def default_matcher(self, request):
"""Matches all routes against a request object.
The first one that matches is returned.
:param request:
A :class:`Request` instance.
:returns:
A tuple ``(route, args, kwargs)`` if a route matched, or None.
:raises:
``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
"""
method_not_allowed = False
for route in self.match_routes:
try:
match = route.match(request)
if match:
return match
except exc.HTTPMethodNotAllowed:
method_not_allowed = True
if method_not_allowed:
raise exc.HTTPMethodNotAllowed()
raise exc.HTTPNotFound()
def default_builder(self, request, name, args, kwargs):
"""Returns a URI for a named :class:`Route`.
:param request:
The current :class:`Request` object.
:param name:
The route name.
:param args:
Tuple of positional arguments to build the URI. All positional
variables defined in the route must be passed and must conform
to the format set in the route. Extra arguments are ignored.
:param kwargs:
Dictionary of keyword arguments to build the URI. All variables
not set in the route default values must be passed and must
conform to the format set in the route. Extra keywords are
appended as a query string.
A few keywords have special meaning:
- **_full**: If True, builds an absolute URI.
- **_scheme**: URI scheme, e.g., `http` or `https`. If defined,
an absolute URI is always returned.
- **_netloc**: Network location, e.g., `www.google.com`. If
defined, an absolute URI is always returned.
- **_fragment**: If set, appends a fragment (or "anchor") to the
generated URI.
:returns:
An absolute or relative URI.
"""
route = self.build_routes.get(name)
if route is None:
raise KeyError('Route named %r is not defined.' % name)
return route.build(request, args, kwargs)
def default_dispatcher(self, request, response):
"""Dispatches a handler.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
:raises:
``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
:returns:
The returned value from the handler.
"""
route, args, kwargs = rv = self.match(request)
request.route, request.route_args, request.route_kwargs = rv
if route.handler_adapter is None:
handler = route.handler
if isinstance(handler, basestring):
if handler not in self.handlers:
self.handlers[handler] = handler = import_string(handler)
else:
handler = self.handlers[handler]
route.handler_adapter = self.adapt(handler)
return route.handler_adapter(request, response)
def default_adapter(self, handler):
"""Adapts a handler for dispatching.
Because handlers use or implement different dispatching mechanisms,
they can be wrapped to use a unified API for dispatching.
This way webapp2 can support, for example, a :class:`RequestHandler`
class and function views or, for compatibility purposes, a
``webapp.RequestHandler`` class. The adapters follow the same router
dispatching API but dispatch each handler type differently.
:param handler:
A handler callable.
:returns:
A wrapped handler callable.
"""
if inspect.isclass(handler):
if _webapp and issubclass(handler, _webapp.RequestHandler):
# Compatible with webapp.RequestHandler.
adapter = WebappHandlerAdapter
else:
# Default, compatible with webapp2.RequestHandler.
adapter = Webapp2HandlerAdapter
else:
# A "view" function.
adapter = BaseHandlerAdapter
return adapter(handler)
def __repr__(self):
routes = self.match_routes + [v for k, v in \
self.build_routes.iteritems() if v not in self.match_routes]
return '<Router(%r)>' % routes
# Default matcher, builder, dispatcher and adapter.
match = default_matcher
build = default_builder
dispatch = default_dispatcher
adapt = default_adapter
class Config(dict):
"""A simple configuration dictionary for the :class:`WSGIApplication`."""
#: Loaded configurations.
loaded = None
def __init__(self, defaults=None):
dict.__init__(self, defaults or ())
self.loaded = []
def load_config(self, key, default_values=None, user_values=None,
required_keys=None):
"""Returns a configuration for a given key.
This can be used by objects that define a default configuration. It
will update the app configuration with the default values the first
time it is requested, and mark the key as loaded.
:param key:
A configuration key.
:param default_values:
Default values defined by a module or class.
:param user_values:
User values, used when an object can be initialized with
configuration. This overrides the app configuration.
:param required_keys:
Keys that can not be None.
:raises:
Exception, when a required key is not set or is None.
"""
if key in self.loaded:
config = self[key]
else:
config = dict(default_values or ())
if key in self:
config.update(self[key])
self[key] = config
self.loaded.append(key)
if required_keys and not user_values:
self._validate_required(key, config, required_keys)
if user_values:
config = config.copy()
config.update(user_values)
if required_keys:
self._validate_required(key, config, required_keys)
return config
def _validate_required(self, key, config, required_keys):
missing = [k for k in required_keys if config.get(k) is None]
if missing:
raise Exception(
'Missing configuration keys for %r: %r.' % (key, missing))
class RequestContext(object):
"""Context for a single request.
The context is responsible for setting and cleaning global variables for
a request.
"""
#: A :class:`WSGIApplication` instance.
app = None
#: WSGI environment dictionary.
environ = None
def __init__(self, app, environ):
"""Initializes the request context.
:param app:
An :class:`WSGIApplication` instance.
:param environ:
A WSGI environment dictionary.
"""
self.app = app
self.environ = environ
def __enter__(self):
"""Enters the request context.
:returns:
A tuple ``(request, response)``.
"""
# Build request and response.
request = self.app.request_class(self.environ)
response = self.app.response_class()
# Make active app and response available through the request object.
request.app = self.app
request.response = response
# Register global variables.
self.app.set_globals(app=self.app, request=request)
return request, response
def __exit__(self, exc_type, exc_value, traceback):
"""Exits the request context.
This release the context locals except if an exception is caught
in debug mode. In this case they are kept to be inspected.
"""
if exc_type is None or not self.app.debug:
# Unregister global variables.
self.app.clear_globals()
class WSGIApplication(object):
"""A WSGI-compliant application."""
#: Allowed request methods.
allowed_methods = frozenset(('GET', 'POST', 'HEAD', 'OPTIONS', 'PUT',
'DELETE', 'TRACE'))
#: Class used for the request object.
request_class = Request
#: Class used for the response object.
response_class = Response
#: Class used for the router object.
router_class = Router
#: Class used for the request context object.
request_context_class = RequestContext
#: Class used for the configuration object.
config_class = Config
#: A general purpose flag to indicate development mode: if True, uncaught
#: exceptions are raised instead of using ``HTTPInternalServerError``.
debug = False
#: A :class:`Router` instance with all URIs registered for the application.
router = None
#: A :class:`Config` instance with the application configuration.
config = None
#: A dictionary to register objects used during the app lifetime.
registry = None
#: A dictionary mapping HTTP error codes to callables to handle those
#: HTTP exceptions. See :meth:`handle_exception`.
error_handlers = None
#: Active :class:`WSGIApplication` instance. See :meth:`set_globals`.
app = None
#: Active :class:`Request` instance. See :meth:`set_globals`.
request = None
#: Same as :attr:`app`, for webapp compatibility. See :meth:`set_globals`.
active_instance = None
def __init__(self, routes=None, debug=False, config=None):
"""Initializes the WSGI application.
:param routes:
A sequence of :class:`Route` instances or, for simple routes,
tuples ``(regex, handler)``.
:param debug:
True to enable debug mode, False otherwise.
:param config:
A configuration dictionary for the application.
"""
self.debug = debug
self.registry = {}
self.error_handlers = {}
self.config = self.config_class(config)
self.router = self.router_class(routes)
def set_globals(self, app=None, request=None):
"""Registers the global variables for app and request.
If :mod:`webapp2_extras.local` is available the app and request
class attributes are assigned to a proxy object that returns them
using thread-local, making the application thread-safe. This can also
be used in environments that don't support threading.
If :mod:`webapp2_extras.local` is not available app and request will
be assigned directly as class attributes. This should only be used in
non-threaded environments (e.g., App Engine Python 2.5).
:param app:
A :class:`WSGIApplication` instance.
:param request:
A :class:`Request` instance.
"""
if _local is not None: # pragma: no cover
_local.app = app
_local.request = request
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = app
WSGIApplication.request = request
def clear_globals(self):
"""Clears global variables. See :meth:`set_globals`."""
if _local is not None: # pragma: no cover
_local.__release_local__()
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = None
WSGIApplication.request = None
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in.
:param environ:
A WSGI environment.
:param start_response:
A callable accepting a status code, a list of headers and an
optional exception context to start the response.
:returns:
An iterable with the response to return to the client.
"""
with self.request_context_class(self, environ) as (request, response):
try:
if request.method not in self.allowed_methods:
# 501 Not Implemented.
raise exc.HTTPNotImplemented()
rv = self.router.dispatch(request, response)
if rv is not None:
response = rv
except Exception, e:
try:
# Try to handle it with a custom error handler.
rv = self.handle_exception(request, response, e)
if rv is not None:
response = rv
except HTTPException, e:
# Use the HTTP exception as response.
response = e
except Exception, e:
# Error wasn't handled so we have nothing else to do.
response = self._internal_error(e)
try:
return response(environ, start_response)
except Exception, e:
return self._internal_error(e)(environ, start_response)
def _internal_error(self, exception):
"""Last resource error for :meth:`__call__`."""
logging.exception(exception)
if self.debug:
lines = ''.join(traceback.format_exception(*sys.exc_info()))
html = _debug_template % (cgi.escape(lines, quote=True))
return Response(body=html, status=500)
return exc.HTTPInternalServerError()
def handle_exception(self, request, response, e):
"""Handles a uncaught exception occurred in :meth:`__call__`.
Uncaught exceptions can be handled by error handlers registered in
:attr:`error_handlers`. This is a dictionary that maps HTTP status
codes to callables that will handle the corresponding error code.
If the exception is not an ``HTTPException``, the status code 500
is used.
The error handlers receive (request, response, exception) and can be
a callable or a string in dotted notation to be lazily imported.
If no error handler is found, the exception is re-raised.
Based on idea from `Flask`_.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
:param e:
The uncaught exception.
:returns:
The returned value from the error handler.
"""
if isinstance(e, HTTPException):
code = e.code
else:
code = 500
handler = self.error_handlers.get(code)
if handler:
if isinstance(handler, basestring):
self.error_handlers[code] = handler = import_string(handler)
return handler(request, response, e)
else:
# Re-raise it to be caught by the WSGI app.
raise
def run(self, bare=False):
"""Runs this WSGI-compliant application in a CGI environment.
This uses functions provided by ``google.appengine.ext.webapp.util``,
if available: ``run_bare_wsgi_app`` and ``run_wsgi_app``.
Otherwise, it uses ``wsgiref.handlers.CGIHandler().run()``.
:param bare:
If True, doesn't add registered WSGI middleware: use
``run_bare_wsgi_app`` instead of ``run_wsgi_app``.
"""
if _webapp_util:
if bare:
_webapp_util.run_bare_wsgi_app(self)
else:
_webapp_util.run_wsgi_app(self)
else: # pragma: no cover
handlers.CGIHandler().run(self)
def get_response(self, *args, **kwargs):
"""Creates a request and returns a response for this app.
This is a convenience for unit testing purposes. It receives
parameters to build a request and calls the application, returning
the resulting response::
class HelloHandler(webapp2.RequestHandler):
def get(self):
self.response.write('Hello, world!')
app = webapp2.WSGIapplication([('/', HelloHandler)])
# Test the app, passing parameters to build a request.
response = app.get_response('/')
assert response.status_int == 200
assert response.body == 'Hello, world!'
:param args:
Positional arguments to be passed to ``Request.blank()``.
:param kwargs:
Keyword arguments to be passed to ``Request.blank()``.
:returns:
A :class:`Response` object.
"""
return self.request_class.blank(*args, **kwargs).get_response(self)
_import_string_error = """\
import_string() failed for %r. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Original exception:
%s: %s
Debugged import:
%s"""
class ImportStringError(Exception):
"""Provides information about a failed :func:`import_string` attempt."""
#: String in dotted notation that failed to be imported.
import_name = None
#: Wrapped exception.
exception = None
def __init__(self, import_name, exception):
self.import_name = import_name
self.exception = exception
msg = _import_string_error
name = ''
tracked = []
for part in import_name.split('.'):
name += (name and '.') + part
imported = import_string(name, silent=True)
if imported:
tracked.append((name, imported.__file__))
else:
track = ['- %r found in %r.' % rv for rv in tracked]
track.append('- %r not found.' % name)
msg = msg % (import_name, exception.__class__.__name__,
str(exception), '\n'.join(track))
break
Exception.__init__(self, msg)
_get_app_error = 'WSGIApplication global variable is not set.'
_get_request_error = 'Request global variable is not set.'
def get_app():
"""Returns the active app instance.
:returns:
A :class:`WSGIApplication` instance.
"""
if _local:
assert getattr(_local, 'app', None) is not None, _get_app_error
else:
assert WSGIApplication.app is not None, _get_app_error
return WSGIApplication.app
def get_request():
"""Returns the active request instance.
:returns:
A :class:`Request` instance.
"""
if _local:
assert getattr(_local, 'request', None) is not None, _get_request_error
else:
assert WSGIApplication.request is not None, _get_request_error
return WSGIApplication.request
def uri_for(_name, _request=None, *args, **kwargs):
"""A standalone uri_for version that can be passed to templates.
.. seealso:: :meth:`Router.build`.
"""
request = _request or get_request()
return request.app.router.build(request, _name, args, kwargs)
def redirect(uri, permanent=False, abort=False, code=None, body=None,
request=None, response=None):
"""Issues an HTTP redirect to the given relative URI.
This won't stop code execution unless **abort** is True. A common
practice is to return when calling this method::
return redirect('/some-path')
:param uri:
A relative or absolute URI (e.g., ``'../flowers.html'``).
:param permanent:
If True, uses a 301 redirect instead of a 302 redirect.
:param abort:
If True, raises an exception to perform the redirect.
:param code:
The redirect status code. Supported codes are 301, 302, 303, 305,
and 307. 300 is not supported because it's not a real redirect
and 304 because it's the answer for a request with defined
``If-Modified-Since`` headers.
:param body:
Response body, if any.
:param request:
Optional request object. If not set, uses :func:`get_request`.
:param response:
Optional response object. If not set, a new response is created.
:returns:
A :class:`Response` instance.
"""
if uri.startswith(('.', '/')):
request = request or get_request()
uri = str(urlparse.urljoin(request.url, uri))
if code is None:
if permanent:
code = 301
else:
code = 302
assert code in (301, 302, 303, 305, 307), \
'Invalid redirect status code.'
if abort:
_abort(code, headers=[('Location', uri)])
if response is None:
request = request or get_request()
response = request.app.response_class()
else:
response.clear()
response.headers['Location'] = uri
response.status = code
if body is not None:
response.write(body)
return response
def redirect_to(_name, _permanent=False, _abort=False, _code=None,
_body=None, _request=None, _response=None, *args, **kwargs):
"""Convenience function mixing :func:`redirect` and :func:`uri_for`.
Issues an HTTP redirect to a named URI built using :func:`uri_for`.
:param _name:
The route name to redirect to.
:param args:
Positional arguments to build the URI.
:param kwargs:
Keyword arguments to build the URI.
:returns:
A :class:`Response` instance.
The other arguments are described in :func:`redirect`.
"""
uri = uri_for(_name, _request=_request, *args, **kwargs)
return redirect(uri, permanent=_permanent, abort=_abort, code=_code,
body=_body, request=_request, response=_response)
def abort(code, *args, **kwargs):
"""Raises an ``HTTPException``.
:param code:
An integer that represents a valid HTTP status code.
:param args:
Positional arguments to instantiate the exception.
:param kwargs:
Keyword arguments to instantiate the exception.
"""
cls = exc.status_map.get(code)
if not cls:
raise KeyError('No exception is defined for code %r.' % code)
raise cls(*args, **kwargs)
def import_string(import_name, silent=False):
"""Imports an object based on a string in dotted notation.
Simplified version of the function with same name from `Werkzeug`_.
:param import_name:
String in dotted notation of the object to be imported.
:param silent:
If True, import or attribute errors are ignored and None is returned
instead of raising an exception.
:returns:
The imported object.
"""
import_name = _to_utf8(import_name)
try:
if '.' in import_name:
module, obj = import_name.rsplit('.', 1)
return getattr(__import__(module, None, None, [obj]), obj)
else:
return __import__(import_name)
except (ImportError, AttributeError), e:
if not silent:
raise ImportStringError(import_name, e), None, sys.exc_info()[2]
def _urlunsplit(scheme=None, netloc=None, path=None, query=None,
fragment=None):
"""Like ``urlparse.urlunsplit``, but will escape values and urlencode and
sort query arguments.
:param scheme:
URI scheme, e.g., `http` or `https`.
:param netloc:
Network location, e.g., `localhost:8080` or `www.google.com`.
:param path:
URI path.
:param query:
URI query as an escaped string, or a dictionary or list of key-values
tuples to build a query.
:param fragment:
Fragment identifier, also known as "anchor".
:returns:
An assembled absolute or relative URI.
"""
if not scheme or not netloc:
scheme = None
netloc = None
if path:
path = urllib.quote(_to_utf8(path))
if query and not isinstance(query, basestring):
if isinstance(query, dict):
query = query.iteritems()
# Sort args: commonly needed to build signatures for services.
query = urllib.urlencode(sorted(query))
if fragment:
fragment = urllib.quote(_to_utf8(fragment))
return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
def _get_handler_methods(handler):
"""Returns a list of HTTP methods supported by a handler.
:param handler:
A :class:`RequestHandler` instance.
:returns:
A list of HTTP methods supported by the handler.
"""
methods = []
for method in get_app().allowed_methods:
if getattr(handler, _normalize_handler_method(method), None):
methods.append(method)
return methods
def _normalize_handler_method(method):
"""Transforms an HTTP method into a valid Python identifier."""
return method.lower().replace('-', '_')
def _to_utf8(value):
"""Encodes a unicode value to UTF-8 if not yet encoded."""
if isinstance(value, str):
return value
return value.encode('utf-8')
def _parse_route_template(template, default_sufix=''):
"""Lazy route template parser."""
variables = {}
reverse_template = pattern = ''
args_count = last = 0
for match in _route_re.finditer(template):
part = template[last:match.start()]
name = match.group(1)
expr = match.group(2) or default_sufix
last = match.end()
if not name:
name = '__%d__' % args_count
args_count += 1
pattern += '%s(?P<%s>%s)' % (re.escape(part), name, expr)
reverse_template += '%s%%(%s)s' % (part, name)
variables[name] = re.compile('^%s$' % expr)
part = template[last:]
kwargs_count = len(variables) - args_count
reverse_template += part
regex = re.compile('^%s%s$' % (pattern, re.escape(part)))
return regex, reverse_template, args_count, kwargs_count, variables
def _get_route_variables(match, default_kwargs=None):
"""Returns (args, kwargs) for a route match."""
kwargs = default_kwargs or {}
kwargs.update(match.groupdict())
if kwargs:
args = tuple(value[1] for value in sorted(
(int(key[2:-2]), kwargs.pop(key)) for key in kwargs.keys() \
if key.startswith('__') and key.endswith('__')))
else:
args = ()
return args, kwargs
def _set_thread_safe_app():
"""Assigns WSGIApplication globals to a proxy pointing to thread-local."""
if _local is not None: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = _local('app')
WSGIApplication.request = _local('request')
Request.ResponseClass = Response
Response.RequestClass = Request
# Alias.
_abort = abort
# Thread-safety support.
_set_thread_safe_app()
# Defer importing google.appengine.ext.webapp.util until every public symbol
# has been defined since google.appengine.ext.webapp in App Engine Python 2.7
# runtime imports this module to provide its public interface.
try:
from google.appengine.ext.webapp import util as _webapp_util
except ImportError: # pragma: no cover
pass
| Python |
import webapp2
class HomeHandler(webapp2.RequestHandler):
def get(self, **kwargs):
html = '<a href="%s">test item</a>' % self.url_for('view', item='test')
self.response.out.write(html)
class ViewHandler(webapp2.RequestHandler):
def get(self, **kwargs):
item = kwargs.get('item')
self.response.out.write('You are viewing item "%s".' % item)
class HandlerWithError(webapp2.RequestHandler):
def get(self, **kwargs):
raise ValueError('Oops!')
def get_redirect_url(handler, **kwargs):
return handler.url_for('view', item='i-came-from-a-redirect')
app = webapp2.WSGIApplication([
# Home sweet home.
webapp2.Route('/', HomeHandler, name='home'),
# A route with a named variable.
webapp2.Route('/view/<item>', ViewHandler, name='view'),
# Loads a handler lazily.
webapp2.Route('/lazy', 'handlers.LazyHandler', name='lazy'),
# Redirects to a given path.
webapp2.Route('/redirect-me', webapp2.RedirectHandler, defaults={'url': '/lazy'}),
# Redirects to a URL using a callable to get the destination URL.
webapp2.Route('/redirect-me2', webapp2.RedirectHandler, defaults={'url': get_redirect_url}),
# No exception should pass. If exceptions are not handled, a 500 page is displayed.
webapp2.Route('/exception', HandlerWithError),
])
| Python |
import webapp2
class LazyHandler(webapp2.RequestHandler):
def get(self, **kwargs):
self.response.out.write('I am a laaazy view.')
| Python |
# -*- coding: utf-8 -*-
"""
webapp2
=======
Taking Google App Engine's webapp to the next level!
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from __future__ import with_statement
import cgi
import inspect
import logging
import os
import re
import sys
import threading
import traceback
import urllib
import urlparse
from wsgiref import handlers
import webob
from webob import exc
_webapp = _webapp_util = _local = None
try: # pragma: no cover
# WebOb < 1.0 (App Engine Python 2.5).
from webob.statusreasons import status_reasons
from webob.headerdict import HeaderDict as BaseResponseHeaders
except ImportError: # pragma: no cover
# WebOb >= 1.0.
from webob.util import status_reasons
from webob.headers import ResponseHeaders as BaseResponseHeaders
# google.appengine.ext.webapp imports webapp2 in the
# App Engine Python 2.7 runtime.
if os.environ.get('APPENGINE_RUNTIME') != 'python27': # pragma: no cover
try:
from google.appengine.ext import webapp as _webapp
except ImportError: # pragma: no cover
# Running webapp2 outside of GAE.
pass
try: # pragma: no cover
# Thread-local variables container.
from webapp2_extras import local
_local = local.Local()
except ImportError: # pragma: no cover
logging.warning("webapp2_extras.local is not available "
"so webapp2 won't be thread-safe!")
__version_info__ = (2, 5, 2)
__version__ = '.'.join(str(n) for n in __version_info__)
#: Base HTTP exception, set here as public interface.
HTTPException = exc.HTTPException
#: Regex for route definitions.
_route_re = re.compile(r"""
\< # The exact character "<"
([a-zA-Z_]\w*)? # The optional variable name
(?:\:([^\>]*))? # The optional :regex part
\> # The exact character ">"
""", re.VERBOSE)
#: Regex extract charset from environ.
_charset_re = re.compile(r';\s*charset=([^;]*)', re.I)
#: To show exceptions in debug mode.
_debug_template = """<html>
<head>
<title>Internal Server Error</title>
<style>
body {
padding: 20px;
font-family: arial, sans-serif;
font-size: 14px;
}
pre {
background: #F2F2F2;
padding: 10px;
}
</style>
</head>
<body>
<h1>Internal Server Error</h1>
<p>The server has either erred or is incapable of performing
the requested operation.</p>
<pre>%s</pre>
</body>
</html>"""
# Set same default messages from webapp plus missing ones.
_webapp_status_reasons = {
203: 'Non-Authoritative Information',
302: 'Moved Temporarily',
306: 'Unused',
408: 'Request Time-out',
414: 'Request-URI Too Large',
504: 'Gateway Time-out',
505: 'HTTP Version not supported',
}
status_reasons.update(_webapp_status_reasons)
for code, message in _webapp_status_reasons.iteritems():
cls = exc.status_map.get(code)
if cls:
cls.title = message
class Request(webob.Request):
"""Abstraction for an HTTP request.
Most extra methods and attributes are ported from webapp. Check the
`WebOb`_ documentation for the ones not listed here.
"""
#: A reference to the active :class:`WSGIApplication` instance.
app = None
#: A reference to the active :class:`Response` instance.
response = None
#: A reference to the matched :class:`Route`.
route = None
#: The matched route positional arguments.
route_args = None
#: The matched route keyword arguments.
route_kwargs = None
#: A dictionary to register objects used during the request lifetime.
registry = None
# Attributes from webapp.
request_body_tempfile_limit = 0
uri = property(lambda self: self.url)
query = property(lambda self: self.query_string)
def __init__(self, environ, *args, **kwargs):
"""Constructs a Request object from a WSGI environment.
:param environ:
A WSGI-compliant environment dictionary.
"""
if kwargs.get('charset') is None and not hasattr(webob, '__version__'):
# webob 0.9 didn't have a __version__ attribute and also defaulted
# to None rather than UTF-8 if no charset was provided. Providing a
# default charset is required for backwards compatibility.
match = _charset_re.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
kwargs['charset'] = charset
super(Request, self).__init__(environ, *args, **kwargs)
self.registry = {}
def get(self, argument_name, default_value='', allow_multiple=False):
"""Returns the query or POST argument with the given name.
We parse the query string and POST payload lazily, so this will be a
slower operation on the first call.
:param argument_name:
The name of the query or POST argument.
:param default_value:
The value to return if the given argument is not present.
:param allow_multiple:
Return a list of values with the given name (deprecated).
:returns:
If allow_multiple is False (which it is by default), we return
the first value with the given name given in the request. If it
is True, we always return a list.
"""
param_value = self.get_all(argument_name)
if allow_multiple:
logging.warning('allow_multiple is a deprecated param. '
'Please use the Request.get_all() method instead.')
if len(param_value) > 0:
if allow_multiple:
return param_value
return param_value[0]
else:
if allow_multiple and not default_value:
return []
return default_value
def get_all(self, argument_name, default_value=None):
"""Returns a list of query or POST arguments with the given name.
We parse the query string and POST payload lazily, so this will be a
slower operation on the first call.
:param argument_name:
The name of the query or POST argument.
:param default_value:
The value to return if the given argument is not present,
None may not be used as a default, if it is then an empty
list will be returned instead.
:returns:
A (possibly empty) list of values.
"""
if self.charset:
argument_name = argument_name.encode(self.charset)
if default_value is None:
default_value = []
param_value = self.params.getall(argument_name)
if param_value is None or len(param_value) == 0:
return default_value
for i in xrange(len(param_value)):
if isinstance(param_value[i], cgi.FieldStorage):
param_value[i] = param_value[i].value
return param_value
def arguments(self):
"""Returns a list of the arguments provided in the query and/or POST.
The return value is a list of strings.
"""
return list(set(self.params.keys()))
def get_range(self, name, min_value=None, max_value=None, default=0):
"""Parses the given int argument, limiting it to the given range.
:param name:
The name of the argument.
:param min_value:
The minimum int value of the argument (if any).
:param max_value:
The maximum int value of the argument (if any).
:param default:
The default value of the argument if it is not given.
:returns:
An int within the given range for the argument.
"""
value = self.get(name, default)
if value is None:
return value
try:
value = int(value)
except ValueError:
value = default
if value is not None:
if max_value is not None:
value = min(value, max_value)
if min_value is not None:
value = max(value, min_value)
return value
@classmethod
def blank(cls, path, environ=None, base_url=None,
headers=None, **kwargs): # pragma: no cover
"""Adds parameters compatible with WebOb >= 1.0: POST and **kwargs."""
try:
return super(Request, cls).blank(path, environ=environ,
base_url=base_url,
headers=headers, **kwargs)
except TypeError:
if not kwargs:
raise
data = kwargs.pop('POST', None)
if data is not None:
from cStringIO import StringIO
environ = environ or {}
environ['REQUEST_METHOD'] = 'POST'
if hasattr(data, 'items'):
data = data.items()
if not isinstance(data, str):
data = urllib.urlencode(data)
environ['wsgi.input'] = StringIO(data)
environ['webob.is_body_seekable'] = True
environ['CONTENT_LENGTH'] = str(len(data))
environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
base = super(Request, cls).blank(path, environ=environ,
base_url=base_url, headers=headers)
if kwargs:
obj = cls(base.environ, **kwargs)
obj.headers.update(base.headers)
return obj
else:
return base
class ResponseHeaders(BaseResponseHeaders):
"""Implements methods from ``wsgiref.headers.Headers``, used by webapp."""
get_all = BaseResponseHeaders.getall
def add_header(self, _name, _value, **_params):
"""Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example::
h.add_header('content-disposition', 'attachment',
filename='bud.gif')
Note that unlike the corresponding 'email.message' method, this does
*not* handle '(charset, language, value)' tuples: all values must be
strings or None.
"""
parts = []
if _value is not None:
parts.append(_value)
for k, v in _params.items():
k = k.replace('_', '-')
if v is not None and len(v) > 0:
v = v.replace('\\', '\\\\').replace('"', r'\"')
parts.append('%s="%s"' % (k, v))
else:
parts.append(k)
self.add(_name, '; '.join(parts))
def __str__(self):
"""Returns the formatted headers ready for HTTP transmission."""
return '\r\n'.join(['%s: %s' % v for v in self.items()] + ['', ''])
class Response(webob.Response):
"""Abstraction for an HTTP response.
Most extra methods and attributes are ported from webapp. Check the
`WebOb`_ documentation for the ones not listed here.
Differences from webapp.Response:
- ``out`` is not a ``StringIO.StringIO`` instance. Instead it is the
response itself, as it has the method ``write()``.
- As in WebOb, ``status`` is the code plus message, e.g., '200 OK', while
in webapp it is the integer code. The status code as an integer is
available in ``status_int``, and the status message is available in
``status_message``.
- ``response.headers`` raises an exception when a key that doesn't exist
is accessed or deleted, differently from ``wsgiref.headers.Headers``.
"""
#: Default charset as in webapp.
default_charset = 'utf-8'
def __init__(self, *args, **kwargs):
"""Constructs a response with the default settings."""
super(Response, self).__init__(*args, **kwargs)
self.headers['Cache-Control'] = 'no-cache'
@property
def out(self):
"""A reference to the Response instance itself, for compatibility with
webapp only: webapp uses `Response.out.write()`, so we point `out` to
`self` and it will use `Response.write()`.
"""
return self
def write(self, text):
"""Appends a text to the response body."""
# webapp uses StringIO as Response.out, so we need to convert anything
# that is not str or unicode to string to keep same behavior.
if not isinstance(text, basestring):
text = unicode(text)
if isinstance(text, unicode) and not self.charset:
self.charset = self.default_charset
super(Response, self).write(text)
def _set_status(self, value):
"""The status string, including code and message."""
message = None
# Accept long because urlfetch in App Engine returns codes as longs.
if isinstance(value, (int, long)):
code = int(value)
else:
if isinstance(value, unicode):
# Status messages have to be ASCII safe, so this is OK.
value = str(value)
if not isinstance(value, str):
raise TypeError(
'You must set status to a string or integer (not %s)' %
type(value))
parts = value.split(' ', 1)
code = int(parts[0])
if len(parts) == 2:
message = parts[1]
message = message or Response.http_status_message(code)
self._status = '%d %s' % (code, message)
def _get_status(self):
return self._status
status = property(_get_status, _set_status, doc=_set_status.__doc__)
def set_status(self, code, message=None):
"""Sets the HTTP status code of this response.
:param code:
The HTTP status string to use
:param message:
A status string. If none is given, uses the default from the
HTTP/1.1 specification.
"""
if message:
self.status = '%d %s' % (code, message)
else:
self.status = code
def _get_status_message(self):
"""The response status message, as a string."""
return self.status.split(' ', 1)[1]
def _set_status_message(self, message):
self.status = '%d %s' % (self.status_int, message)
status_message = property(_get_status_message, _set_status_message,
doc=_get_status_message.__doc__)
def _get_headers(self):
"""The headers as a dictionary-like object."""
if self._headers is None:
self._headers = ResponseHeaders.view_list(self.headerlist)
return self._headers
def _set_headers(self, value):
if hasattr(value, 'items'):
value = value.items()
elif not isinstance(value, list):
raise TypeError('Response headers must be a list or dictionary.')
self.headerlist = value
self._headers = None
headers = property(_get_headers, _set_headers, doc=_get_headers.__doc__)
def has_error(self):
"""Indicates whether the response was an error response."""
return self.status_int >= 400
def clear(self):
"""Clears all data written to the output stream so that it is empty."""
self.body = ''
def wsgi_write(self, start_response):
"""Writes this response using using the given WSGI function.
This is only here for compatibility with ``webapp.WSGIApplication``.
:param start_response:
The WSGI-compatible start_response function.
"""
if (self.headers.get('Cache-Control') == 'no-cache' and
not self.headers.get('Expires')):
self.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'
self.headers['Content-Length'] = str(len(self.body))
write = start_response(self.status, self.headerlist)
write(self.body)
@staticmethod
def http_status_message(code):
"""Returns the default HTTP status message for the given code.
:param code:
The HTTP code for which we want a message.
"""
message = status_reasons.get(code)
if not message:
raise KeyError('Invalid HTTP status code: %d' % code)
return message
class RequestHandler(object):
"""Base HTTP request handler.
Implements most of ``webapp.RequestHandler`` interface.
"""
#: A :class:`Request` instance.
request = None
#: A :class:`Response` instance.
response = None
#: A :class:`WSGIApplication` instance.
app = None
def __init__(self, request=None, response=None):
"""Initializes this request handler with the given WSGI application,
Request and Response.
When instantiated by ``webapp.WSGIApplication``, request and response
are not set on instantiation. Instead, initialize() is called right
after the handler is created to set them.
Also in webapp dispatching is done by the WSGI app, while webapp2
does it here to allow more flexibility in extended classes: handlers
can wrap :meth:`dispatch` to check for conditions before executing the
requested method and/or post-process the response.
.. note::
Parameters are optional only to support webapp's constructor which
doesn't take any arguments. Consider them as required.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.initialize(request, response)
def initialize(self, request, response):
"""Initializes this request handler with the given WSGI application,
Request and Response.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.request = request
self.response = response
self.app = WSGIApplication.active_instance
def dispatch(self):
"""Dispatches the request.
This will first check if there's a handler_method defined in the
matched route, and if not it'll use the method correspondent to the
request method (``get()``, ``post()`` etc).
"""
request = self.request
method_name = request.route.handler_method
if not method_name:
method_name = _normalize_handler_method(request.method)
method = getattr(self, method_name, None)
if method is None:
# 405 Method Not Allowed.
# The response MUST include an Allow header containing a
# list of valid methods for the requested resource.
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6
valid = ', '.join(_get_handler_methods(self))
self.abort(405, headers=[('Allow', valid)])
# The handler only receives *args if no named variables are set.
args, kwargs = request.route_args, request.route_kwargs
if kwargs:
args = ()
try:
return method(*args, **kwargs)
except Exception, e:
return self.handle_exception(e, self.app.debug)
def error(self, code):
"""Clears the response and sets the given HTTP status code.
This doesn't stop code execution; for this, use :meth:`abort`.
:param code:
HTTP status error code (e.g., 501).
"""
self.response.status = code
self.response.clear()
def abort(self, code, *args, **kwargs):
"""Raises an :class:`HTTPException`.
This stops code execution, leaving the HTTP exception to be handled
by an exception handler.
:param code:
HTTP status code (e.g., 404).
:param args:
Positional arguments to be passed to the exception class.
:param kwargs:
Keyword arguments to be passed to the exception class.
"""
abort(code, *args, **kwargs)
def redirect(self, uri, permanent=False, abort=False, code=None,
body=None):
"""Issues an HTTP redirect to the given relative URI.
The arguments are described in :func:`redirect`.
"""
return redirect(uri, permanent=permanent, abort=abort, code=code,
body=body, request=self.request,
response=self.response)
def redirect_to(self, _name, _permanent=False, _abort=False, _code=None,
_body=None, *args, **kwargs):
"""Convenience method mixing :meth:`redirect` and :meth:`uri_for`.
The arguments are described in :func:`redirect` and :func:`uri_for`.
"""
uri = self.uri_for(_name, *args, **kwargs)
return self.redirect(uri, permanent=_permanent, abort=_abort,
code=_code, body=_body)
def uri_for(self, _name, *args, **kwargs):
"""Returns a URI for a named :class:`Route`.
.. seealso:: :meth:`Router.build`.
"""
return self.app.router.build(self.request, _name, args, kwargs)
# Alias.
url_for = uri_for
def handle_exception(self, exception, debug):
"""Called if this handler throws an exception during execution.
The default behavior is to re-raise the exception to be handled by
:meth:`WSGIApplication.handle_exception`.
:param exception:
The exception that was thrown.
:param debug_mode:
True if the web application is running in debug mode.
"""
raise
class RedirectHandler(RequestHandler):
"""Redirects to the given URI for all GET requests.
This is intended to be used when defining URI routes. You must provide at
least the keyword argument *url* in the route default values. Example::
def get_redirect_url(handler, *args, **kwargs):
return handler.uri_for('new-route-name')
app = WSGIApplication([
Route('/old-url', RedirectHandler, defaults={'_uri': '/new-url'}),
Route('/other-old-url', RedirectHandler, defaults={
'_uri': get_redirect_url}),
])
Based on idea from `Tornado`_.
"""
def get(self, *args, **kwargs):
"""Performs a redirect.
Two keyword arguments can be passed through the URI route:
- **_uri**: A URI string or a callable that returns a URI. The callable
is called passing ``(handler, *args, **kwargs)`` as arguments.
- **_code**: The redirect status code. Default is 301 (permanent
redirect).
"""
uri = kwargs.pop('_uri', '/')
permanent = kwargs.pop('_permanent', True)
code = kwargs.pop('_code', None)
func = getattr(uri, '__call__', None)
if func:
uri = func(self, *args, **kwargs)
self.redirect(uri, permanent=permanent, code=code)
class cached_property(object):
"""A decorator that converts a function into a lazy property.
The function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
the value::
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a `__dict__` in order for this property to
work.
.. note:: Implementation detail: this property is implemented as non-data
descriptor. non-data descriptors are only invoked if there is
no entry with the same name in the instance's __dict__.
this allows us to completely get rid of the access function call
overhead. If one choses to invoke __get__ by hand the property
will still work as expected because the lookup logic is replicated
in __get__ for manual invocation.
This class was ported from `Werkzeug`_ and `Flask`_.
"""
_default_value = object()
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
self.lock = threading.RLock()
def __get__(self, obj, type=None):
if obj is None:
return self
with self.lock:
value = obj.__dict__.get(self.__name__, self._default_value)
if value is self._default_value:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
class BaseRoute(object):
"""Interface for URI routes."""
#: The regex template.
template = None
#: Route name, used to build URIs.
name = None
#: True if this route is only used for URI generation and never matches.
build_only = False
#: The handler or string in dotted notation to be lazily imported.
handler = None
#: The custom handler method, if handler is a class.
handler_method = None
#: The handler, imported and ready for dispatching.
handler_adapter = None
def __init__(self, template, handler=None, name=None, build_only=False):
"""Initializes this route.
:param template:
A regex to be matched.
:param handler:
A callable or string in dotted notation to be lazily imported,
e.g., ``'my.module.MyHandler'`` or ``'my.module.my_function'``.
:param name:
The name of this route, used to build URIs based on it.
:param build_only:
If True, this route never matches and is used only to build URIs.
"""
if build_only and name is None:
raise ValueError(
"Route %r is build_only but doesn't have a name." % self)
self.template = template
self.handler = handler
self.name = name
self.build_only = build_only
def match(self, request):
"""Matches all routes against a request object.
The first one that matches is returned.
:param request:
A :class:`Request` instance.
:returns:
A tuple ``(route, args, kwargs)`` if a route matched, or None.
"""
raise NotImplementedError()
def build(self, request, args, kwargs):
"""Returns a URI for this route.
:param request:
The current :class:`Request` object.
:param args:
Tuple of positional arguments to build the URI.
:param kwargs:
Dictionary of keyword arguments to build the URI.
:returns:
An absolute or relative URI.
"""
raise NotImplementedError()
def get_routes(self):
"""Generator to get all routes from a route.
:yields:
This route or all nested routes that it contains.
"""
yield self
def get_match_routes(self):
"""Generator to get all routes that can be matched from a route.
Match routes must implement :meth:`match`.
:yields:
This route or all nested routes that can be matched.
"""
if not self.build_only:
yield self
def get_build_routes(self):
"""Generator to get all routes that can be built from a route.
Build routes must implement :meth:`build`.
:yields:
A tuple ``(name, route)`` for all nested routes that can be built.
"""
if self.name is not None:
yield self.name, self
class SimpleRoute(BaseRoute):
"""A route that is compatible with webapp's routing mechanism.
URI building is not implemented as webapp has rudimentar support for it,
and this is the most unknown webapp feature anyway.
"""
@cached_property
def regex(self):
"""Lazy regex compiler."""
if not self.template.startswith('^'):
self.template = '^' + self.template
if not self.template.endswith('$'):
self.template += '$'
return re.compile(self.template)
def match(self, request):
"""Matches this route against the current request.
.. seealso:: :meth:`BaseRoute.match`.
"""
match = self.regex.match(urllib.unquote(request.path))
if match:
return self, match.groups(), {}
def __repr__(self):
return '<SimpleRoute(%r, %r)>' % (self.template, self.handler)
class Route(BaseRoute):
"""A route definition that maps a URI path to a handler.
The initial concept was based on `Another Do-It-Yourself Framework`_, by
Ian Bicking.
"""
#: Default parameters values.
defaults = None
#: Sequence of allowed HTTP methods. If not set, all methods are allowed.
methods = None
#: Sequence of allowed URI schemes. If not set, all schemes are allowed.
schemes = None
# Lazy properties extracted from the route template.
regex = None
reverse_template = None
variables = None
args_count = 0
kwargs_count = 0
def __init__(self, template, handler=None, name=None, defaults=None,
build_only=False, handler_method=None, methods=None,
schemes=None):
"""Initializes this route.
:param template:
A route template to match against the request path. A template
can have variables enclosed by ``<>`` that define a name, a
regular expression or both. Examples:
================= ==================================
Format Example
================= ==================================
``<name>`` ``'/blog/<year>/<month>'``
``<:regex>`` ``'/blog/<:\d{4}>/<:\d{2}>'``
``<name:regex>`` ``'/blog/<year:\d{4}>/<month:\d{2}>'``
================= ==================================
The same template can mix parts with name, regular expression or
both.
If the name is set, the value of the matched regular expression
is passed as keyword argument to the handler. Otherwise it is
passed as positional argument.
If only the name is set, it will match anything except a slash.
So these routes are equivalent::
Route('/<user_id>/settings', handler=SettingsHandler,
name='user-settings')
Route('/<user_id:[^/]+>/settings', handler=SettingsHandler,
name='user-settings')
.. note::
The handler only receives ``*args`` if no named variables are
set. Otherwise, the handler only receives ``**kwargs``. This
allows you to set regular expressions that are not captured:
just mix named and unnamed variables and the handler will
only receive the named ones.
:param handler:
A callable or string in dotted notation to be lazily imported,
e.g., ``'my.module.MyHandler'`` or ``'my.module.my_function'``.
It is possible to define a method if the callable is a class,
separating it by a colon: ``'my.module.MyHandler:my_method'``.
This is a shortcut and has the same effect as defining the
`handler_method` parameter.
:param name:
The name of this route, used to build URIs based on it.
:param defaults:
Default or extra keywords to be returned by this route. Values
also present in the route variables are used to build the URI
when they are missing.
:param build_only:
If True, this route never matches and is used only to build URIs.
:param handler_method:
The name of a custom handler method to be called, in case `handler`
is a class. If not defined, the default behavior is to call the
handler method correspondent to the HTTP request method in lower
case (e.g., `get()`, `post()` etc).
:param methods:
A sequence of HTTP methods. If set, the route will only match if
the request method is allowed.
:param schemes:
A sequence of URI schemes, e.g., ``['http']`` or ``['https']``.
If set, the route will only match requests with these schemes.
"""
super(Route, self).__init__(template, handler=handler, name=name,
build_only=build_only)
self.defaults = defaults or {}
self.methods = methods
self.schemes = schemes
if isinstance(handler, basestring) and ':' in handler:
if handler_method:
raise ValueError(
"If handler_method is defined in a Route, handler "
"can't have a colon (got %r)." % handler)
else:
self.handler, self.handler_method = handler.rsplit(':', 1)
else:
self.handler_method = handler_method
@cached_property
def regex(self):
"""Lazy route template parser."""
regex, self.reverse_template, self.args_count, self.kwargs_count, \
self.variables = _parse_route_template(self.template,
default_sufix='[^/]+')
return regex
def match(self, request):
"""Matches this route against the current request.
:raises:
``exc.HTTPMethodNotAllowed`` if the route defines :attr:`methods`
and the request method isn't allowed.
.. seealso:: :meth:`BaseRoute.match`.
"""
match = self.regex.match(urllib.unquote(request.path))
if not match or self.schemes and request.scheme not in self.schemes:
return None
if self.methods and request.method not in self.methods:
# This will be caught by the router, so routes with different
# methods can be tried.
raise exc.HTTPMethodNotAllowed()
args, kwargs = _get_route_variables(match, self.defaults.copy())
return self, args, kwargs
def build(self, request, args, kwargs):
"""Returns a URI for this route.
.. seealso:: :meth:`Router.build`.
"""
scheme = kwargs.pop('_scheme', None)
netloc = kwargs.pop('_netloc', None)
anchor = kwargs.pop('_fragment', None)
full = kwargs.pop('_full', False) and not scheme and not netloc
if full or scheme or netloc:
netloc = netloc or request.host
scheme = scheme or request.scheme
path, query = self._build(args, kwargs)
return _urlunsplit(scheme, netloc, path, query, anchor)
def _build(self, args, kwargs):
"""Returns the URI path for this route.
:returns:
A tuple ``(path, kwargs)`` with the built URI path and extra
keywords to be used as URI query arguments.
"""
# Access self.regex just to set the lazy properties.
regex = self.regex
variables = self.variables
if self.args_count:
for index, value in enumerate(args):
key = '__%d__' % index
if key in variables:
kwargs[key] = value
values = {}
for name, regex in variables.iteritems():
value = kwargs.pop(name, self.defaults.get(name))
if value is None:
raise KeyError('Missing argument "%s" to build URI.' % \
name.strip('_'))
if not isinstance(value, basestring):
value = str(value)
if not regex.match(value):
raise ValueError('URI buiding error: Value "%s" is not '
'supported for argument "%s".' % (value, name.strip('_')))
values[name] = value
return (self.reverse_template % values, kwargs)
def __repr__(self):
return '<Route(%r, %r, name=%r, defaults=%r, build_only=%r)>' % \
(self.template, self.handler, self.name, self.defaults,
self.build_only)
class BaseHandlerAdapter(object):
"""A basic adapter to dispatch a handler.
This is used when the handler is a simple function: it just calls the
handler and returns the resulted response.
"""
#: The handler to be dispatched.
handler = None
def __init__(self, handler):
self.handler = handler
def __call__(self, request, response):
# The handler only receives *args if no named variables are set.
args, kwargs = request.route_args, request.route_kwargs
if kwargs:
args = ()
return self.handler(request, *args, **kwargs)
class WebappHandlerAdapter(BaseHandlerAdapter):
"""An adapter to dispatch a ``webapp.RequestHandler``.
Like in webapp, the handler is constructed, then ``initialize()`` is
called, then the method corresponding to the HTTP request method is called.
"""
def __call__(self, request, response):
handler = self.handler()
handler.initialize(request, response)
method_name = _normalize_handler_method(request.method)
method = getattr(handler, method_name, None)
if not method:
abort(501)
# The handler only receives *args if no named variables are set.
args, kwargs = request.route_args, request.route_kwargs
if kwargs:
args = ()
try:
method(*args, **kwargs)
except Exception, e:
handler.handle_exception(e, request.app.debug)
class Webapp2HandlerAdapter(BaseHandlerAdapter):
"""An adapter to dispatch a ``webapp2.RequestHandler``.
The handler is constructed then ``dispatch()`` is called.
"""
def __call__(self, request, response):
handler = self.handler(request, response)
return handler.dispatch()
class Router(object):
"""A URI router used to match, dispatch and build URIs."""
#: Class used when the route is set as a tuple.
route_class = SimpleRoute
#: All routes that can be matched.
match_routes = None
#: All routes that can be built.
build_routes = None
#: Handler classes imported lazily.
handlers = None
def __init__(self, routes=None):
"""Initializes the router.
:param routes:
A sequence of :class:`Route` instances or, for simple routes,
tuples ``(regex, handler)``.
"""
self.match_routes = []
self.build_routes = {}
self.handlers = {}
if routes:
for route in routes:
self.add(route)
def add(self, route):
"""Adds a route to this router.
:param route:
A :class:`Route` instance or, for simple routes, a tuple
``(regex, handler)``.
"""
if isinstance(route, tuple):
# Exceptional case: simple routes defined as a tuple.
route = self.route_class(*route)
for r in route.get_match_routes():
self.match_routes.append(r)
for name, r in route.get_build_routes():
self.build_routes[name] = r
def set_matcher(self, func):
"""Sets the function called to match URIs.
:param func:
A function that receives ``(router, request)`` and returns
a tuple ``(route, args, kwargs)`` if any route matches, or
raise ``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
"""
# Functions are descriptors, so bind it to this instance with __get__.
self.match = func.__get__(self, self.__class__)
def set_builder(self, func):
"""Sets the function called to build URIs.
:param func:
A function that receives ``(router, request, name, args, kwargs)``
and returns a URI.
"""
self.build = func.__get__(self, self.__class__)
def set_dispatcher(self, func):
"""Sets the function called to dispatch the handler.
:param func:
A function that receives ``(router, request, response)``
and returns the value returned by the dispatched handler.
"""
self.dispatch = func.__get__(self, self.__class__)
def set_adapter(self, func):
"""Sets the function that adapts loaded handlers for dispatching.
:param func:
A function that receives ``(router, handler)`` and returns a
handler callable.
"""
self.adapt = func.__get__(self, self.__class__)
def default_matcher(self, request):
"""Matches all routes against a request object.
The first one that matches is returned.
:param request:
A :class:`Request` instance.
:returns:
A tuple ``(route, args, kwargs)`` if a route matched, or None.
:raises:
``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
"""
method_not_allowed = False
for route in self.match_routes:
try:
match = route.match(request)
if match:
return match
except exc.HTTPMethodNotAllowed:
method_not_allowed = True
if method_not_allowed:
raise exc.HTTPMethodNotAllowed()
raise exc.HTTPNotFound()
def default_builder(self, request, name, args, kwargs):
"""Returns a URI for a named :class:`Route`.
:param request:
The current :class:`Request` object.
:param name:
The route name.
:param args:
Tuple of positional arguments to build the URI. All positional
variables defined in the route must be passed and must conform
to the format set in the route. Extra arguments are ignored.
:param kwargs:
Dictionary of keyword arguments to build the URI. All variables
not set in the route default values must be passed and must
conform to the format set in the route. Extra keywords are
appended as a query string.
A few keywords have special meaning:
- **_full**: If True, builds an absolute URI.
- **_scheme**: URI scheme, e.g., `http` or `https`. If defined,
an absolute URI is always returned.
- **_netloc**: Network location, e.g., `www.google.com`. If
defined, an absolute URI is always returned.
- **_fragment**: If set, appends a fragment (or "anchor") to the
generated URI.
:returns:
An absolute or relative URI.
"""
route = self.build_routes.get(name)
if route is None:
raise KeyError('Route named %r is not defined.' % name)
return route.build(request, args, kwargs)
def default_dispatcher(self, request, response):
"""Dispatches a handler.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
:raises:
``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
:returns:
The returned value from the handler.
"""
route, args, kwargs = rv = self.match(request)
request.route, request.route_args, request.route_kwargs = rv
if route.handler_adapter is None:
handler = route.handler
if isinstance(handler, basestring):
if handler not in self.handlers:
self.handlers[handler] = handler = import_string(handler)
else:
handler = self.handlers[handler]
route.handler_adapter = self.adapt(handler)
return route.handler_adapter(request, response)
def default_adapter(self, handler):
"""Adapts a handler for dispatching.
Because handlers use or implement different dispatching mechanisms,
they can be wrapped to use a unified API for dispatching.
This way webapp2 can support, for example, a :class:`RequestHandler`
class and function views or, for compatibility purposes, a
``webapp.RequestHandler`` class. The adapters follow the same router
dispatching API but dispatch each handler type differently.
:param handler:
A handler callable.
:returns:
A wrapped handler callable.
"""
if inspect.isclass(handler):
if _webapp and issubclass(handler, _webapp.RequestHandler):
# Compatible with webapp.RequestHandler.
adapter = WebappHandlerAdapter
else:
# Default, compatible with webapp2.RequestHandler.
adapter = Webapp2HandlerAdapter
else:
# A "view" function.
adapter = BaseHandlerAdapter
return adapter(handler)
def __repr__(self):
routes = self.match_routes + [v for k, v in \
self.build_routes.iteritems() if v not in self.match_routes]
return '<Router(%r)>' % routes
# Default matcher, builder, dispatcher and adapter.
match = default_matcher
build = default_builder
dispatch = default_dispatcher
adapt = default_adapter
class Config(dict):
"""A simple configuration dictionary for the :class:`WSGIApplication`."""
#: Loaded configurations.
loaded = None
def __init__(self, defaults=None):
dict.__init__(self, defaults or ())
self.loaded = []
def load_config(self, key, default_values=None, user_values=None,
required_keys=None):
"""Returns a configuration for a given key.
This can be used by objects that define a default configuration. It
will update the app configuration with the default values the first
time it is requested, and mark the key as loaded.
:param key:
A configuration key.
:param default_values:
Default values defined by a module or class.
:param user_values:
User values, used when an object can be initialized with
configuration. This overrides the app configuration.
:param required_keys:
Keys that can not be None.
:raises:
Exception, when a required key is not set or is None.
"""
if key in self.loaded:
config = self[key]
else:
config = dict(default_values or ())
if key in self:
config.update(self[key])
self[key] = config
self.loaded.append(key)
if required_keys and not user_values:
self._validate_required(key, config, required_keys)
if user_values:
config = config.copy()
config.update(user_values)
if required_keys:
self._validate_required(key, config, required_keys)
return config
def _validate_required(self, key, config, required_keys):
missing = [k for k in required_keys if config.get(k) is None]
if missing:
raise Exception(
'Missing configuration keys for %r: %r.' % (key, missing))
class RequestContext(object):
"""Context for a single request.
The context is responsible for setting and cleaning global variables for
a request.
"""
#: A :class:`WSGIApplication` instance.
app = None
#: WSGI environment dictionary.
environ = None
def __init__(self, app, environ):
"""Initializes the request context.
:param app:
An :class:`WSGIApplication` instance.
:param environ:
A WSGI environment dictionary.
"""
self.app = app
self.environ = environ
def __enter__(self):
"""Enters the request context.
:returns:
A tuple ``(request, response)``.
"""
# Build request and response.
request = self.app.request_class(self.environ)
response = self.app.response_class()
# Make active app and response available through the request object.
request.app = self.app
request.response = response
# Register global variables.
self.app.set_globals(app=self.app, request=request)
return request, response
def __exit__(self, exc_type, exc_value, traceback):
"""Exits the request context.
This release the context locals except if an exception is caught
in debug mode. In this case they are kept to be inspected.
"""
if exc_type is None or not self.app.debug:
# Unregister global variables.
self.app.clear_globals()
class WSGIApplication(object):
"""A WSGI-compliant application."""
#: Allowed request methods.
allowed_methods = frozenset(('GET', 'POST', 'HEAD', 'OPTIONS', 'PUT',
'DELETE', 'TRACE'))
#: Class used for the request object.
request_class = Request
#: Class used for the response object.
response_class = Response
#: Class used for the router object.
router_class = Router
#: Class used for the request context object.
request_context_class = RequestContext
#: Class used for the configuration object.
config_class = Config
#: A general purpose flag to indicate development mode: if True, uncaught
#: exceptions are raised instead of using ``HTTPInternalServerError``.
debug = False
#: A :class:`Router` instance with all URIs registered for the application.
router = None
#: A :class:`Config` instance with the application configuration.
config = None
#: A dictionary to register objects used during the app lifetime.
registry = None
#: A dictionary mapping HTTP error codes to callables to handle those
#: HTTP exceptions. See :meth:`handle_exception`.
error_handlers = None
#: Active :class:`WSGIApplication` instance. See :meth:`set_globals`.
app = None
#: Active :class:`Request` instance. See :meth:`set_globals`.
request = None
#: Same as :attr:`app`, for webapp compatibility. See :meth:`set_globals`.
active_instance = None
def __init__(self, routes=None, debug=False, config=None):
"""Initializes the WSGI application.
:param routes:
A sequence of :class:`Route` instances or, for simple routes,
tuples ``(regex, handler)``.
:param debug:
True to enable debug mode, False otherwise.
:param config:
A configuration dictionary for the application.
"""
self.debug = debug
self.registry = {}
self.error_handlers = {}
self.config = self.config_class(config)
self.router = self.router_class(routes)
def set_globals(self, app=None, request=None):
"""Registers the global variables for app and request.
If :mod:`webapp2_extras.local` is available the app and request
class attributes are assigned to a proxy object that returns them
using thread-local, making the application thread-safe. This can also
be used in environments that don't support threading.
If :mod:`webapp2_extras.local` is not available app and request will
be assigned directly as class attributes. This should only be used in
non-threaded environments (e.g., App Engine Python 2.5).
:param app:
A :class:`WSGIApplication` instance.
:param request:
A :class:`Request` instance.
"""
if _local is not None: # pragma: no cover
_local.app = app
_local.request = request
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = app
WSGIApplication.request = request
def clear_globals(self):
"""Clears global variables. See :meth:`set_globals`."""
if _local is not None: # pragma: no cover
_local.__release_local__()
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = None
WSGIApplication.request = None
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in.
:param environ:
A WSGI environment.
:param start_response:
A callable accepting a status code, a list of headers and an
optional exception context to start the response.
:returns:
An iterable with the response to return to the client.
"""
with self.request_context_class(self, environ) as (request, response):
try:
if request.method not in self.allowed_methods:
# 501 Not Implemented.
raise exc.HTTPNotImplemented()
rv = self.router.dispatch(request, response)
if rv is not None:
response = rv
except Exception, e:
try:
# Try to handle it with a custom error handler.
rv = self.handle_exception(request, response, e)
if rv is not None:
response = rv
except HTTPException, e:
# Use the HTTP exception as response.
response = e
except Exception, e:
# Error wasn't handled so we have nothing else to do.
response = self._internal_error(e)
try:
return response(environ, start_response)
except Exception, e:
return self._internal_error(e)(environ, start_response)
def _internal_error(self, exception):
"""Last resource error for :meth:`__call__`."""
logging.exception(exception)
if self.debug:
lines = ''.join(traceback.format_exception(*sys.exc_info()))
html = _debug_template % (cgi.escape(lines, quote=True))
return Response(body=html, status=500)
return exc.HTTPInternalServerError()
def handle_exception(self, request, response, e):
"""Handles a uncaught exception occurred in :meth:`__call__`.
Uncaught exceptions can be handled by error handlers registered in
:attr:`error_handlers`. This is a dictionary that maps HTTP status
codes to callables that will handle the corresponding error code.
If the exception is not an ``HTTPException``, the status code 500
is used.
The error handlers receive (request, response, exception) and can be
a callable or a string in dotted notation to be lazily imported.
If no error handler is found, the exception is re-raised.
Based on idea from `Flask`_.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
:param e:
The uncaught exception.
:returns:
The returned value from the error handler.
"""
if isinstance(e, HTTPException):
code = e.code
else:
code = 500
handler = self.error_handlers.get(code)
if handler:
if isinstance(handler, basestring):
self.error_handlers[code] = handler = import_string(handler)
return handler(request, response, e)
else:
# Re-raise it to be caught by the WSGI app.
raise
def run(self, bare=False):
"""Runs this WSGI-compliant application in a CGI environment.
This uses functions provided by ``google.appengine.ext.webapp.util``,
if available: ``run_bare_wsgi_app`` and ``run_wsgi_app``.
Otherwise, it uses ``wsgiref.handlers.CGIHandler().run()``.
:param bare:
If True, doesn't add registered WSGI middleware: use
``run_bare_wsgi_app`` instead of ``run_wsgi_app``.
"""
if _webapp_util:
if bare:
_webapp_util.run_bare_wsgi_app(self)
else:
_webapp_util.run_wsgi_app(self)
else: # pragma: no cover
handlers.CGIHandler().run(self)
def get_response(self, *args, **kwargs):
"""Creates a request and returns a response for this app.
This is a convenience for unit testing purposes. It receives
parameters to build a request and calls the application, returning
the resulting response::
class HelloHandler(webapp2.RequestHandler):
def get(self):
self.response.write('Hello, world!')
app = webapp2.WSGIapplication([('/', HelloHandler)])
# Test the app, passing parameters to build a request.
response = app.get_response('/')
assert response.status_int == 200
assert response.body == 'Hello, world!'
:param args:
Positional arguments to be passed to ``Request.blank()``.
:param kwargs:
Keyword arguments to be passed to ``Request.blank()``.
:returns:
A :class:`Response` object.
"""
return self.request_class.blank(*args, **kwargs).get_response(self)
_import_string_error = """\
import_string() failed for %r. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Original exception:
%s: %s
Debugged import:
%s"""
class ImportStringError(Exception):
"""Provides information about a failed :func:`import_string` attempt."""
#: String in dotted notation that failed to be imported.
import_name = None
#: Wrapped exception.
exception = None
def __init__(self, import_name, exception):
self.import_name = import_name
self.exception = exception
msg = _import_string_error
name = ''
tracked = []
for part in import_name.split('.'):
name += (name and '.') + part
imported = import_string(name, silent=True)
if imported:
tracked.append((name, imported.__file__))
else:
track = ['- %r found in %r.' % rv for rv in tracked]
track.append('- %r not found.' % name)
msg = msg % (import_name, exception.__class__.__name__,
str(exception), '\n'.join(track))
break
Exception.__init__(self, msg)
_get_app_error = 'WSGIApplication global variable is not set.'
_get_request_error = 'Request global variable is not set.'
def get_app():
"""Returns the active app instance.
:returns:
A :class:`WSGIApplication` instance.
"""
if _local:
assert getattr(_local, 'app', None) is not None, _get_app_error
else:
assert WSGIApplication.app is not None, _get_app_error
return WSGIApplication.app
def get_request():
"""Returns the active request instance.
:returns:
A :class:`Request` instance.
"""
if _local:
assert getattr(_local, 'request', None) is not None, _get_request_error
else:
assert WSGIApplication.request is not None, _get_request_error
return WSGIApplication.request
def uri_for(_name, _request=None, *args, **kwargs):
"""A standalone uri_for version that can be passed to templates.
.. seealso:: :meth:`Router.build`.
"""
request = _request or get_request()
return request.app.router.build(request, _name, args, kwargs)
def redirect(uri, permanent=False, abort=False, code=None, body=None,
request=None, response=None):
"""Issues an HTTP redirect to the given relative URI.
This won't stop code execution unless **abort** is True. A common
practice is to return when calling this method::
return redirect('/some-path')
:param uri:
A relative or absolute URI (e.g., ``'../flowers.html'``).
:param permanent:
If True, uses a 301 redirect instead of a 302 redirect.
:param abort:
If True, raises an exception to perform the redirect.
:param code:
The redirect status code. Supported codes are 301, 302, 303, 305,
and 307. 300 is not supported because it's not a real redirect
and 304 because it's the answer for a request with defined
``If-Modified-Since`` headers.
:param body:
Response body, if any.
:param request:
Optional request object. If not set, uses :func:`get_request`.
:param response:
Optional response object. If not set, a new response is created.
:returns:
A :class:`Response` instance.
"""
if uri.startswith(('.', '/')):
request = request or get_request()
uri = str(urlparse.urljoin(request.url, uri))
if code is None:
if permanent:
code = 301
else:
code = 302
assert code in (301, 302, 303, 305, 307), \
'Invalid redirect status code.'
if abort:
_abort(code, headers=[('Location', uri)])
if response is None:
request = request or get_request()
response = request.app.response_class()
else:
response.clear()
response.headers['Location'] = uri
response.status = code
if body is not None:
response.write(body)
return response
def redirect_to(_name, _permanent=False, _abort=False, _code=None,
_body=None, _request=None, _response=None, *args, **kwargs):
"""Convenience function mixing :func:`redirect` and :func:`uri_for`.
Issues an HTTP redirect to a named URI built using :func:`uri_for`.
:param _name:
The route name to redirect to.
:param args:
Positional arguments to build the URI.
:param kwargs:
Keyword arguments to build the URI.
:returns:
A :class:`Response` instance.
The other arguments are described in :func:`redirect`.
"""
uri = uri_for(_name, _request=_request, *args, **kwargs)
return redirect(uri, permanent=_permanent, abort=_abort, code=_code,
body=_body, request=_request, response=_response)
def abort(code, *args, **kwargs):
"""Raises an ``HTTPException``.
:param code:
An integer that represents a valid HTTP status code.
:param args:
Positional arguments to instantiate the exception.
:param kwargs:
Keyword arguments to instantiate the exception.
"""
cls = exc.status_map.get(code)
if not cls:
raise KeyError('No exception is defined for code %r.' % code)
raise cls(*args, **kwargs)
def import_string(import_name, silent=False):
"""Imports an object based on a string in dotted notation.
Simplified version of the function with same name from `Werkzeug`_.
:param import_name:
String in dotted notation of the object to be imported.
:param silent:
If True, import or attribute errors are ignored and None is returned
instead of raising an exception.
:returns:
The imported object.
"""
import_name = _to_utf8(import_name)
try:
if '.' in import_name:
module, obj = import_name.rsplit('.', 1)
return getattr(__import__(module, None, None, [obj]), obj)
else:
return __import__(import_name)
except (ImportError, AttributeError), e:
if not silent:
raise ImportStringError(import_name, e), None, sys.exc_info()[2]
def _urlunsplit(scheme=None, netloc=None, path=None, query=None,
fragment=None):
"""Like ``urlparse.urlunsplit``, but will escape values and urlencode and
sort query arguments.
:param scheme:
URI scheme, e.g., `http` or `https`.
:param netloc:
Network location, e.g., `localhost:8080` or `www.google.com`.
:param path:
URI path.
:param query:
URI query as an escaped string, or a dictionary or list of key-values
tuples to build a query.
:param fragment:
Fragment identifier, also known as "anchor".
:returns:
An assembled absolute or relative URI.
"""
if not scheme or not netloc:
scheme = None
netloc = None
if path:
path = urllib.quote(_to_utf8(path))
if query and not isinstance(query, basestring):
if isinstance(query, dict):
query = query.iteritems()
# Sort args: commonly needed to build signatures for services.
query = urllib.urlencode(sorted(query))
if fragment:
fragment = urllib.quote(_to_utf8(fragment))
return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
def _get_handler_methods(handler):
"""Returns a list of HTTP methods supported by a handler.
:param handler:
A :class:`RequestHandler` instance.
:returns:
A list of HTTP methods supported by the handler.
"""
methods = []
for method in get_app().allowed_methods:
if getattr(handler, _normalize_handler_method(method), None):
methods.append(method)
return methods
def _normalize_handler_method(method):
"""Transforms an HTTP method into a valid Python identifier."""
return method.lower().replace('-', '_')
def _to_utf8(value):
"""Encodes a unicode value to UTF-8 if not yet encoded."""
if isinstance(value, str):
return value
return value.encode('utf-8')
def _parse_route_template(template, default_sufix=''):
"""Lazy route template parser."""
variables = {}
reverse_template = pattern = ''
args_count = last = 0
for match in _route_re.finditer(template):
part = template[last:match.start()]
name = match.group(1)
expr = match.group(2) or default_sufix
last = match.end()
if not name:
name = '__%d__' % args_count
args_count += 1
pattern += '%s(?P<%s>%s)' % (re.escape(part), name, expr)
reverse_template += '%s%%(%s)s' % (part, name)
variables[name] = re.compile('^%s$' % expr)
part = template[last:]
kwargs_count = len(variables) - args_count
reverse_template += part
regex = re.compile('^%s%s$' % (pattern, re.escape(part)))
return regex, reverse_template, args_count, kwargs_count, variables
def _get_route_variables(match, default_kwargs=None):
"""Returns (args, kwargs) for a route match."""
kwargs = default_kwargs or {}
kwargs.update(match.groupdict())
if kwargs:
args = tuple(value[1] for value in sorted(
(int(key[2:-2]), kwargs.pop(key)) for key in kwargs.keys() \
if key.startswith('__') and key.endswith('__')))
else:
args = ()
return args, kwargs
def _set_thread_safe_app():
"""Assigns WSGIApplication globals to a proxy pointing to thread-local."""
if _local is not None: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = _local('app')
WSGIApplication.request = _local('request')
Request.ResponseClass = Response
Response.RequestClass = Request
# Alias.
_abort = abort
# Thread-safety support.
_set_thread_safe_app()
# Defer importing google.appengine.ext.webapp.util until every public symbol
# has been defined since google.appengine.ext.webapp in App Engine Python 2.7
# runtime imports this module to provide its public interface.
try:
from google.appengine.ext.webapp import util as _webapp_util
except ImportError: # pragma: no cover
pass
| Python |
from jinja2 import nodes
from jinja2.ext import Extension
class FragmentCacheExtension(Extension):
# a set of names that trigger the extension.
tags = set(['cache'])
def __init__(self, environment):
super(FragmentCacheExtension, self).__init__(environment)
# add the defaults to the environment
environment.extend(
fragment_cache_prefix='',
fragment_cache=None
)
def parse(self, parser):
# the first token is the token that started the tag. In our case
# we only listen to ``'cache'`` so this will be a name token with
# `cache` as value. We get the line number so that we can give
# that line number to the nodes we create by hand.
lineno = parser.stream.next().lineno
# now we parse a single expression that is used as cache key.
args = [parser.parse_expression()]
# if there is a comma, the user provided a timeout. If not use
# None as second parameter.
if parser.stream.skip_if('comma'):
args.append(parser.parse_expression())
else:
args.append(nodes.Const(None))
# now we parse the body of the cache block up to `endcache` and
# drop the needle (which would always be `endcache` in that case)
body = parser.parse_statements(['name:endcache'], drop_needle=True)
# now return a `CallBlock` node that calls our _cache_support
# helper method on this extension.
return nodes.CallBlock(self.call_method('_cache_support', args),
[], [], body).set_lineno(lineno)
def _cache_support(self, name, timeout, caller):
"""Helper callback."""
key = self.environment.fragment_cache_prefix + name
# try to load the block from the cache
# if there is no fragment in the cache, render it and store
# it in the cache.
rv = self.environment.fragment_cache.get(key)
if rv is not None:
return rv
rv = caller()
self.environment.fragment_cache.add(key, rv, timeout)
return rv
| Python |
# -*- coding: utf-8 -*-
"""
Jinja Documentation Extensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for automatically documenting filters and tests.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
import os
import re
import inspect
import jinja2
from itertools import islice
from types import BuiltinFunctionType
from docutils import nodes
from docutils.statemachine import ViewList
from sphinx.ext.autodoc import prepare_docstring
from sphinx.application import TemplateBridge
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
from jinja2 import Environment, FileSystemLoader
def parse_rst(state, content_offset, doc):
node = nodes.section()
# hack around title style bookkeeping
surrounding_title_styles = state.memo.title_styles
surrounding_section_level = state.memo.section_level
state.memo.title_styles = []
state.memo.section_level = 0
state.nested_parse(doc, content_offset, node, match_titles=1)
state.memo.title_styles = surrounding_title_styles
state.memo.section_level = surrounding_section_level
return node.children
class JinjaStyle(Style):
title = 'Jinja Style'
default_style = ""
styles = {
Comment: 'italic #aaaaaa',
Comment.Preproc: 'noitalic #B11414',
Comment.Special: 'italic #505050',
Keyword: 'bold #B80000',
Keyword.Type: '#808080',
Operator.Word: 'bold #B80000',
Name.Builtin: '#333333',
Name.Function: '#333333',
Name.Class: 'bold #333333',
Name.Namespace: 'bold #333333',
Name.Entity: 'bold #363636',
Name.Attribute: '#686868',
Name.Tag: 'bold #686868',
Name.Decorator: '#686868',
String: '#AA891C',
Number: '#444444',
Generic.Heading: 'bold #000080',
Generic.Subheading: 'bold #800080',
Generic.Deleted: '#aa0000',
Generic.Inserted: '#00aa00',
Generic.Error: '#aa0000',
Generic.Emph: 'italic',
Generic.Strong: 'bold',
Generic.Prompt: '#555555',
Generic.Output: '#888888',
Generic.Traceback: '#aa0000',
Error: '#F00 bg:#FAA'
}
_sig_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*(\(.*?\))')
def format_function(name, aliases, func):
lines = inspect.getdoc(func).splitlines()
signature = '()'
if isinstance(func, BuiltinFunctionType):
match = _sig_re.match(lines[0])
if match is not None:
del lines[:1 + bool(lines and not lines[0])]
signature = match.group(1)
else:
try:
argspec = inspect.getargspec(func)
if getattr(func, 'environmentfilter', False) or \
getattr(func, 'contextfilter', False) or \
getattr(func, 'evalcontextfilter', False):
del argspec[0][0]
signature = inspect.formatargspec(*argspec)
except:
pass
result = ['.. function:: %s%s' % (name, signature), '']
result.extend(' ' + line for line in lines)
if aliases:
result.extend(('', ' :aliases: %s' % ', '.join(
'``%s``' % x for x in sorted(aliases))))
return result
def dump_functions(mapping):
def directive(dirname, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
reverse_mapping = {}
for name, func in mapping.iteritems():
reverse_mapping.setdefault(func, []).append(name)
filters = []
for func, names in reverse_mapping.iteritems():
aliases = sorted(names, key=lambda x: len(x))
name = aliases.pop()
filters.append((name, aliases, func))
filters.sort()
result = ViewList()
for name, aliases, func in filters:
for item in format_function(name, aliases, func):
result.append(item, '<jinjaext>')
node = nodes.paragraph()
state.nested_parse(result, content_offset, node)
return node.children
return directive
from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS
jinja_filters = dump_functions(DEFAULT_FILTERS)
jinja_tests = dump_functions(DEFAULT_TESTS)
def jinja_nodes(dirname, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
from jinja2.nodes import Node
doc = ViewList()
def walk(node, indent):
p = ' ' * indent
sig = ', '.join(node.fields)
doc.append(p + '.. autoclass:: %s(%s)' % (node.__name__, sig), '')
if node.abstract:
members = []
for key, name in node.__dict__.iteritems():
if not key.startswith('_') and \
not hasattr(node.__base__, key) and callable(name):
members.append(key)
if members:
members.sort()
doc.append('%s :members: %s' % (p, ', '.join(members)), '')
if node.__base__ != object:
doc.append('', '')
doc.append('%s :Node type: :class:`%s`' %
(p, node.__base__.__name__), '')
doc.append('', '')
children = node.__subclasses__()
children.sort(key=lambda x: x.__name__.lower())
for child in children:
walk(child, indent)
walk(Node, 0)
return parse_rst(state, content_offset, doc)
def inject_toc(app, doctree, docname):
titleiter = iter(doctree.traverse(nodes.title))
try:
# skip first title, we are not interested in that one
titleiter.next()
title = titleiter.next()
# and check if there is at least another title
titleiter.next()
except StopIteration:
return
tocnode = nodes.section('')
tocnode['classes'].append('toc')
toctitle = nodes.section('')
toctitle['classes'].append('toctitle')
toctitle.append(nodes.title(text='Table Of Contents'))
tocnode.append(toctitle)
tocnode += doctree.document.settings.env.get_toc_for(docname)[0][1]
title.parent.insert(title.parent.children.index(title), tocnode)
def setup(app):
app.add_directive('jinjafilters', jinja_filters, 0, (0, 0, 0))
app.add_directive('jinjatests', jinja_tests, 0, (0, 0, 0))
app.add_directive('jinjanodes', jinja_nodes, 0, (0, 0, 0))
# uncomment for inline toc. links are broken unfortunately
##app.connect('doctree-resolved', inject_toc)
| Python |
# -*- coding: utf-8 -*-
#
# Jinja2 documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 27 21:42:41 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys, os
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'jinjaext']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'Jinja2'
copyright = '2008, Armin Ronacher'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
import pkg_resources
try:
release = pkg_resources.get_distribution('Jinja2').version
except ImportError:
print 'To build the documentation, The distribution information of Jinja2'
print 'Has to be available. Either install the package into your'
print 'development environment or run "setup.py develop" to setup the'
print 'metadata. A virtualenv is recommended!'
sys.exit(1)
if 'dev' in release:
release = release.split('dev')[0] + 'dev'
version = '.'.join(release.split('.')[:2])
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'jinjaext.JinjaStyle'
# Options for HTML output
# -----------------------
html_theme = 'jinja'
html_theme_path = ['_themes']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# no modindex
html_use_modindex = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.
#html_use_opensearch = False
# Output file base name for HTML help builder.
htmlhelp_basename = 'Jinja2doc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
('latexindex', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher',
'manual'),
]
# Additional stuff for LaTeX
latex_elements = {
'fontpkg': r'\usepackage{mathpazo}',
'papersize': 'a4paper',
'pointsize': '12pt',
'preamble': r'''
\usepackage{jinjastyle}
% i hate you latex
\DeclareUnicodeCharacter{14D}{o}
'''
}
latex_use_parts = True
latex_additional_files = ['jinjastyle.sty', 'logo.pdf']
# If false, no module index is generated.
latex_use_modindex = False
html_sidebars = {
'index': ['sidebarlogo.html', 'sidebarintro.html', 'sourcelink.html',
'searchbox.html'],
'**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',
'sourcelink.html', 'searchbox.html']
}
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from itertools import chain, imap
from jinja2.nodes import EvalContext, _context_function_types
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, internalcode, next, object_type_repr
from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
TemplateNotFound
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join', 'to_string', 'identity',
'TemplateNotFound']
#: the name of the function that is used to convert something into
#: a string. 2to3 will adopt that automatically and the generated
#: code can take advantage of it.
to_string = unicode
#: the identity function. Useful for certain things in the environment
identity = lambda x: x
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode."""
buf = []
iterator = imap(soft_unicode, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, '__html__'):
return Markup(u'').join(chain(buf, iterator))
return concat(buf)
def unicode_join(seq):
"""Simple args to unicode conversion and concatenation."""
return concat(imap(unicode, seq))
def new_context(environment, template_name, blocks, vars=None,
shared=None, globals=None, locals=None):
"""Internal helper to for context creation."""
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or (), **vars)
if locals:
# if the parent is shared a copy should be created because
# we don't want to modify the dict passed
if shared:
parent = dict(parent)
for key, value in locals.iteritems():
if key[:2] == 'l_' and value is not missing:
parent[key[2:]] = value
return Context(environment, parent, template_name, blocks)
class TemplateReference(object):
"""The `self` in templates."""
def __init__(self, context):
self.__context = context
def __getitem__(self, name):
blocks = self.__context.blocks[name]
return BlockReference(name, self.__context, blocks, 0)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self.__context.name
)
class Context(object):
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`contextfunction`\s get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
__slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',
'name', 'blocks', '__weakref__')
def __init__(self, environment, parent, name, blocks):
self.parent = parent
self.vars = {}
self.environment = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars = set()
self.name = name
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index)
def get(self, key, default=None):
"""Returns an item from the template context, if it doesn't exist
`default` is returned.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key):
"""Looks up a variable like `__getitem__` or `get` but returns an
:class:`Undefined` object with the name of the name looked up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return self.environment.undefined(name=key)
def get_exported(self):
"""Get a new dict with the exported variables."""
return dict((k, self.vars[k]) for k in self.exported_vars)
def get_all(self):
"""Return a copy of the complete context as dict including the
exported variables.
"""
return dict(self.parent, **self.vars)
@internalcode
def call(__self, __obj, *args, **kwargs):
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
"""
if __debug__:
__traceback_hide__ = True
if isinstance(__obj, _context_function_types):
if getattr(__obj, 'contextfunction', 0):
args = (__self,) + args
elif getattr(__obj, 'evalcontextfunction', 0):
args = (__self.eval_ctx,) + args
elif getattr(__obj, 'environmentfunction', 0):
args = (__self.environment,) + args
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined('value was undefined because '
'a callable raised a '
'StopIteration exception')
def derived(self, locals=None):
"""Internal helper function to create a derived context."""
context = new_context(self.environment, self.name, {},
self.parent, True, None, locals)
context.vars.update(self.vars)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())
return context
def _all(meth):
proxy = lambda self: getattr(self.get_all(), meth)()
proxy.__doc__ = getattr(dict, meth).__doc__
proxy.__name__ = meth
return proxy
keys = _all('keys')
values = _all('values')
items = _all('items')
# not available on python 3
if hasattr(dict, 'iterkeys'):
iterkeys = _all('iterkeys')
itervalues = _all('itervalues')
iteritems = _all('iteritems')
del _all
def __contains__(self, name):
return name in self.vars or name in self.parent
def __getitem__(self, key):
"""Lookup a variable or raise `KeyError` if the variable is
undefined.
"""
item = self.resolve(key)
if isinstance(item, Undefined):
raise KeyError(key)
return item
def __repr__(self):
return '<%s %s of %r>' % (
self.__class__.__name__,
repr(self.get_all()),
self.name
)
# register the context as mapping if possible
try:
from collections import Mapping
Mapping.register(Context)
except ImportError:
pass
class BlockReference(object):
"""One block on a template reference."""
def __init__(self, name, context, stack, depth):
self.name = name
self._context = context
self._stack = stack
self._depth = depth
@property
def super(self):
"""Super the block."""
if self._depth + 1 >= len(self._stack):
return self._context.environment. \
undefined('there is no parent block called %r.' %
self.name, name='super')
return BlockReference(self.name, self._context, self._stack,
self._depth + 1)
@internalcode
def __call__(self):
rv = concat(self._stack[self._depth](self._context))
if self._context.eval_ctx.autoescape:
rv = Markup(rv)
return rv
class LoopContext(object):
"""A loop context for dynamic iteration."""
def __init__(self, iterable, recurse=None):
self._iterator = iter(iterable)
self._recurse = recurse
self.index0 = -1
# try to get the length of the iterable early. This must be done
# here because there are some broken iterators around where there
# __len__ is the number of iterations left (i'm looking at your
# listreverseiterator!).
try:
self._length = len(iterable)
except (TypeError, AttributeError):
self._length = None
def cycle(self, *args):
"""Cycles among the arguments with the current loop index."""
if not args:
raise TypeError('no items for cycling given')
return args[self.index0 % len(args)]
first = property(lambda x: x.index0 == 0)
last = property(lambda x: x.index0 + 1 == x.length)
index = property(lambda x: x.index0 + 1)
revindex = property(lambda x: x.length - x.index0)
revindex0 = property(lambda x: x.length - x.index)
def __len__(self):
return self.length
def __iter__(self):
return LoopContextIterator(self)
@internalcode
def loop(self, iterable):
if self._recurse is None:
raise TypeError('Tried to call non recursive loop. Maybe you '
"forgot the 'recursive' modifier.")
return self._recurse(iterable, self._recurse)
# a nifty trick to enhance the error message if someone tried to call
# the the loop without or with too many arguments.
__call__ = loop
del loop
@property
def length(self):
if self._length is None:
# if was not possible to get the length of the iterator when
# the loop context was created (ie: iterating over a generator)
# we have to convert the iterable into a sequence and use the
# length of that.
iterable = tuple(self._iterator)
self._iterator = iter(iterable)
self._length = len(iterable) + self.index0 + 1
return self._length
def __repr__(self):
return '<%s %r/%r>' % (
self.__class__.__name__,
self.index,
self.length
)
class LoopContextIterator(object):
"""The iterator for a loop context."""
__slots__ = ('context',)
def __init__(self, context):
self.context = context
def __iter__(self):
return self
def next(self):
ctx = self.context
ctx.index0 += 1
return next(ctx._iterator), ctx
class Macro(object):
"""Wraps a macro function."""
def __init__(self, environment, func, name, arguments, defaults,
catch_kwargs, catch_varargs, caller):
self._environment = environment
self._func = func
self._argument_count = len(arguments)
self.name = name
self.arguments = arguments
self.defaults = defaults
self.catch_kwargs = catch_kwargs
self.catch_varargs = catch_varargs
self.caller = caller
@internalcode
def __call__(self, *args, **kwargs):
# try to consume the positional arguments
arguments = list(args[:self._argument_count])
off = len(arguments)
# if the number of arguments consumed is not the number of
# arguments expected we start filling in keyword arguments
# and defaults.
if off != self._argument_count:
for idx, name in enumerate(self.arguments[len(arguments):]):
try:
value = kwargs.pop(name)
except KeyError:
try:
value = self.defaults[idx - self._argument_count + off]
except IndexError:
value = self._environment.undefined(
'parameter %r was not provided' % name, name=name)
arguments.append(value)
# it's important that the order of these arguments does not change
# if not also changed in the compiler's `function_scoping` method.
# the order is caller, keyword arguments, positional arguments!
if self.caller:
caller = kwargs.pop('caller', None)
if caller is None:
caller = self._environment.undefined('No caller defined',
name='caller')
arguments.append(caller)
if self.catch_kwargs:
arguments.append(kwargs)
elif kwargs:
raise TypeError('macro %r takes no keyword argument %r' %
(self.name, next(iter(kwargs))))
if self.catch_varargs:
arguments.append(args[self._argument_count:])
elif len(args) > self._argument_count:
raise TypeError('macro %r takes not more than %d argument(s)' %
(self.name, len(self.arguments)))
return self._func(*arguments)
def __repr__(self):
return '<%s %s>' % (
self.__class__.__name__,
self.name is None and 'anonymous' or repr(self.name)
)
class Undefined(object):
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
'_undefined_exception')
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
@internalcode
def _fail_with_undefined_error(self, *args, **kwargs):
"""Regular callback function for undefined objects that raises an
`UndefinedError` on call.
"""
if self._undefined_hint is None:
if self._undefined_obj is missing:
hint = '%r is undefined' % self._undefined_name
elif not isinstance(self._undefined_name, basestring):
hint = '%s has no element %r' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
else:
hint = '%r has no attribute %r' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
else:
hint = self._undefined_hint
raise self._undefined_exception(hint)
@internalcode
def __getattr__(self, name):
if name[:2] == '__':
raise AttributeError(name)
return self._fail_with_undefined_error()
__add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
__truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
__mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
__getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
__float__ = __complex__ = __pow__ = __rpow__ = \
_fail_with_undefined_error
def __str__(self):
return unicode(self).encode('utf-8')
# unicode goes after __str__ because we configured 2to3 to rename
# __unicode__ to __str__. because the 2to3 tree is not designed to
# remove nodes from it, we leave the above __str__ around and let
# it override at runtime.
def __unicode__(self):
return u''
def __len__(self):
return 0
def __iter__(self):
if 0:
yield None
def __nonzero__(self):
return False
def __repr__(self):
return 'Undefined'
class DebugUndefined(Undefined):
"""An undefined that returns the debug info when printed.
>>> foo = DebugUndefined(name='foo')
>>> str(foo)
'{{ foo }}'
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ()
def __unicode__(self):
if self._undefined_hint is None:
if self._undefined_obj is missing:
return u'{{ %s }}' % self._undefined_name
return '{{ no such element: %s[%r] }}' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
return u'{{ undefined value printed: %s }}' % self._undefined_hint
class StrictUndefined(Undefined):
"""An undefined that barks on print and iteration as well as boolean
tests and all kinds of comparisons. In other words: you can do nothing
with it except checking if it's defined using the `defined` test.
>>> foo = StrictUndefined(name='foo')
>>> str(foo)
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> not foo
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ()
__iter__ = __unicode__ = __str__ = __len__ = __nonzero__ = __eq__ = \
__ne__ = __bool__ = Undefined._fail_with_undefined_error
# remove remaining slots attributes, after the metaclass did the magic they
# are unneeded and irritating as they contain wrong data for the subclasses.
del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.nodes
~~~~~~~~~~~~
This module implements additional nodes derived from the ast base node.
It also provides some node tree helper functions like `in_lineno` and
`get_nodes` used by the parser and translator in order to normalize
python and jinja nodes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import operator
from itertools import chain, izip
from collections import deque
from jinja2.utils import Markup, MethodType, FunctionType
#: the types we support for context functions
_context_function_types = (FunctionType, MethodType)
_binop_to_func = {
'*': operator.mul,
'/': operator.truediv,
'//': operator.floordiv,
'**': operator.pow,
'%': operator.mod,
'+': operator.add,
'-': operator.sub
}
_uaop_to_func = {
'not': operator.not_,
'+': operator.pos,
'-': operator.neg
}
_cmpop_to_func = {
'eq': operator.eq,
'ne': operator.ne,
'gt': operator.gt,
'gteq': operator.ge,
'lt': operator.lt,
'lteq': operator.le,
'in': lambda a, b: a in b,
'notin': lambda a, b: a not in b
}
class Impossible(Exception):
"""Raised if the node could not perform a requested action."""
class NodeType(type):
"""A metaclass for nodes that handles the field and attribute
inheritance. fields and attributes from the parent class are
automatically forwarded to the child."""
def __new__(cls, name, bases, d):
for attr in 'fields', 'attributes':
storage = []
storage.extend(getattr(bases[0], attr, ()))
storage.extend(d.get(attr, ()))
assert len(bases) == 1, 'multiple inheritance not allowed'
assert len(storage) == len(set(storage)), 'layout conflict'
d[attr] = tuple(storage)
d.setdefault('abstract', False)
return type.__new__(cls, name, bases, d)
class EvalContext(object):
"""Holds evaluation time information. Custom attributes can be attached
to it in extensions.
"""
def __init__(self, environment, template_name=None):
self.environment = environment
if callable(environment.autoescape):
self.autoescape = environment.autoescape(template_name)
else:
self.autoescape = environment.autoescape
self.volatile = False
def save(self):
return self.__dict__.copy()
def revert(self, old):
self.__dict__.clear()
self.__dict__.update(old)
def get_eval_context(node, ctx):
if ctx is None:
if node.environment is None:
raise RuntimeError('if no eval context is passed, the '
'node must have an attached '
'environment.')
return EvalContext(node.environment)
return ctx
class Node(object):
"""Baseclass for all Jinja2 nodes. There are a number of nodes available
of different types. There are three major types:
- :class:`Stmt`: statements
- :class:`Expr`: expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists,
or arbitrary values. Fields are passed to the constructor as regular
positional arguments, attributes as keyword arguments. Each node has
two attributes: `lineno` (the line number of the node) and `environment`.
The `environment` attribute is set at the end of the parsing process for
all nodes automatically.
"""
__metaclass__ = NodeType
fields = ()
attributes = ('lineno', 'environment')
abstract = True
def __init__(self, *fields, **attributes):
if self.abstract:
raise TypeError('abstract nodes are not instanciable')
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError('%r takes 0 arguments' %
self.__class__.__name__)
raise TypeError('%r takes 0 or %d argument%s' % (
self.__class__.__name__,
len(self.fields),
len(self.fields) != 1 and 's' or ''
))
for name, arg in izip(self.fields, fields):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError('unknown attribute %r' %
iter(attributes).next())
def iter_fields(self, exclude=None, only=None):
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
def iter_child_nodes(self, exclude=None, only=None):
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
def find(self, node_type):
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result
def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result
def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self
def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
def __eq__(self, other):
return type(self) is type(other) and \
tuple(self.iter_fields()) == tuple(other.iter_fields())
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
arg in self.fields)
)
class Stmt(Node):
"""Base node for all statements."""
abstract = True
class Helper(Node):
"""Nodes that exist in a specific context only."""
abstract = True
class Template(Node):
"""Node that represents a template. This must be the outermost node that
is passed to the compiler.
"""
fields = ('body',)
class Output(Stmt):
"""A node that holds multiple expressions which are then printed out.
This is used both for the `print` statement and the regular template data.
"""
fields = ('nodes',)
class Extends(Stmt):
"""Represents an extends statement."""
fields = ('template',)
class For(Stmt):
"""The for loop. `target` is the target for the iteration (usually a
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
of nodes that are used as loop-body, and `else_` a list of nodes for the
`else` block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as `test`, otherwise `None`.
"""
fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
class If(Stmt):
"""If `test` is true, `body` is rendered, else `else_`."""
fields = ('test', 'body', 'else_')
class Macro(Stmt):
"""A macro definition. `name` is the name of the macro, `args` a list of
arguments and `defaults` a list of defaults if there are any. `body` is
a list of nodes for the macro body.
"""
fields = ('name', 'args', 'defaults', 'body')
class CallBlock(Stmt):
"""Like a macro without a name but a call instead. `call` is called with
the unnamed macro as `caller` argument this node holds.
"""
fields = ('call', 'args', 'defaults', 'body')
class FilterBlock(Stmt):
"""Node for filter sections."""
fields = ('body', 'filter')
class Block(Stmt):
"""A node that represents a block."""
fields = ('name', 'body', 'scoped')
class Include(Stmt):
"""A node that represents the include tag."""
fields = ('template', 'with_context', 'ignore_missing')
class Import(Stmt):
"""A node that represents the import tag."""
fields = ('template', 'target', 'with_context')
class FromImport(Stmt):
"""A node that represents the from import tag. It's important to not
pass unsafe names to the name attribute. The compiler translates the
attribute lookups directly into getattr calls and does *not* use the
subscript callback of the interface. As exported variables may not
start with double underscores (which the parser asserts) this is not a
problem for regular Jinja code, but if this node is used in an extension
extra care must be taken.
The list of names may contain tuples if aliases are wanted.
"""
fields = ('template', 'names', 'with_context')
class ExprStmt(Stmt):
"""A statement that evaluates an expression and discards the result."""
fields = ('node',)
class Assign(Stmt):
"""Assigns an expression to a target."""
fields = ('target', 'node')
class Expr(Node):
"""Baseclass for all expressions."""
abstract = True
def as_const(self, eval_ctx=None):
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
"""
raise Impossible()
def can_assign(self):
"""Check if it's possible to assign something to this node."""
return False
class BinExpr(Expr):
"""Baseclass for all binary expressions."""
fields = ('left', 'right')
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if self.environment.sandboxed and \
self.operator in self.environment.intercepted_binops:
raise Impossible()
f = _binop_to_func[self.operator]
try:
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
except Exception:
raise Impossible()
class UnaryExpr(Expr):
"""Baseclass for all unary expressions."""
fields = ('node',)
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if self.environment.sandboxed and \
self.operator in self.environment.intercepted_unops:
raise Impossible()
f = _uaop_to_func[self.operator]
try:
return f(self.node.as_const(eval_ctx))
except Exception:
raise Impossible()
class Name(Expr):
"""Looks up a name or stores a value in a name.
The `ctx` of the node can be one of the following values:
- `store`: store a value in the name
- `load`: load that name
- `param`: like `store` but if the name was defined as function parameter.
"""
fields = ('name', 'ctx')
def can_assign(self):
return self.name not in ('true', 'false', 'none',
'True', 'False', 'None')
class Literal(Expr):
"""Baseclass for literals."""
abstract = True
class Const(Literal):
"""All constant values. The parser will return this node for simple
constants such as ``42`` or ``"foo"`` but it can be used to store more
complex values such as lists too. Only constants with a safe
representation (objects where ``eval(repr(x)) == x`` is true).
"""
fields = ('value',)
def as_const(self, eval_ctx=None):
return self.value
@classmethod
def from_untrusted(cls, value, lineno=None, environment=None):
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
class TemplateData(Literal):
"""A constant template string."""
fields = ('data',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
class Tuple(Literal):
"""For loop unpacking and some other things like multiple arguments
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
is used for loading the names or storing.
"""
fields = ('items', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return tuple(x.as_const(eval_ctx) for x in self.items)
def can_assign(self):
for item in self.items:
if not item.can_assign():
return False
return True
class List(Literal):
"""Any list literal such as ``[1, 2, 3]``"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return [x.as_const(eval_ctx) for x in self.items]
class Dict(Literal):
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair` nodes.
"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return dict(x.as_const(eval_ctx) for x in self.items)
class Pair(Helper):
"""A key, value pair for dicts."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
class Keyword(Helper):
"""A key, value pair for keyword arguments where key is a string."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key, self.value.as_const(eval_ctx)
class CondExpr(Expr):
"""A conditional expression (inline if expression). (``{{
foo if bar else baz }}``)
"""
fields = ('test', 'expr1', 'expr2')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.test.as_const(eval_ctx):
return self.expr1.as_const(eval_ctx)
# if we evaluate to an undefined object, we better do that at runtime
if self.expr2 is None:
raise Impossible()
return self.expr2.as_const(eval_ctx)
class Filter(Expr):
"""This node applies a filter on an expression. `name` is the name of
the filter, the rest of the fields are the same as for :class:`Call`.
If the `node` of a filter is `None` the contents of the last buffer are
filtered. Buffers are created by macros and filter blocks.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile or self.node is None:
raise Impossible()
# we have to be careful here because we call filter_ below.
# if this variable would be called filter, 2to3 would wrap the
# call in a list beause it is assuming we are talking about the
# builtin filter function here which no longer returns a list in
# python 3. because of that, do not rename filter_ to filter!
filter_ = self.environment.filters.get(self.name)
if filter_ is None or getattr(filter_, 'contextfilter', False):
raise Impossible()
obj = self.node.as_const(eval_ctx)
args = [x.as_const(eval_ctx) for x in self.args]
if getattr(filter_, 'evalcontextfilter', False):
args.insert(0, eval_ctx)
elif getattr(filter_, 'environmentfilter', False):
args.insert(0, self.environment)
kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
if self.dyn_args is not None:
try:
args.extend(self.dyn_args.as_const(eval_ctx))
except Exception:
raise Impossible()
if self.dyn_kwargs is not None:
try:
kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
except Exception:
raise Impossible()
try:
return filter_(obj, *args, **kwargs)
except Exception:
raise Impossible()
class Test(Expr):
"""Applies a test on an expression. `name` is the name of the test, the
rest of the fields are the same as for :class:`Call`.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
class Call(Expr):
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
and `dyn_kwargs` has to be either `None` or a node that is used as
node for dynamic positional (``*args``) or keyword (``**kwargs``)
arguments.
"""
fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
obj = self.node.as_const(eval_ctx)
# don't evaluate context functions
args = [x.as_const(eval_ctx) for x in self.args]
if isinstance(obj, _context_function_types):
if getattr(obj, 'contextfunction', False):
raise Impossible()
elif getattr(obj, 'evalcontextfunction', False):
args.insert(0, eval_ctx)
elif getattr(obj, 'environmentfunction', False):
args.insert(0, self.environment)
kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
if self.dyn_args is not None:
try:
args.extend(self.dyn_args.as_const(eval_ctx))
except Exception:
raise Impossible()
if self.dyn_kwargs is not None:
try:
kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
except Exception:
raise Impossible()
try:
return obj(*args, **kwargs)
except Exception:
raise Impossible()
class Getitem(Expr):
"""Get an attribute or item from an expression and prefer the item."""
fields = ('node', 'arg', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.ctx != 'load':
raise Impossible()
try:
return self.environment.getitem(self.node.as_const(eval_ctx),
self.arg.as_const(eval_ctx))
except Exception:
raise Impossible()
def can_assign(self):
return False
class Getattr(Expr):
"""Get an attribute or item from an expression that is a ascii-only
bytestring and prefer the attribute.
"""
fields = ('node', 'attr', 'ctx')
def as_const(self, eval_ctx=None):
if self.ctx != 'load':
raise Impossible()
try:
eval_ctx = get_eval_context(self, eval_ctx)
return self.environment.getattr(self.node.as_const(eval_ctx),
self.attr)
except Exception:
raise Impossible()
def can_assign(self):
return False
class Slice(Expr):
"""Represents a slice object. This must only be used as argument for
:class:`Subscript`.
"""
fields = ('start', 'stop', 'step')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
def const(obj):
if obj is None:
return None
return obj.as_const(eval_ctx)
return slice(const(self.start), const(self.stop), const(self.step))
class Concat(Expr):
"""Concatenates the list of expressions provided after converting them to
unicode.
"""
fields = ('nodes',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
class Compare(Expr):
"""Compares an expression with some other expressions. `ops` must be a
list of :class:`Operand`\s.
"""
fields = ('expr', 'ops')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
result = value = self.expr.as_const(eval_ctx)
try:
for op in self.ops:
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
value = new_value
except Exception:
raise Impossible()
return result
class Operand(Helper):
"""Holds an operator and an expression."""
fields = ('op', 'expr')
if __debug__:
Operand.__doc__ += '\nThe following operators are available: ' + \
', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
set(_uaop_to_func) | set(_cmpop_to_func)))
class Mul(BinExpr):
"""Multiplies the left with the right node."""
operator = '*'
class Div(BinExpr):
"""Divides the left by the right node."""
operator = '/'
class FloorDiv(BinExpr):
"""Divides the left by the right node and truncates conver the
result into an integer by truncating.
"""
operator = '//'
class Add(BinExpr):
"""Add the left to the right node."""
operator = '+'
class Sub(BinExpr):
"""Substract the right from the left node."""
operator = '-'
class Mod(BinExpr):
"""Left modulo right."""
operator = '%'
class Pow(BinExpr):
"""Left to the power of right."""
operator = '**'
class And(BinExpr):
"""Short circuited AND."""
operator = 'and'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
class Or(BinExpr):
"""Short circuited OR."""
operator = 'or'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
class Not(UnaryExpr):
"""Negate the expression."""
operator = 'not'
class Neg(UnaryExpr):
"""Make the expression negative."""
operator = '-'
class Pos(UnaryExpr):
"""Make the expression positive (noop for most expressions)"""
operator = '+'
# Helpers for extensions
class EnvironmentAttribute(Expr):
"""Loads an attribute from the environment object. This is useful for
extensions that want to call a callback stored on the environment.
"""
fields = ('name',)
class ExtensionAttribute(Expr):
"""Returns the attribute of an extension bound to the environment.
The identifier is the identifier of the :class:`Extension`.
This node is usually constructed by calling the
:meth:`~jinja2.ext.Extension.attr` method on an extension.
"""
fields = ('identifier', 'name')
class ImportedName(Expr):
"""If created with an import name the import name is returned on node
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
function from the cgi module on evaluation. Imports are optimized by the
compiler so there is no need to assign them to local variables.
"""
fields = ('importname',)
class InternalName(Expr):
"""An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier is not available from the
template and is not threated specially by the compiler.
"""
fields = ('name',)
def __init__(self):
raise TypeError('Can\'t create internal names. Use the '
'`free_identifier` method on a parser.')
class MarkSafe(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
class MarkSafeIfAutoescape(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`) but
only if autoescaping is active.
.. versionadded:: 2.5
"""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
expr = self.expr.as_const(eval_ctx)
if eval_ctx.autoescape:
return Markup(expr)
return expr
class ContextReference(Expr):
"""Returns the current template context. It can be used like a
:class:`Name` node, with a ``'load'`` ctx and will return the
current :class:`~jinja2.runtime.Context` object.
Here an example that assigns the current template name to a
variable named `foo`::
Assign(Name('foo', ctx='store'),
Getattr(ContextReference(), 'name'))
"""
class Continue(Stmt):
"""Continue a loop."""
class Break(Stmt):
"""Break a loop."""
class Scope(Stmt):
"""An artificial scope."""
fields = ('body',)
class EvalContextModifier(Stmt):
"""Modifies the eval context. For each option that should be modified,
a :class:`Keyword` has to be added to the :attr:`options` list.
Example to change the `autoescape` setting::
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
"""
fields = ('options',)
class ScopedEvalContextModifier(EvalContextModifier):
"""Modifies the eval context and reverts it later. Works exactly like
:class:`EvalContextModifier` but will only modify the
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
"""
fields = ('body',)
# make sure nobody creates custom nodes
def _failing_new(*args, **kwargs):
raise TypeError('can\'t create custom node types')
NodeType.__new__ = staticmethod(_failing_new); del _failing_new
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.debug
~~~~~~~~~~~~
Implements the debug interface for Jinja. This module does some pretty
ugly stuff with the Python traceback system in order to achieve tracebacks
with correct line numbers, locals and contents.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import sys
import traceback
from types import TracebackType
from jinja2.utils import CodeType, missing, internal_code
from jinja2.exceptions import TemplateSyntaxError
# on pypy we can take advantage of transparent proxies
try:
from __pypy__ import tproxy
except ImportError:
tproxy = None
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
except SyntaxError:
raise_helper = 'raise __jinja_exception__[1]'
except TypeError:
raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]'
class TracebackFrameProxy(object):
"""Proxies a traceback frame."""
def __init__(self, tb):
self.tb = tb
self._tb_next = None
@property
def tb_next(self):
return self._tb_next
def set_next(self, next):
if tb_set_next is not None:
try:
tb_set_next(self.tb, next and next.tb or None)
except Exception:
# this function can fail due to all the hackery it does
# on various python implementations. We just catch errors
# down and ignore them if necessary.
pass
self._tb_next = next
@property
def is_jinja_frame(self):
return '__jinja_template__' in self.tb.tb_frame.f_globals
def __getattr__(self, name):
return getattr(self.tb, name)
def make_frame_proxy(frame):
proxy = TracebackFrameProxy(frame)
if tproxy is None:
return proxy
def operation_handler(operation, *args, **kwargs):
if operation in ('__getattribute__', '__getattr__'):
return getattr(proxy, args[0])
elif operation == '__setattr__':
proxy.__setattr__(*args, **kwargs)
else:
return getattr(proxy, operation)(*args, **kwargs)
return tproxy(TracebackType, operation_handler)
class ProcessedTraceback(object):
"""Holds a Jinja preprocessed traceback for priting or reraising."""
def __init__(self, exc_type, exc_value, frames):
assert frames, 'no frames for this traceback?'
self.exc_type = exc_type
self.exc_value = exc_value
self.frames = frames
# newly concatenate the frames (which are proxies)
prev_tb = None
for tb in self.frames:
if prev_tb is not None:
prev_tb.set_next(tb)
prev_tb = tb
prev_tb.set_next(None)
def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
self.frames[0], limit=limit)
return ''.join(lines).rstrip()
def render_as_html(self, full=False):
"""Return a unicode string with the traceback as rendered HTML."""
from jinja2.debugrenderer import render_traceback
return u'%s\n\n<!--\n%s\n-->' % (
render_traceback(self, full=full),
self.render_as_text().decode('utf-8', 'replace')
)
@property
def is_template_syntax_error(self):
"""`True` if this is a template syntax error."""
return isinstance(self.exc_value, TemplateSyntaxError)
@property
def exc_info(self):
"""Exception info tuple with a proxy around the frame objects."""
return self.exc_type, self.exc_value, self.frames[0]
@property
def standard_exc_info(self):
"""Standard python exc_info for re-raising"""
tb = self.frames[0]
# the frame will be an actual traceback (or transparent proxy) if
# we are on pypy or a python implementation with support for tproxy
if type(tb) is not TracebackType:
tb = tb.tb
return self.exc_type, self.exc_value, tb
def make_traceback(exc_info, source_hint=None):
"""Creates a processed traceback object from the exc_info."""
exc_type, exc_value, tb = exc_info
if isinstance(exc_value, TemplateSyntaxError):
exc_info = translate_syntax_error(exc_value, source_hint)
initial_skip = 0
else:
initial_skip = 1
return translate_exception(exc_info, initial_skip)
def translate_syntax_error(error, source=None):
"""Rewrites a syntax error to please traceback systems."""
error.source = source
error.translated = True
exc_info = (error.__class__, error, None)
filename = error.filename
if filename is None:
filename = '<unknown>'
return fake_exc_info(exc_info, filename, error.lineno)
def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
"""
tb = exc_info[2]
frames = []
# skip some internal frames if wanted
for x in xrange(initial_skip):
if tb is not None:
tb = tb.tb_next
initial_tb = tb
while tb is not None:
# skip frames decorated with @internalcode. These are internal
# calls we can't avoid and that are useless in template debugging
# output.
if tb.tb_frame.f_code in internal_code:
tb = tb.tb_next
continue
# save a reference to the next frame if we override the current
# one with a faked one.
next = tb.tb_next
# fake template exceptions
template = tb.tb_frame.f_globals.get('__jinja_template__')
if template is not None:
lineno = template.get_corresponding_lineno(tb.tb_lineno)
tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
lineno)[2]
frames.append(make_frame_proxy(tb))
tb = next
# if we don't have any exceptions in the frames left, we have to
# reraise it unchanged.
# XXX: can we backup here? when could this happen?
if not frames:
raise exc_info[0], exc_info[1], exc_info[2]
return ProcessedTraceback(exc_info[0], exc_info[1], frames)
def fake_exc_info(exc_info, filename, lineno):
"""Helper for `translate_exception`."""
exc_type, exc_value, tb = exc_info
# figure the real context out
if tb is not None:
real_locals = tb.tb_frame.f_locals.copy()
ctx = real_locals.get('context')
if ctx:
locals = ctx.get_all()
else:
locals = {}
for name, value in real_locals.iteritems():
if name.startswith('l_') and value is not missing:
locals[name[2:]] = value
# if there is a local called __jinja_exception__, we get
# rid of it to not break the debug functionality.
locals.pop('__jinja_exception__', None)
else:
locals = {}
# assamble fake globals we need
globals = {
'__name__': filename,
'__file__': filename,
'__jinja_exception__': exc_info[:2],
# we don't want to keep the reference to the template around
# to not cause circular dependencies, but we mark it as Jinja
# frame for the ProcessedTraceback
'__jinja_template__': None
}
# and fake the exception
code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec')
# if it's possible, change the name of the code. This won't work
# on some python environments such as google appengine
try:
if tb is None:
location = 'template'
else:
function = tb.tb_frame.f_code.co_name
if function == 'root':
location = 'top-level template code'
elif function.startswith('block_'):
location = 'block "%s"' % function[6:]
else:
location = 'template'
code = CodeType(0, code.co_nlocals, code.co_stacksize,
code.co_flags, code.co_code, code.co_consts,
code.co_names, code.co_varnames, filename,
location, code.co_firstlineno,
code.co_lnotab, (), ())
except:
pass
# execute the code and catch the new traceback
try:
exec code in globals, locals
except:
exc_info = sys.exc_info()
new_tb = exc_info[2].tb_next
# return without this frame
return exc_info[:2] + (new_tb,)
def _init_ugly_crap():
"""This function implements a few ugly things so that we can patch the
traceback objects. The function returned allows resetting `tb_next` on
any python traceback object. Do not attempt to use this on non cpython
interpreters
"""
import ctypes
from types import TracebackType
# figure out side of _Py_ssize_t
if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
_Py_ssize_t = ctypes.c_int64
else:
_Py_ssize_t = ctypes.c_int
# regular python
class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
]
# python with trace
if hasattr(sys, 'getobjects'):
class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('_ob_next', ctypes.POINTER(_PyObject)),
('_ob_prev', ctypes.POINTER(_PyObject)),
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
]
class _Traceback(_PyObject):
pass
_Traceback._fields_ = [
('tb_next', ctypes.POINTER(_Traceback)),
('tb_frame', ctypes.POINTER(_PyObject)),
('tb_lasti', ctypes.c_int),
('tb_lineno', ctypes.c_int)
]
def tb_set_next(tb, next):
"""Set the tb_next attribute of a traceback object."""
if not (isinstance(tb, TracebackType) and
(next is None or isinstance(next, TracebackType))):
raise TypeError('tb_set_next arguments must be traceback objects')
obj = _Traceback.from_address(id(tb))
if tb.tb_next is not None:
old = _Traceback.from_address(id(tb.tb_next))
old.ob_refcnt -= 1
if next is None:
obj.tb_next = ctypes.POINTER(_Traceback)()
else:
next = _Traceback.from_address(id(next))
next.ob_refcnt += 1
obj.tb_next = ctypes.pointer(next)
return tb_set_next
# try to get a tb_set_next implementation if we don't have transparent
# proxies.
tb_set_next = None
if tproxy is None:
try:
from jinja2._debugsupport import tb_set_next
except ImportError:
try:
tb_set_next = _init_ugly_crap()
except:
pass
del _init_ugly_crap
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.compiler
~~~~~~~~~~~~~~~
Compiles nodes into python code.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from cStringIO import StringIO
from itertools import chain
from copy import deepcopy
from jinja2 import nodes
from jinja2.nodes import EvalContext
from jinja2.visitor import NodeVisitor
from jinja2.exceptions import TemplateAssertionError
from jinja2.utils import Markup, concat, escape, is_python_keyword, next
operators = {
'eq': '==',
'ne': '!=',
'gt': '>',
'gteq': '>=',
'lt': '<',
'lteq': '<=',
'in': 'in',
'notin': 'not in'
}
try:
exec '(0 if 0 else 0)'
except SyntaxError:
have_condexpr = False
else:
have_condexpr = True
# what method to iterate over items do we want to use for dict iteration
# in generated code? on 2.x let's go with iteritems, on 3.x with items
if hasattr(dict, 'iteritems'):
dict_item_iter = 'iteritems'
else:
dict_item_iter = 'items'
# does if 0: dummy(x) get us x into the scope?
def unoptimize_before_dead_code():
x = 42
def f():
if 0: dummy(x)
return f
unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)
def generate(node, environment, name, filename, stream=None,
defer_init=False):
"""Generate the python source for a node tree."""
if not isinstance(node, nodes.Template):
raise TypeError('Can\'t compile non template nodes')
generator = CodeGenerator(environment, name, filename, stream, defer_init)
generator.visit(node)
if stream is None:
return generator.stream.getvalue()
def has_safe_repr(value):
"""Does the node have a safe representation?"""
if value is None or value is NotImplemented or value is Ellipsis:
return True
if isinstance(value, (bool, int, long, float, complex, basestring,
xrange, Markup)):
return True
if isinstance(value, (tuple, list, set, frozenset)):
for item in value:
if not has_safe_repr(item):
return False
return True
elif isinstance(value, dict):
for key, value in value.iteritems():
if not has_safe_repr(key):
return False
if not has_safe_repr(value):
return False
return True
return False
def find_undeclared(nodes, names):
"""Check if the names passed are accessed undeclared. The return value
is a set of all the undeclared names from the sequence of names found.
"""
visitor = UndeclaredNameVisitor(names)
try:
for node in nodes:
visitor.visit(node)
except VisitorExit:
pass
return visitor.undeclared
class Identifiers(object):
"""Tracks the status of identifiers in frames."""
def __init__(self):
# variables that are known to be declared (probably from outer
# frames or because they are special for the frame)
self.declared = set()
# undeclared variables from outer scopes
self.outer_undeclared = set()
# names that are accessed without being explicitly declared by
# this one or any of the outer scopes. Names can appear both in
# declared and undeclared.
self.undeclared = set()
# names that are declared locally
self.declared_locally = set()
# names that are declared by parameters
self.declared_parameter = set()
def add_special(self, name):
"""Register a special name like `loop`."""
self.undeclared.discard(name)
self.declared.add(name)
def is_declared(self, name):
"""Check if a name is declared in this or an outer scope."""
if name in self.declared_locally or name in self.declared_parameter:
return True
return name in self.declared
def copy(self):
return deepcopy(self)
class Frame(object):
"""Holds compile time information for us."""
def __init__(self, eval_ctx, parent=None):
self.eval_ctx = eval_ctx
self.identifiers = Identifiers()
# a toplevel frame is the root + soft frames such as if conditions.
self.toplevel = False
# the root frame is basically just the outermost frame, so no if
# conditions. This information is used to optimize inheritance
# situations.
self.rootlevel = False
# in some dynamic inheritance situations the compiler needs to add
# write tests around output statements.
self.require_output_check = parent and parent.require_output_check
# inside some tags we are using a buffer rather than yield statements.
# this for example affects {% filter %} or {% macro %}. If a frame
# is buffered this variable points to the name of the list used as
# buffer.
self.buffer = None
# the name of the block we're in, otherwise None.
self.block = parent and parent.block or None
# a set of actually assigned names
self.assigned_names = set()
# the parent of this frame
self.parent = parent
if parent is not None:
self.identifiers.declared.update(
parent.identifiers.declared |
parent.identifiers.declared_parameter |
parent.assigned_names
)
self.identifiers.outer_undeclared.update(
parent.identifiers.undeclared -
self.identifiers.declared
)
self.buffer = parent.buffer
def copy(self):
"""Create a copy of the current one."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.identifiers = object.__new__(self.identifiers.__class__)
rv.identifiers.__dict__.update(self.identifiers.__dict__)
return rv
def inspect(self, nodes):
"""Walk the node and check for identifiers. If the scope is hard (eg:
enforce on a python level) overrides from outer scopes are tracked
differently.
"""
visitor = FrameIdentifierVisitor(self.identifiers)
for node in nodes:
visitor.visit(node)
def find_shadowed(self, extra=()):
"""Find all the shadowed names. extra is an iterable of variables
that may be defined with `add_special` which may occour scoped.
"""
i = self.identifiers
return (i.declared | i.outer_undeclared) & \
(i.declared_locally | i.declared_parameter) | \
set(x for x in extra if i.is_declared(x))
def inner(self):
"""Return an inner frame."""
return Frame(self.eval_ctx, self)
def soft(self):
"""Return a soft frame. A soft frame may not be modified as
standalone thing as it shares the resources with the frame it
was created of, but it's not a rootlevel frame any longer.
"""
rv = self.copy()
rv.rootlevel = False
return rv
__copy__ = copy
class VisitorExit(RuntimeError):
"""Exception used by the `UndeclaredNameVisitor` to signal a stop."""
class DependencyFinderVisitor(NodeVisitor):
"""A visitor that collects filter and test calls."""
def __init__(self):
self.filters = set()
self.tests = set()
def visit_Filter(self, node):
self.generic_visit(node)
self.filters.add(node.name)
def visit_Test(self, node):
self.generic_visit(node)
self.tests.add(node.name)
def visit_Block(self, node):
"""Stop visiting at blocks."""
class UndeclaredNameVisitor(NodeVisitor):
"""A visitor that checks if a name is accessed without being
declared. This is different from the frame visitor as it will
not stop at closure frames.
"""
def __init__(self, names):
self.names = set(names)
self.undeclared = set()
def visit_Name(self, node):
if node.ctx == 'load' and node.name in self.names:
self.undeclared.add(node.name)
if self.undeclared == self.names:
raise VisitorExit()
else:
self.names.discard(node.name)
def visit_Block(self, node):
"""Stop visiting a blocks."""
class FrameIdentifierVisitor(NodeVisitor):
"""A visitor for `Frame.inspect`."""
def __init__(self, identifiers):
self.identifiers = identifiers
def visit_Name(self, node):
"""All assignments to names go through this function."""
if node.ctx == 'store':
self.identifiers.declared_locally.add(node.name)
elif node.ctx == 'param':
self.identifiers.declared_parameter.add(node.name)
elif node.ctx == 'load' and not \
self.identifiers.is_declared(node.name):
self.identifiers.undeclared.add(node.name)
def visit_If(self, node):
self.visit(node.test)
real_identifiers = self.identifiers
old_names = real_identifiers.declared_locally | \
real_identifiers.declared_parameter
def inner_visit(nodes):
if not nodes:
return set()
self.identifiers = real_identifiers.copy()
for subnode in nodes:
self.visit(subnode)
rv = self.identifiers.declared_locally - old_names
# we have to remember the undeclared variables of this branch
# because we will have to pull them.
real_identifiers.undeclared.update(self.identifiers.undeclared)
self.identifiers = real_identifiers
return rv
body = inner_visit(node.body)
else_ = inner_visit(node.else_ or ())
# the differences between the two branches are also pulled as
# undeclared variables
real_identifiers.undeclared.update(body.symmetric_difference(else_) -
real_identifiers.declared)
# remember those that are declared.
real_identifiers.declared_locally.update(body | else_)
def visit_Macro(self, node):
self.identifiers.declared_locally.add(node.name)
def visit_Import(self, node):
self.generic_visit(node)
self.identifiers.declared_locally.add(node.target)
def visit_FromImport(self, node):
self.generic_visit(node)
for name in node.names:
if isinstance(name, tuple):
self.identifiers.declared_locally.add(name[1])
else:
self.identifiers.declared_locally.add(name)
def visit_Assign(self, node):
"""Visit assignments in the correct order."""
self.visit(node.node)
self.visit(node.target)
def visit_For(self, node):
"""Visiting stops at for blocks. However the block sequence
is visited as part of the outer scope.
"""
self.visit(node.iter)
def visit_CallBlock(self, node):
self.visit(node.call)
def visit_FilterBlock(self, node):
self.visit(node.filter)
def visit_Scope(self, node):
"""Stop visiting at scopes."""
def visit_Block(self, node):
"""Stop visiting at blocks."""
class CompilerExit(Exception):
"""Raised if the compiler encountered a situation where it just
doesn't make sense to further process the code. Any block that
raises such an exception is not further processed.
"""
class CodeGenerator(NodeVisitor):
def __init__(self, environment, name, filename, stream=None,
defer_init=False):
if stream is None:
stream = StringIO()
self.environment = environment
self.name = name
self.filename = filename
self.stream = stream
self.created_block_context = False
self.defer_init = defer_init
# aliases for imports
self.import_aliases = {}
# a registry for all blocks. Because blocks are moved out
# into the global python scope they are registered here
self.blocks = {}
# the number of extends statements so far
self.extends_so_far = 0
# some templates have a rootlevel extends. In this case we
# can safely assume that we're a child template and do some
# more optimizations.
self.has_known_extends = False
# the current line number
self.code_lineno = 1
# registry of all filters and tests (global, not block local)
self.tests = {}
self.filters = {}
# the debug information
self.debug_info = []
self._write_debug_info = None
# the number of new lines before the next write()
self._new_lines = 0
# the line number of the last written statement
self._last_line = 0
# true if nothing was written so far.
self._first_write = True
# used by the `temporary_identifier` method to get new
# unique, temporary identifier
self._last_identifier = 0
# the current indentation
self._indentation = 0
# -- Various compilation helpers
def fail(self, msg, lineno):
"""Fail with a :exc:`TemplateAssertionError`."""
raise TemplateAssertionError(msg, lineno, self.name, self.filename)
def temporary_identifier(self):
"""Get a new unique identifier."""
self._last_identifier += 1
return 't_%d' % self._last_identifier
def buffer(self, frame):
"""Enable buffering for the frame from that point onwards."""
frame.buffer = self.temporary_identifier()
self.writeline('%s = []' % frame.buffer)
def return_buffer_contents(self, frame):
"""Return the buffer contents of the frame."""
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
else:
self.writeline('return concat(%s)' % frame.buffer)
def indent(self):
"""Indent by one."""
self._indentation += 1
def outdent(self, step=1):
"""Outdent by step."""
self._indentation -= step
def start_write(self, frame, node=None):
"""Yield or write into the frame buffer."""
if frame.buffer is None:
self.writeline('yield ', node)
else:
self.writeline('%s.append(' % frame.buffer, node)
def end_write(self, frame):
"""End the writing process started by `start_write`."""
if frame.buffer is not None:
self.write(')')
def simple_write(self, s, frame, node=None):
"""Simple shortcut for start_write + write + end_write."""
self.start_write(frame, node)
self.write(s)
self.end_write(frame)
def blockvisit(self, nodes, frame):
"""Visit a list of nodes as block in a frame. If the current frame
is no buffer a dummy ``if 0: yield None`` is written automatically
unless the force_generator parameter is set to False.
"""
if frame.buffer is None:
self.writeline('if 0: yield None')
else:
self.writeline('pass')
try:
for node in nodes:
self.visit(node, frame)
except CompilerExit:
pass
def write(self, x):
"""Write a string into the output stream."""
if self._new_lines:
if not self._first_write:
self.stream.write('\n' * self._new_lines)
self.code_lineno += self._new_lines
if self._write_debug_info is not None:
self.debug_info.append((self._write_debug_info,
self.code_lineno))
self._write_debug_info = None
self._first_write = False
self.stream.write(' ' * self._indentation)
self._new_lines = 0
self.stream.write(x)
def writeline(self, x, node=None, extra=0):
"""Combination of newline and write."""
self.newline(node, extra)
self.write(x)
def newline(self, node=None, extra=0):
"""Add one or more newlines before the next write."""
self._new_lines = max(self._new_lines, 1 + extra)
if node is not None and node.lineno != self._last_line:
self._write_debug_info = node.lineno
self._last_line = node.lineno
def signature(self, node, frame, extra_kwargs=None):
"""Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict.
"""
# if any of the given keyword arguments is a python keyword
# we have to make sure that no invalid call is created.
kwarg_workaround = False
for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
if is_python_keyword(kwarg):
kwarg_workaround = True
break
for arg in node.args:
self.write(', ')
self.visit(arg, frame)
if not kwarg_workaround:
for kwarg in node.kwargs:
self.write(', ')
self.visit(kwarg, frame)
if extra_kwargs is not None:
for key, value in extra_kwargs.iteritems():
self.write(', %s=%s' % (key, value))
if node.dyn_args:
self.write(', *')
self.visit(node.dyn_args, frame)
if kwarg_workaround:
if node.dyn_kwargs is not None:
self.write(', **dict({')
else:
self.write(', **{')
for kwarg in node.kwargs:
self.write('%r: ' % kwarg.key)
self.visit(kwarg.value, frame)
self.write(', ')
if extra_kwargs is not None:
for key, value in extra_kwargs.iteritems():
self.write('%r: %s, ' % (key, value))
if node.dyn_kwargs is not None:
self.write('}, **')
self.visit(node.dyn_kwargs, frame)
self.write(')')
else:
self.write('}')
elif node.dyn_kwargs is not None:
self.write(', **')
self.visit(node.dyn_kwargs, frame)
def pull_locals(self, frame):
"""Pull all the references identifiers into the local scope."""
for name in frame.identifiers.undeclared:
self.writeline('l_%s = context.resolve(%r)' % (name, name))
def pull_dependencies(self, nodes):
"""Pull all the dependencies."""
visitor = DependencyFinderVisitor()
for node in nodes:
visitor.visit(node)
for dependency in 'filters', 'tests':
mapping = getattr(self, dependency)
for name in getattr(visitor, dependency):
if name not in mapping:
mapping[name] = self.temporary_identifier()
self.writeline('%s = environment.%s[%r]' %
(mapping[name], dependency, name))
def unoptimize_scope(self, frame):
"""Disable Python optimizations for the frame."""
# XXX: this is not that nice but it has no real overhead. It
# mainly works because python finds the locals before dead code
# is removed. If that breaks we have to add a dummy function
# that just accepts the arguments and does nothing.
if frame.identifiers.declared:
self.writeline('%sdummy(%s)' % (
unoptimize_before_dead_code and 'if 0: ' or '',
', '.join('l_' + name for name in frame.identifiers.declared)
))
def push_scope(self, frame, extra_vars=()):
"""This function returns all the shadowed variables in a dict
in the form name: alias and will write the required assignments
into the current scope. No indentation takes place.
This also predefines locally declared variables from the loop
body because under some circumstances it may be the case that
`extra_vars` is passed to `Frame.find_shadowed`.
"""
aliases = {}
for name in frame.find_shadowed(extra_vars):
aliases[name] = ident = self.temporary_identifier()
self.writeline('%s = l_%s' % (ident, name))
to_declare = set()
for name in frame.identifiers.declared_locally:
if name not in aliases:
to_declare.add('l_' + name)
if to_declare:
self.writeline(' = '.join(to_declare) + ' = missing')
return aliases
def pop_scope(self, aliases, frame):
"""Restore all aliases and delete unused variables."""
for name, alias in aliases.iteritems():
self.writeline('l_%s = %s' % (name, alias))
to_delete = set()
for name in frame.identifiers.declared_locally:
if name not in aliases:
to_delete.add('l_' + name)
if to_delete:
# we cannot use the del statement here because enclosed
# scopes can trigger a SyntaxError:
# a = 42; b = lambda: a; del a
self.writeline(' = '.join(to_delete) + ' = missing')
def function_scoping(self, node, frame, children=None,
find_special=True):
"""In Jinja a few statements require the help of anonymous
functions. Those are currently macros and call blocks and in
the future also recursive loops. As there is currently
technical limitation that doesn't allow reading and writing a
variable in a scope where the initial value is coming from an
outer scope, this function tries to fall back with a common
error message. Additionally the frame passed is modified so
that the argumetns are collected and callers are looked up.
This will return the modified frame.
"""
# we have to iterate twice over it, make sure that works
if children is None:
children = node.iter_child_nodes()
children = list(children)
func_frame = frame.inner()
func_frame.inspect(children)
# variables that are undeclared (accessed before declaration) and
# declared locally *and* part of an outside scope raise a template
# assertion error. Reason: we can't generate reasonable code from
# it without aliasing all the variables.
# this could be fixed in Python 3 where we have the nonlocal
# keyword or if we switch to bytecode generation
overriden_closure_vars = (
func_frame.identifiers.undeclared &
func_frame.identifiers.declared &
(func_frame.identifiers.declared_locally |
func_frame.identifiers.declared_parameter)
)
if overriden_closure_vars:
self.fail('It\'s not possible to set and access variables '
'derived from an outer scope! (affects: %s)' %
', '.join(sorted(overriden_closure_vars)), node.lineno)
# remove variables from a closure from the frame's undeclared
# identifiers.
func_frame.identifiers.undeclared -= (
func_frame.identifiers.undeclared &
func_frame.identifiers.declared
)
# no special variables for this scope, abort early
if not find_special:
return func_frame
func_frame.accesses_kwargs = False
func_frame.accesses_varargs = False
func_frame.accesses_caller = False
func_frame.arguments = args = ['l_' + x.name for x in node.args]
undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
if 'caller' in undeclared:
func_frame.accesses_caller = True
func_frame.identifiers.add_special('caller')
args.append('l_caller')
if 'kwargs' in undeclared:
func_frame.accesses_kwargs = True
func_frame.identifiers.add_special('kwargs')
args.append('l_kwargs')
if 'varargs' in undeclared:
func_frame.accesses_varargs = True
func_frame.identifiers.add_special('varargs')
args.append('l_varargs')
return func_frame
def macro_body(self, node, frame, children=None):
"""Dump the function def of a macro or call block."""
frame = self.function_scoping(node, frame, children)
# macros are delayed, they never require output checks
frame.require_output_check = False
args = frame.arguments
# XXX: this is an ugly fix for the loop nesting bug
# (tests.test_old_bugs.test_loop_call_bug). This works around
# a identifier nesting problem we have in general. It's just more
# likely to happen in loops which is why we work around it. The
# real solution would be "nonlocal" all the identifiers that are
# leaking into a new python frame and might be used both unassigned
# and assigned.
if 'loop' in frame.identifiers.declared:
args = args + ['l_loop=l_loop']
self.writeline('def macro(%s):' % ', '.join(args), node)
self.indent()
self.buffer(frame)
self.pull_locals(frame)
self.blockvisit(node.body, frame)
self.return_buffer_contents(frame)
self.outdent()
return frame
def macro_def(self, node, frame):
"""Dump the macro definition for the def created by macro_body."""
arg_tuple = ', '.join(repr(x.name) for x in node.args)
name = getattr(node, 'name', None)
if len(node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), (' %
(name, arg_tuple))
for arg in node.defaults:
self.visit(arg, frame)
self.write(', ')
self.write('), %r, %r, %r)' % (
bool(frame.accesses_kwargs),
bool(frame.accesses_varargs),
bool(frame.accesses_caller)
))
def position(self, node):
"""Return a human readable position for the node."""
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv
# -- Statement Visitors
def visit_Template(self, node, frame=None):
assert frame is None, 'no root frame allowed'
eval_ctx = EvalContext(self.environment, self.name)
from jinja2.runtime import __all__ as exported
self.writeline('from __future__ import division')
self.writeline('from jinja2.runtime import ' + ', '.join(exported))
if not unoptimize_before_dead_code:
self.writeline('dummy = lambda *x: None')
# if we want a deferred initialization we cannot move the
# environment into a local name
envenv = not self.defer_init and ', environment=environment' or ''
# do we have an extends tag at all? If not, we can save some
# overhead by just not processing any inheritance code.
have_extends = node.find(nodes.Extends) is not None
# find all blocks
for block in node.find_all(nodes.Block):
if block.name in self.blocks:
self.fail('block %r defined twice' % block.name, block.lineno)
self.blocks[block.name] = block
# find all imports and import them
for import_ in node.find_all(nodes.ImportedName):
if import_.importname not in self.import_aliases:
imp = import_.importname
self.import_aliases[imp] = alias = self.temporary_identifier()
if '.' in imp:
module, obj = imp.rsplit('.', 1)
self.writeline('from %s import %s as %s' %
(module, obj, alias))
else:
self.writeline('import %s as %s' % (imp, alias))
# add the load name
self.writeline('name = %r' % self.name)
# generate the root render function.
self.writeline('def root(context%s):' % envenv, extra=1)
# process the root
frame = Frame(eval_ctx)
frame.inspect(node.body)
frame.toplevel = frame.rootlevel = True
frame.require_output_check = have_extends and not self.has_known_extends
self.indent()
if have_extends:
self.writeline('parent_template = None')
if 'self' in find_undeclared(node.body, ('self',)):
frame.identifiers.add_special('self')
self.writeline('l_self = TemplateReference(context)')
self.pull_locals(frame)
self.pull_dependencies(node.body)
self.blockvisit(node.body, frame)
self.outdent()
# make sure that the parent root is called.
if have_extends:
if not self.has_known_extends:
self.indent()
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('for event in parent_template.'
'root_render_func(context):')
self.indent()
self.writeline('yield event')
self.outdent(2 + (not self.has_known_extends))
# at this point we now have the blocks collected and can visit them too.
for name, block in self.blocks.iteritems():
block_frame = Frame(eval_ctx)
block_frame.inspect(block.body)
block_frame.block = name
self.writeline('def block_%s(context%s):' % (name, envenv),
block, 1)
self.indent()
undeclared = find_undeclared(block.body, ('self', 'super'))
if 'self' in undeclared:
block_frame.identifiers.add_special('self')
self.writeline('l_self = TemplateReference(context)')
if 'super' in undeclared:
block_frame.identifiers.add_special('super')
self.writeline('l_super = context.super(%r, '
'block_%s)' % (name, name))
self.pull_locals(block_frame)
self.pull_dependencies(block.body)
self.blockvisit(block.body, block_frame)
self.outdent()
self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
for x in self.blocks),
extra=1)
# add a function that returns the debug info
self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
in self.debug_info))
def visit_Block(self, node, frame):
"""Call a block and register it for the template."""
level = 1
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline('if parent_template is None:')
self.indent()
level += 1
context = node.scoped and 'context.derived(locals())' or 'context'
self.writeline('for event in context.blocks[%r][0](%s):' % (
node.name, context), node)
self.indent()
self.simple_write('event', frame)
self.outdent(level)
def visit_Extends(self, node, frame):
"""Calls the extender."""
if not frame.toplevel:
self.fail('cannot use extend from a non top-level scope',
node.lineno)
# if the number of extends statements in general is zero so
# far, we don't have to add a check if something extended
# the template before this one.
if self.extends_so_far > 0:
# if we have a known extends we just add a template runtime
# error into the generated code. We could catch that at compile
# time too, but i welcome it not to confuse users by throwing the
# same error at different times just "because we can".
if not self.has_known_extends:
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('raise TemplateRuntimeError(%r)' %
'extended multiple times')
self.outdent()
# if we have a known extends already we don't need that code here
# as we know that the template execution will end here.
if self.has_known_extends:
raise CompilerExit()
self.writeline('parent_template = environment.get_template(', node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
self.writeline('for name, parent_block in parent_template.'
'blocks.%s():' % dict_item_iter)
self.indent()
self.writeline('context.blocks.setdefault(name, []).'
'append(parent_block)')
self.outdent()
# if this extends statement was in the root level we can take
# advantage of that information and simplify the generated code
# in the top level from this point onwards
if frame.rootlevel:
self.has_known_extends = True
# and now we have one more
self.extends_so_far += 1
def visit_Include(self, node, frame):
"""Handles includes."""
if node.with_context:
self.unoptimize_scope(frame)
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, basestring):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
if node.with_context:
self.writeline('for event in template.root_render_func('
'template.new_context(context.parent, True, '
'locals())):')
else:
self.writeline('for event in template.module._body_stream:')
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent()
def visit_Import(self, node, frame):
"""Visit regular imports."""
if node.with_context:
self.unoptimize_scope(frame)
self.writeline('l_%s = ' % node.target, node)
if frame.toplevel:
self.write('context.vars[%r] = ' % node.target)
self.write('environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True, locals())')
else:
self.write('module')
if frame.toplevel and not node.target.startswith('_'):
self.writeline('context.exported_vars.discard(%r)' % node.target)
frame.assigned_names.add(node.target)
def visit_FromImport(self, node, frame):
"""Visit named imports."""
self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True)')
else:
self.write('module')
var_names = []
discarded_names = []
for name in node.names:
if isinstance(name, tuple):
name, alias = name
else:
alias = name
self.writeline('l_%s = getattr(included_template, '
'%r, missing)' % (alias, name))
self.writeline('if l_%s is missing:' % alias)
self.indent()
self.writeline('l_%s = environment.undefined(%r %% '
'included_template.__name__, '
'name=%r)' %
(alias, 'the template %%r (imported on %s) does '
'not export the requested name %s' % (
self.position(node),
repr(name)
), name))
self.outdent()
if frame.toplevel:
var_names.append(alias)
if not alias.startswith('_'):
discarded_names.append(alias)
frame.assigned_names.add(alias)
if var_names:
if len(var_names) == 1:
name = var_names[0]
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({%s})' % ', '.join(
'%r: l_%s' % (name, name) for name in var_names
))
if discarded_names:
if len(discarded_names) == 1:
self.writeline('context.exported_vars.discard(%r)' %
discarded_names[0])
else:
self.writeline('context.exported_vars.difference_'
'update((%s))' % ', '.join(map(repr, discarded_names)))
def visit_For(self, node, frame):
# when calculating the nodes for the inner frame we have to exclude
# the iterator contents from it
children = node.iter_child_nodes(exclude=('iter',))
if node.recursive:
loop_frame = self.function_scoping(node, frame, children,
find_special=False)
else:
loop_frame = frame.inner()
loop_frame.inspect(children)
# try to figure out if we have an extended loop. An extended loop
# is necessary if the loop is in recursive mode if the special loop
# variable is accessed in the body.
extended_loop = node.recursive or 'loop' in \
find_undeclared(node.iter_child_nodes(
only=('body',)), ('loop',))
# if we don't have an recursive loop we have to find the shadowed
# variables at that point. Because loops can be nested but the loop
# variable is a special one we have to enforce aliasing for it.
if not node.recursive:
aliases = self.push_scope(loop_frame, ('loop',))
# otherwise we set up a buffer and add a function def
else:
self.writeline('def loop(reciter, loop_render_func):', node)
self.indent()
self.buffer(loop_frame)
aliases = {}
# make sure the loop variable is a special one and raise a template
# assertion error if a loop tries to write to loop
if extended_loop:
loop_frame.identifiers.add_special('loop')
for name in node.find_all(nodes.Name):
if name.ctx == 'store' and name.name == 'loop':
self.fail('Can\'t assign to special loop variable '
'in for-loop target', name.lineno)
self.pull_locals(loop_frame)
if node.else_:
iteration_indicator = self.temporary_identifier()
self.writeline('%s = 1' % iteration_indicator)
# Create a fake parent loop if the else or test section of a
# loop is accessing the special loop variable and no parent loop
# exists.
if 'loop' not in aliases and 'loop' in find_undeclared(
node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
self.writeline("l_loop = environment.undefined(%r, name='loop')" %
("'loop' is undefined. the filter section of a loop as well "
"as the else block don't have access to the special 'loop'"
" variable of the current loop. Because there is no parent "
"loop it's undefined. Happened in loop on %s" %
self.position(node)))
self.writeline('for ', node)
self.visit(node.target, loop_frame)
self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
# if we have an extened loop and a node test, we filter in the
# "outer frame".
if extended_loop and node.test is not None:
self.write('(')
self.visit(node.target, loop_frame)
self.write(' for ')
self.visit(node.target, loop_frame)
self.write(' in ')
if node.recursive:
self.write('reciter')
else:
self.visit(node.iter, loop_frame)
self.write(' if (')
test_frame = loop_frame.copy()
self.visit(node.test, test_frame)
self.write('))')
elif node.recursive:
self.write('reciter')
else:
self.visit(node.iter, loop_frame)
if node.recursive:
self.write(', recurse=loop_render_func):')
else:
self.write(extended_loop and '):' or ':')
# tests in not extended loops become a continue
if not extended_loop and node.test is not None:
self.indent()
self.writeline('if not ')
self.visit(node.test, loop_frame)
self.write(':')
self.indent()
self.writeline('continue')
self.outdent(2)
self.indent()
self.blockvisit(node.body, loop_frame)
if node.else_:
self.writeline('%s = 0' % iteration_indicator)
self.outdent()
if node.else_:
self.writeline('if %s:' % iteration_indicator)
self.indent()
self.blockvisit(node.else_, loop_frame)
self.outdent()
# reset the aliases if there are any.
if not node.recursive:
self.pop_scope(aliases, loop_frame)
# if the node was recursive we have to return the buffer contents
# and start the iteration code
if node.recursive:
self.return_buffer_contents(loop_frame)
self.outdent()
self.start_write(frame, node)
self.write('loop(')
self.visit(node.iter, frame)
self.write(', loop)')
self.end_write(frame)
def visit_If(self, node, frame):
if_frame = frame.soft()
self.writeline('if ', node)
self.visit(node.test, if_frame)
self.write(':')
self.indent()
self.blockvisit(node.body, if_frame)
self.outdent()
if node.else_:
self.writeline('else:')
self.indent()
self.blockvisit(node.else_, if_frame)
self.outdent()
def visit_Macro(self, node, frame):
macro_frame = self.macro_body(node, frame)
self.newline()
if frame.toplevel:
if not node.name.startswith('_'):
self.write('context.exported_vars.add(%r)' % node.name)
self.writeline('context.vars[%r] = ' % node.name)
self.write('l_%s = ' % node.name)
self.macro_def(node, macro_frame)
frame.assigned_names.add(node.name)
def visit_CallBlock(self, node, frame):
children = node.iter_child_nodes(exclude=('call',))
call_frame = self.macro_body(node, frame, children)
self.writeline('caller = ')
self.macro_def(node, call_frame)
self.start_write(frame, node)
self.visit_Call(node.call, call_frame, forward_caller=True)
self.end_write(frame)
def visit_FilterBlock(self, node, frame):
filter_frame = frame.inner()
filter_frame.inspect(node.iter_child_nodes())
aliases = self.push_scope(filter_frame)
self.pull_locals(filter_frame)
self.buffer(filter_frame)
self.blockvisit(node.body, filter_frame)
self.start_write(frame, node)
self.visit_Filter(node.filter, filter_frame)
self.end_write(frame)
self.pop_scope(aliases, filter_frame)
def visit_ExprStmt(self, node, frame):
self.newline(node)
self.visit(node.node, frame)
def visit_Output(self, node, frame):
# if we have a known extends statement, we don't output anything
# if we are in a require_output_check section
if self.has_known_extends and frame.require_output_check:
return
if self.environment.finalize:
finalize = lambda x: unicode(self.environment.finalize(x))
else:
finalize = unicode
# if we are inside a frame that requires output checking, we do so
outdent_later = False
if frame.require_output_check:
self.writeline('if parent_template is None:')
self.indent()
outdent_later = True
# try to evaluate as many chunks as possible into a static
# string at compile time.
body = []
for child in node.nodes:
try:
const = child.as_const(frame.eval_ctx)
except nodes.Impossible:
body.append(child)
continue
# the frame can't be volatile here, becaus otherwise the
# as_const() function would raise an Impossible exception
# at that point.
try:
if frame.eval_ctx.autoescape:
if hasattr(const, '__html__'):
const = const.__html__()
else:
const = escape(const)
const = finalize(const)
except Exception:
# if something goes wrong here we evaluate the node
# at runtime for easier debugging
body.append(child)
continue
if body and isinstance(body[-1], list):
body[-1].append(const)
else:
body.append([const])
# if we have less than 3 nodes or a buffer we yield or extend/append
if len(body) < 3 or frame.buffer is not None:
if frame.buffer is not None:
# for one item we append, for more we extend
if len(body) == 1:
self.writeline('%s.append(' % frame.buffer)
else:
self.writeline('%s.extend((' % frame.buffer)
self.indent()
for item in body:
if isinstance(item, list):
val = repr(concat(item))
if frame.buffer is None:
self.writeline('yield ' + val)
else:
self.writeline(val + ', ')
else:
if frame.buffer is None:
self.writeline('yield ', item)
else:
self.newline(item)
close = 1
if frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' escape or to_string)(')
elif frame.eval_ctx.autoescape:
self.write('escape(')
else:
self.write('to_string(')
if self.environment.finalize is not None:
self.write('environment.finalize(')
close += 1
self.visit(item, frame)
self.write(')' * close)
if frame.buffer is not None:
self.write(', ')
if frame.buffer is not None:
# close the open parentheses
self.outdent()
self.writeline(len(body) == 1 and ')' or '))')
# otherwise we create a format string as this is faster in that case
else:
format = []
arguments = []
for item in body:
if isinstance(item, list):
format.append(concat(item).replace('%', '%%'))
else:
format.append('%s')
arguments.append(item)
self.writeline('yield ')
self.write(repr(concat(format)) + ' % (')
idx = -1
self.indent()
for argument in arguments:
self.newline(argument)
close = 0
if frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' escape or to_string)(')
close += 1
elif frame.eval_ctx.autoescape:
self.write('escape(')
close += 1
if self.environment.finalize is not None:
self.write('environment.finalize(')
close += 1
self.visit(argument, frame)
self.write(')' * close + ', ')
self.outdent()
self.writeline(')')
if outdent_later:
self.outdent()
def visit_Assign(self, node, frame):
self.newline(node)
# toplevel assignments however go into the local namespace and
# the current template's context. We create a copy of the frame
# here and add a set so that the Name visitor can add the assigned
# names here.
if frame.toplevel:
assignment_frame = frame.copy()
assignment_frame.toplevel_assignments = set()
else:
assignment_frame = frame
self.visit(node.target, assignment_frame)
self.write(' = ')
self.visit(node.node, frame)
# make sure toplevel assignments are added to the context.
if frame.toplevel:
public_names = [x for x in assignment_frame.toplevel_assignments
if not x.startswith('_')]
if len(assignment_frame.toplevel_assignments) == 1:
name = next(iter(assignment_frame.toplevel_assignments))
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({')
for idx, name in enumerate(assignment_frame.toplevel_assignments):
if idx:
self.write(', ')
self.write('%r: l_%s' % (name, name))
self.write('})')
if public_names:
if len(public_names) == 1:
self.writeline('context.exported_vars.add(%r)' %
public_names[0])
else:
self.writeline('context.exported_vars.update((%s))' %
', '.join(map(repr, public_names)))
# -- Expression Visitors
def visit_Name(self, node, frame):
if node.ctx == 'store' and frame.toplevel:
frame.toplevel_assignments.add(node.name)
self.write('l_' + node.name)
frame.assigned_names.add(node.name)
def visit_Const(self, node, frame):
val = node.value
if isinstance(val, float):
self.write(str(val))
else:
self.write(repr(val))
def visit_TemplateData(self, node, frame):
try:
self.write(repr(node.as_const(frame.eval_ctx)))
except nodes.Impossible:
self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)'
% node.data)
def visit_Tuple(self, node, frame):
self.write('(')
idx = -1
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item, frame)
self.write(idx == 0 and ',)' or ')')
def visit_List(self, node, frame):
self.write('[')
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item, frame)
self.write(']')
def visit_Dict(self, node, frame):
self.write('{')
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item.key, frame)
self.write(': ')
self.visit(item.value, frame)
self.write('}')
def binop(operator, interceptable=True):
def visitor(self, node, frame):
if self.environment.sandboxed and \
operator in self.environment.intercepted_binops:
self.write('environment.call_binop(context, %r, ' % operator)
self.visit(node.left, frame)
self.write(', ')
self.visit(node.right, frame)
else:
self.write('(')
self.visit(node.left, frame)
self.write(' %s ' % operator)
self.visit(node.right, frame)
self.write(')')
return visitor
def uaop(operator, interceptable=True):
def visitor(self, node, frame):
if self.environment.sandboxed and \
operator in self.environment.intercepted_unops:
self.write('environment.call_unop(context, %r, ' % operator)
self.visit(node.node, frame)
else:
self.write('(' + operator)
self.visit(node.node, frame)
self.write(')')
return visitor
visit_Add = binop('+')
visit_Sub = binop('-')
visit_Mul = binop('*')
visit_Div = binop('/')
visit_FloorDiv = binop('//')
visit_Pow = binop('**')
visit_Mod = binop('%')
visit_And = binop('and', interceptable=False)
visit_Or = binop('or', interceptable=False)
visit_Pos = uaop('+')
visit_Neg = uaop('-')
visit_Not = uaop('not ', interceptable=False)
del binop, uaop
def visit_Concat(self, node, frame):
if frame.eval_ctx.volatile:
func_name = '(context.eval_ctx.volatile and' \
' markup_join or unicode_join)'
elif frame.eval_ctx.autoescape:
func_name = 'markup_join'
else:
func_name = 'unicode_join'
self.write('%s((' % func_name)
for arg in node.nodes:
self.visit(arg, frame)
self.write(', ')
self.write('))')
def visit_Compare(self, node, frame):
self.visit(node.expr, frame)
for op in node.ops:
self.visit(op, frame)
def visit_Operand(self, node, frame):
self.write(' %s ' % operators[node.op])
self.visit(node.expr, frame)
def visit_Getattr(self, node, frame):
self.write('environment.getattr(')
self.visit(node.node, frame)
self.write(', %r)' % node.attr)
def visit_Getitem(self, node, frame):
# slices bypass the environment getitem method.
if isinstance(node.arg, nodes.Slice):
self.visit(node.node, frame)
self.write('[')
self.visit(node.arg, frame)
self.write(']')
else:
self.write('environment.getitem(')
self.visit(node.node, frame)
self.write(', ')
self.visit(node.arg, frame)
self.write(')')
def visit_Slice(self, node, frame):
if node.start is not None:
self.visit(node.start, frame)
self.write(':')
if node.stop is not None:
self.visit(node.stop, frame)
if node.step is not None:
self.write(':')
self.visit(node.step, frame)
def visit_Filter(self, node, frame):
self.write(self.filters[node.name] + '(')
func = self.environment.filters.get(node.name)
if func is None:
self.fail('no filter named %r' % node.name, node.lineno)
if getattr(func, 'contextfilter', False):
self.write('context, ')
elif getattr(func, 'evalcontextfilter', False):
self.write('context.eval_ctx, ')
elif getattr(func, 'environmentfilter', False):
self.write('environment, ')
# if the filter node is None we are inside a filter block
# and want to write to the current buffer
if node.node is not None:
self.visit(node.node, frame)
elif frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' Markup(concat(%s)) or concat(%s))' %
(frame.buffer, frame.buffer))
elif frame.eval_ctx.autoescape:
self.write('Markup(concat(%s))' % frame.buffer)
else:
self.write('concat(%s)' % frame.buffer)
self.signature(node, frame)
self.write(')')
def visit_Test(self, node, frame):
self.write(self.tests[node.name] + '(')
if node.name not in self.environment.tests:
self.fail('no test named %r' % node.name, node.lineno)
self.visit(node.node, frame)
self.signature(node, frame)
self.write(')')
def visit_CondExpr(self, node, frame):
def write_expr2():
if node.expr2 is not None:
return self.visit(node.expr2, frame)
self.write('environment.undefined(%r)' % ('the inline if-'
'expression on %s evaluated to false and '
'no else section was defined.' % self.position(node)))
if not have_condexpr:
self.write('((')
self.visit(node.test, frame)
self.write(') and (')
self.visit(node.expr1, frame)
self.write(',) or (')
write_expr2()
self.write(',))[0]')
else:
self.write('(')
self.visit(node.expr1, frame)
self.write(' if ')
self.visit(node.test, frame)
self.write(' else ')
write_expr2()
self.write(')')
def visit_Call(self, node, frame, forward_caller=False):
if self.environment.sandboxed:
self.write('environment.call(context, ')
else:
self.write('context.call(')
self.visit(node.node, frame)
extra_kwargs = forward_caller and {'caller': 'caller'} or None
self.signature(node, frame, extra_kwargs)
self.write(')')
def visit_Keyword(self, node, frame):
self.write(node.key + '=')
self.visit(node.value, frame)
# -- Unused nodes for extensions
def visit_MarkSafe(self, node, frame):
self.write('Markup(')
self.visit(node.expr, frame)
self.write(')')
def visit_MarkSafeIfAutoescape(self, node, frame):
self.write('(context.eval_ctx.autoescape and Markup or identity)(')
self.visit(node.expr, frame)
self.write(')')
def visit_EnvironmentAttribute(self, node, frame):
self.write('environment.' + node.name)
def visit_ExtensionAttribute(self, node, frame):
self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
def visit_ImportedName(self, node, frame):
self.write(self.import_aliases[node.importname])
def visit_InternalName(self, node, frame):
self.write(node.name)
def visit_ContextReference(self, node, frame):
self.write('context')
def visit_Continue(self, node, frame):
self.writeline('continue', node)
def visit_Break(self, node, frame):
self.writeline('break', node)
def visit_Scope(self, node, frame):
scope_frame = frame.inner()
scope_frame.inspect(node.iter_child_nodes())
aliases = self.push_scope(scope_frame)
self.pull_locals(scope_frame)
self.blockvisit(node.body, scope_frame)
self.pop_scope(aliases, scope_frame)
def visit_EvalContextModifier(self, node, frame):
for keyword in node.options:
self.writeline('context.eval_ctx.%s = ' % keyword.key)
self.visit(keyword.value, frame)
try:
val = keyword.value.as_const(frame.eval_ctx)
except nodes.Impossible:
frame.eval_ctx.volatile = True
else:
setattr(frame.eval_ctx, keyword.key, val)
def visit_ScopedEvalContextModifier(self, node, frame):
old_ctx_name = self.temporary_identifier()
safed_ctx = frame.eval_ctx.save()
self.writeline('%s = context.eval_ctx.save()' % old_ctx_name)
self.visit_EvalContextModifier(node, frame)
for child in node.body:
self.visit(child, frame)
frame.eval_ctx.revert(safed_ctx)
self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.optimizer
~~~~~~~~~~~~~~~~
The jinja optimizer is currently trying to constant fold a few expressions
and modify the AST in place so that it should be easier to evaluate it.
Because the AST does not contain all the scoping information and the
compiler has to find that out, we cannot do all the optimizations we
want. For example loop unrolling doesn't work because unrolled loops would
have a different scoping.
The solution would be a second syntax tree that has the scoping rules stored.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from jinja2 import nodes
from jinja2.visitor import NodeTransformer
def optimize(node, environment):
"""The context hint can be used to perform an static optimization
based on the context given."""
optimizer = Optimizer(environment)
return optimizer.visit(node)
class Optimizer(NodeTransformer):
def __init__(self, environment):
self.environment = environment
def visit_If(self, node):
"""Eliminate dead code."""
# do not optimize ifs that have a block inside so that it doesn't
# break super().
if node.find(nodes.Block) is not None:
return self.generic_visit(node)
try:
val = self.visit(node.test).as_const()
except nodes.Impossible:
return self.generic_visit(node)
if val:
body = node.body
else:
body = node.else_
result = []
for node in body:
result.extend(self.visit_list(node))
return result
def fold(self, node):
"""Do constant folding."""
node = self.generic_visit(node)
try:
return nodes.Const.from_untrusted(node.as_const(),
lineno=node.lineno,
environment=self.environment)
except nodes.Impossible:
return node
visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \
visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \
visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \
visit_Filter = visit_Test = visit_CondExpr = fold
del fold
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.utils
~~~~~~~~~~~~
Utility functions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import sys
import errno
try:
from thread import allocate_lock
except ImportError:
from dummy_thread import allocate_lock
from collections import deque
from itertools import imap
_word_split_re = re.compile(r'(\s+)')
_punctuation_re = re.compile(
'^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (
'|'.join(imap(re.escape, ('(', '<', '<'))),
'|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))
)
)
_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
_digits = '0123456789'
# special singleton representing missing values for the runtime
missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
# internal code
internal_code = set()
# concatenate a list of strings and convert them to unicode.
# unfortunately there is a bug in python 2.4 and lower that causes
# unicode.join trash the traceback.
_concat = u''.join
try:
def _test_gen_bug():
raise TypeError(_test_gen_bug)
yield None
_concat(_test_gen_bug())
except TypeError, _error:
if not _error.args or _error.args[0] is not _test_gen_bug:
def concat(gen):
try:
return _concat(list(gen))
except Exception:
# this hack is needed so that the current frame
# does not show up in the traceback.
exc_type, exc_value, tb = sys.exc_info()
raise exc_type, exc_value, tb.tb_next
else:
concat = _concat
del _test_gen_bug, _error
# for python 2.x we create outselves a next() function that does the
# basics without exception catching.
try:
next = next
except NameError:
def next(x):
return x.next()
# if this python version is unable to deal with unicode filenames
# when passed to encode we let this function encode it properly.
# This is used in a couple of places. As far as Jinja is concerned
# filenames are unicode *or* bytestrings in 2.x and unicode only in
# 3.x because compile cannot handle bytes
if sys.version_info < (3, 0):
def _encode_filename(filename):
if isinstance(filename, unicode):
return filename.encode('utf-8')
return filename
else:
def _encode_filename(filename):
assert filename is None or isinstance(filename, str), \
'filenames must be strings'
return filename
from keyword import iskeyword as is_python_keyword
# common types. These do exist in the special types module too which however
# does not exist in IronPython out of the box. Also that way we don't have
# to deal with implementation specific stuff here
class _C(object):
def method(self): pass
def _func():
yield None
FunctionType = type(_func)
GeneratorType = type(_func())
MethodType = type(_C.method)
CodeType = type(_C.method.func_code)
try:
raise TypeError()
except TypeError:
_tb = sys.exc_info()[2]
TracebackType = type(_tb)
FrameType = type(_tb.tb_frame)
del _C, _tb, _func
def contextfunction(f):
"""This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this::
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars)
"""
f.contextfunction = True
return f
def evalcontextfunction(f):
"""This decoraotr can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfunction = True
return f
def environmentfunction(f):
"""This decorator can be used to mark a function or method as environment
callable. This decorator works exactly like the :func:`contextfunction`
decorator just that the first argument is the active :class:`Environment`
and not context.
"""
f.environmentfunction = True
return f
def internalcode(f):
"""Marks the function as internally used"""
internal_code.add(f.func_code)
return f
def is_undefined(obj):
"""Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
def default(var, default=''):
if is_undefined(var):
return default
return var
"""
from jinja2.runtime import Undefined
return isinstance(obj, Undefined)
def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass
def clear_caches():
"""Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
messuring memory consumption you may want to clean the caches.
"""
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
def import_string(import_name, silent=False):
"""Imports an object based on a string. This use useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
def open_if_exists(filename, mode='rb'):
"""Returns a file descriptor for the filename if that file exists,
otherwise `None`.
"""
try:
return open(filename, mode)
except IOError, e:
if e.errno not in (errno.ENOENT, errno.EISDIR):
raise
def object_type_repr(obj):
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return 'None'
elif obj is Ellipsis:
return 'Ellipsis'
# __builtin__ in 2.x, builtins in 3.x
if obj.__class__.__module__ in ('__builtin__', 'builtins'):
name = obj.__class__.__name__
else:
name = obj.__class__.__module__ + '.' + obj.__class__.__name__
return '%s object' % name
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj)
def urlize(text, trim_url_limit=None, nofollow=False):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None \
and (x[:limit] + (len(x) >=limit and '...'
or '')) or x
words = _word_split_re.split(unicode(escape(text)))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
for i, word in enumerate(words):
match = _punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('www.') or (
'@' not in middle and
not middle.startswith('http://') and
len(middle) > 0 and
middle[0] in _letters + _digits and (
middle.endswith('.org') or
middle.endswith('.net') or
middle.endswith('.com')
)):
middle = '<a href="http://%s"%s>%s</a>' % (middle,
nofollow_attr, trim_url(middle))
if middle.startswith('http://') or \
middle.startswith('https://'):
middle = '<a href="%s"%s>%s</a>' % (middle,
nofollow_attr, trim_url(middle))
if '@' in middle and not middle.startswith('www.') and \
not ':' in middle and _simple_email_re.match(middle):
middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return u''.join(words)
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
"""Generate some lorem impsum for the template."""
from jinja2.constants import LOREM_IPSUM_WORDS
from random import choice, randrange
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in xrange(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(xrange(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ','
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += '.'
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p = u' '.join(p)
if p.endswith(','):
p = p[:-1] + '.'
elif not p.endswith('.'):
p += '.'
result.append(p)
if not html:
return u'\n\n'.join(result)
return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
class LRUCache(object):
"""A simple LRU Cache implementation."""
# this is fast for small capacities (something below 1000) but doesn't
# scale. But as long as it's only used as storage for templates this
# won't do any harm.
def __init__(self, capacity):
self.capacity = capacity
self._mapping = {}
self._queue = deque()
self._postinit()
def _postinit(self):
# alias all queue methods for faster lookup
self._popleft = self._queue.popleft
self._pop = self._queue.pop
if hasattr(self._queue, 'remove'):
self._remove = self._queue.remove
self._wlock = allocate_lock()
self._append = self._queue.append
def _remove(self, obj):
"""Python 2.4 compatibility."""
for idx, item in enumerate(self._queue):
if item == obj:
del self._queue[idx]
break
def __getstate__(self):
return {
'capacity': self.capacity,
'_mapping': self._mapping,
'_queue': self._queue
}
def __setstate__(self, d):
self.__dict__.update(d)
self._postinit()
def __getnewargs__(self):
return (self.capacity,)
def copy(self):
"""Return an shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv
def get(self, key, default=None):
"""Return an item from the cache dict or `default`"""
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
try:
return self[key]
except KeyError:
self[key] = default
return default
def clear(self):
"""Clear the cache."""
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release()
def __contains__(self, key):
"""Check if a key exists in this cache."""
return key in self._mapping
def __len__(self):
"""Return the current size of the cache."""
return len(self._mapping)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self._mapping
)
def __getitem__(self, key):
"""Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise an `KeyError` if it does not exist.
"""
rv = self._mapping[key]
if self._queue[-1] != key:
try:
self._remove(key)
except ValueError:
# if something removed the key from the container
# when we read, ignore the ValueError that we would
# get otherwise.
pass
self._append(key)
return rv
def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
try:
self._remove(key)
except ValueError:
# __getitem__ is not locked, it might happen
pass
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release()
def __delitem__(self, key):
"""Remove an item from the cache dict.
Raise an `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
del self._mapping[key]
try:
self._remove(key)
except ValueError:
# __getitem__ is not locked, it might happen
pass
finally:
self._wlock.release()
def items(self):
"""Return a list of items."""
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result
def iteritems(self):
"""Iterate over all items."""
return iter(self.items())
def values(self):
"""Return a list of all values."""
return [x[1] for x in self.items()]
def itervalue(self):
"""Iterate over all values."""
return iter(self.values())
def keys(self):
"""Return a list of all keys ordered by most recent usage."""
return list(self)
def iterkeys(self):
"""Iterate over all keys in the cache dict, ordered by
the most recent usage.
"""
return reversed(tuple(self._queue))
__iter__ = iterkeys
def __reversed__(self):
"""Iterate over the values in the cache dict, oldest items
coming first.
"""
return iter(tuple(self._queue))
__copy__ = copy
# register the LRU cache as mutable mapping if possible
try:
from collections import MutableMapping
MutableMapping.register(LRUCache)
except ImportError:
pass
class Cycler(object):
"""A cycle helper for templates."""
def __init__(self, *items):
if not items:
raise RuntimeError('at least one item has to be provided')
self.items = items
self.reset()
def reset(self):
"""Resets the cycle."""
self.pos = 0
@property
def current(self):
"""Returns the current item."""
return self.items[self.pos]
def next(self):
"""Goes one item ahead and returns it."""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv
class Joiner(object):
"""A joining helper for templates."""
def __init__(self, sep=u', '):
self.sep = sep
self.used = False
def __call__(self):
if not self.used:
self.used = True
return u''
return self.sep
# try markupsafe first, if that fails go with Jinja2's bundled version
# of markupsafe. Markupsafe was previously Jinja2's implementation of
# the Markup object but was moved into a separate package in a patchleve
# release
try:
from markupsafe import Markup, escape, soft_unicode
except ImportError:
from jinja2._markupsafe import Markup, escape, soft_unicode
# partials
try:
from functools import partial
except ImportError:
class partial(object):
def __init__(self, _func, *args, **kwargs):
self._func = _func
self._args = args
self._kwargs = kwargs
def __call__(self, *args, **kwargs):
kwargs.update(self._kwargs)
return self._func(*(self._args + args), **kwargs)
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.ext
~~~~~~~~~~
Jinja extensions allow to add custom tags similar to the way django custom
tags work. By default two example extensions exist: an i18n and a cache
extension.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from collections import deque
from jinja2 import nodes
from jinja2.defaults import *
from jinja2.environment import Environment
from jinja2.runtime import Undefined, concat
from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
from jinja2.utils import contextfunction, import_string, Markup, next
# the only real useful gettext functions for a Jinja template. Note
# that ugettext must be assigned to gettext as Jinja doesn't support
# non unicode strings.
GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
class ExtensionRegistry(type):
"""Gives the extension an unique identifier."""
def __new__(cls, name, bases, d):
rv = type.__new__(cls, name, bases, d)
rv.identifier = rv.__module__ + '.' + rv.__name__
return rv
class Extension(object):
"""Extensions can be used to add extra functionality to the Jinja template
system at the parser level. Custom extensions are bound to an environment
but may not store environment specific data on `self`. The reason for
this is that an extension can be bound to another environment (for
overlays) by creating a copy and reassigning the `environment` attribute.
As extensions are created by the environment they cannot accept any
arguments for configuration. One may want to work around that by using
a factory function, but that is not possible as extensions are identified
by their import name. The correct way to configure the extension is
storing the configuration values on the environment. Because this way the
environment ends up acting as central configuration storage the
attributes may clash which is why extensions have to ensure that the names
they choose for configuration are not too generic. ``prefix`` for example
is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
name as includes the name of the extension (fragment cache).
"""
__metaclass__ = ExtensionRegistry
#: if this extension parses this is the list of tags it's listening to.
tags = set()
#: the priority of that extension. This is especially useful for
#: extensions that preprocess values. A lower value means higher
#: priority.
#:
#: .. versionadded:: 2.4
priority = 100
def __init__(self, environment):
self.environment = environment
def bind(self, environment):
"""Create a copy of this extension bound to another environment."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.environment = environment
return rv
def preprocess(self, source, name, filename=None):
"""This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source.
"""
return source
def filter_stream(self, stream):
"""It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
to filter tokens returned. This method has to return an iterable of
:class:`~jinja2.lexer.Token`\s, but it doesn't have to return a
:class:`~jinja2.lexer.TokenStream`.
In the `ext` folder of the Jinja2 source distribution there is a file
called `inlinegettext.py` which implements a filter that utilizes this
method.
"""
return stream
def parse(self, parser):
"""If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes.
"""
raise NotImplementedError()
def attr(self, name, lineno=None):
"""Return an attribute node for the current extension. This is useful
to pass constants on extensions to generated template code.
::
self.attr('_my_attribute', lineno=lineno)
"""
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
def call_method(self, name, args=None, kwargs=None, dyn_args=None,
dyn_kwargs=None, lineno=None):
"""Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`.
"""
if args is None:
args = []
if kwargs is None:
kwargs = []
return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
dyn_args, dyn_kwargs, lineno=lineno)
@contextfunction
def _gettext_alias(__context, *args, **kwargs):
return __context.call(__context.resolve('gettext'), *args, **kwargs)
def _make_new_gettext(func):
@contextfunction
def gettext(__context, __string, **variables):
rv = __context.call(func, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
return rv % variables
return gettext
def _make_new_ngettext(func):
@contextfunction
def ngettext(__context, __singular, __plural, __num, **variables):
variables.setdefault('num', __num)
rv = __context.call(func, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
return rv % variables
return ngettext
class InternationalizationExtension(Extension):
"""This extension adds gettext support to Jinja2."""
tags = set(['trans'])
# TODO: the i18n extension is currently reevaluating values in a few
# situations. Take this example:
# {% trans count=something() %}{{ count }} foo{% pluralize
# %}{{ count }} fooss{% endtrans %}
# something is called twice here. One time for the gettext value and
# the other time for the n-parameter of the ngettext function.
def __init__(self, environment):
Extension.__init__(self, environment)
environment.globals['_'] = _gettext_alias
environment.extend(
install_gettext_translations=self._install,
install_null_translations=self._install_null,
install_gettext_callables=self._install_callables,
uninstall_gettext_translations=self._uninstall,
extract_translations=self._extract,
newstyle_gettext=False
)
def _install(self, translations, newstyle=None):
gettext = getattr(translations, 'ugettext', None)
if gettext is None:
gettext = translations.gettext
ngettext = getattr(translations, 'ungettext', None)
if ngettext is None:
ngettext = translations.ngettext
self._install_callables(gettext, ngettext, newstyle)
def _install_null(self, newstyle=None):
self._install_callables(
lambda x: x,
lambda s, p, n: (n != 1 and (p,) or (s,))[0],
newstyle
)
def _install_callables(self, gettext, ngettext, newstyle=None):
if newstyle is not None:
self.environment.newstyle_gettext = newstyle
if self.environment.newstyle_gettext:
gettext = _make_new_gettext(gettext)
ngettext = _make_new_ngettext(ngettext)
self.environment.globals.update(
gettext=gettext,
ngettext=ngettext
)
def _uninstall(self, translations):
for key in 'gettext', 'ngettext':
self.environment.globals.pop(key, None)
def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
if isinstance(source, basestring):
source = self.environment.parse(source)
return extract_from_ast(source, gettext_functions)
def parse(self, parser):
"""Parse a translatable tag."""
lineno = next(parser.stream).lineno
num_called_num = False
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
plural_expr = None
variables = {}
while parser.stream.current.type != 'block_end':
if variables:
parser.stream.expect('comma')
# skip colon for python compatibility
if parser.stream.skip_if('colon'):
break
name = parser.stream.expect('name')
if name.value in variables:
parser.fail('translatable variable %r defined twice.' %
name.value, name.lineno,
exc=TemplateAssertionError)
# expressions
if parser.stream.current.type == 'assign':
next(parser.stream)
variables[name.value] = var = parser.parse_expression()
else:
variables[name.value] = var = nodes.Name(name.value, 'load')
if plural_expr is None:
plural_expr = var
num_called_num = name.value == 'num'
parser.stream.expect('block_end')
plural = plural_names = None
have_plural = False
referenced = set()
# now parse until endtrans or pluralize
singular_names, singular = self._parse_block(parser, True)
if singular_names:
referenced.update(singular_names)
if plural_expr is None:
plural_expr = nodes.Name(singular_names[0], 'load')
num_called_num = singular_names[0] == 'num'
# if we have a pluralize block, we parse that too
if parser.stream.current.test('name:pluralize'):
have_plural = True
next(parser.stream)
if parser.stream.current.type != 'block_end':
name = parser.stream.expect('name')
if name.value not in variables:
parser.fail('unknown variable %r for pluralization' %
name.value, name.lineno,
exc=TemplateAssertionError)
plural_expr = variables[name.value]
num_called_num = name.value == 'num'
parser.stream.expect('block_end')
plural_names, plural = self._parse_block(parser, False)
next(parser.stream)
referenced.update(plural_names)
else:
next(parser.stream)
# register free names as simple name expressions
for var in referenced:
if var not in variables:
variables[var] = nodes.Name(var, 'load')
if not have_plural:
plural_expr = None
elif plural_expr is None:
parser.fail('pluralize without variables', lineno)
node = self._make_node(singular, plural, variables, plural_expr,
bool(referenced),
num_called_num and have_plural)
node.set_lineno(lineno)
return node
def _parse_block(self, parser, allow_pluralize):
"""Parse until the next block tag with a given name."""
referenced = []
buf = []
while 1:
if parser.stream.current.type == 'data':
buf.append(parser.stream.current.value.replace('%', '%%'))
next(parser.stream)
elif parser.stream.current.type == 'variable_begin':
next(parser.stream)
name = parser.stream.expect('name').value
referenced.append(name)
buf.append('%%(%s)s' % name)
parser.stream.expect('variable_end')
elif parser.stream.current.type == 'block_begin':
next(parser.stream)
if parser.stream.current.test('name:endtrans'):
break
elif parser.stream.current.test('name:pluralize'):
if allow_pluralize:
break
parser.fail('a translatable section can have only one '
'pluralize section')
parser.fail('control structures in translatable sections are '
'not allowed')
elif parser.stream.eos:
parser.fail('unclosed translation block')
else:
assert False, 'internal parser error'
return referenced, concat(buf)
def _make_node(self, singular, plural, variables, plural_expr,
vars_referenced, num_called_num):
"""Generates a useful node from the data provided."""
# no variables referenced? no need to escape for old style
# gettext invocations only if there are vars.
if not vars_referenced and not self.environment.newstyle_gettext:
singular = singular.replace('%%', '%')
if plural:
plural = plural.replace('%%', '%')
# singular only:
if plural_expr is None:
gettext = nodes.Name('gettext', 'load')
node = nodes.Call(gettext, [nodes.Const(singular)],
[], None, None)
# singular and plural
else:
ngettext = nodes.Name('ngettext', 'load')
node = nodes.Call(ngettext, [
nodes.Const(singular),
nodes.Const(plural),
plural_expr
], [], None, None)
# in case newstyle gettext is used, the method is powerful
# enough to handle the variable expansion and autoescape
# handling itself
if self.environment.newstyle_gettext:
for key, value in variables.iteritems():
# the function adds that later anyways in case num was
# called num, so just skip it.
if num_called_num and key == 'num':
continue
node.kwargs.append(nodes.Keyword(key, value))
# otherwise do that here
else:
# mark the return value as safe if we are in an
# environment with autoescaping turned on
node = nodes.MarkSafeIfAutoescape(node)
if variables:
node = nodes.Mod(node, nodes.Dict([
nodes.Pair(nodes.Const(key), value)
for key, value in variables.items()
]))
return nodes.Output([node])
class ExprStmtExtension(Extension):
"""Adds a `do` tag to Jinja2 that works like the print statement just
that it doesn't print the return value.
"""
tags = set(['do'])
def parse(self, parser):
node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
node.node = parser.parse_tuple()
return node
class LoopControlExtension(Extension):
"""Adds break and continue to the template engine."""
tags = set(['break', 'continue'])
def parse(self, parser):
token = next(parser.stream)
if token.value == 'break':
return nodes.Break(lineno=token.lineno)
return nodes.Continue(lineno=token.lineno)
class WithExtension(Extension):
"""Adds support for a django-like with block."""
tags = set(['with'])
def parse(self, parser):
node = nodes.Scope(lineno=next(parser.stream).lineno)
assignments = []
while parser.stream.current.type != 'block_end':
lineno = parser.stream.current.lineno
if assignments:
parser.stream.expect('comma')
target = parser.parse_assign_target()
parser.stream.expect('assign')
expr = parser.parse_expression()
assignments.append(nodes.Assign(target, expr, lineno=lineno))
node.body = assignments + \
list(parser.parse_statements(('name:endwith',),
drop_needle=True))
return node
class AutoEscapeExtension(Extension):
"""Changes auto escape rules for a scope."""
tags = set(['autoescape'])
def parse(self, parser):
node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)
node.options = [
nodes.Keyword('autoescape', parser.parse_expression())
]
node.body = parser.parse_statements(('name:endautoescape',),
drop_needle=True)
return nodes.Scope([node])
def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
babel_style=True):
"""Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`. This
allows Babel to figure out what you really meant if you are using
gettext functions that allow keyword arguments for placeholder expansion.
If you don't want that behavior set the `babel_style` parameter to `False`
which causes only strings to be returned and parameters are always stored
in tuples. As a consequence invalid gettext calls (calls without a single
string parameter or string parameters after non-string parameters) are
skipped.
This example explains the behavior:
>>> from jinja2 import Environment
>>> env = Environment()
>>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
>>> list(extract_from_ast(node))
[(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
>>> list(extract_from_ast(node, babel_style=False))
[(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
For every string found this function yields a ``(lineno, function,
message)`` tuple, where:
* ``lineno`` is the number of the line on which the string was found,
* ``function`` is the name of the ``gettext`` function used (if the
string was extracted from embedded Python code), and
* ``message`` is the string itself (a ``unicode`` object, or a tuple
of ``unicode`` objects for functions with multiple string arguments).
This extraction function operates on the AST and is because of that unable
to extract any comments. For comment support you have to use the babel
extraction interface or extract comments yourself.
"""
for node in node.find_all(nodes.Call):
if not isinstance(node.node, nodes.Name) or \
node.node.name not in gettext_functions:
continue
strings = []
for arg in node.args:
if isinstance(arg, nodes.Const) and \
isinstance(arg.value, basestring):
strings.append(arg.value)
else:
strings.append(None)
for arg in node.kwargs:
strings.append(None)
if node.dyn_args is not None:
strings.append(None)
if node.dyn_kwargs is not None:
strings.append(None)
if not babel_style:
strings = tuple(x for x in strings if x is not None)
if not strings:
continue
else:
if len(strings) == 1:
strings = strings[0]
else:
strings = tuple(strings)
yield node.lineno, node.node.name, strings
class _CommentFinder(object):
"""Helper class to find comments in a token stream. Can only
find comments for gettext calls forwards. Once the comment
from line 4 is found, a comment for line 1 will not return a
usable value.
"""
def __init__(self, tokens, comment_tags):
self.tokens = tokens
self.comment_tags = comment_tags
self.offset = 0
self.last_lineno = 0
def find_backwards(self, offset):
try:
for _, token_type, token_value in \
reversed(self.tokens[self.offset:offset]):
if token_type in ('comment', 'linecomment'):
try:
prefix, comment = token_value.split(None, 1)
except ValueError:
continue
if prefix in self.comment_tags:
return [comment.rstrip()]
return []
finally:
self.offset = offset
def find_comments(self, lineno):
if not self.comment_tags or self.last_lineno > lineno:
return []
for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):
if token_lineno > lineno:
return self.find_backwards(self.offset + idx)
return self.find_backwards(len(self.tokens))
def babel_extract(fileobj, keywords, comment_tags, options):
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
"""
extensions = set()
for extension in options.get('extensions', '').split(','):
extension = extension.strip()
if not extension:
continue
extensions.add(import_string(extension))
if InternationalizationExtension not in extensions:
extensions.add(InternationalizationExtension)
def getbool(options, key, default=False):
options.get(key, str(default)).lower() in ('1', 'on', 'yes', 'true')
environment = Environment(
options.get('block_start_string', BLOCK_START_STRING),
options.get('block_end_string', BLOCK_END_STRING),
options.get('variable_start_string', VARIABLE_START_STRING),
options.get('variable_end_string', VARIABLE_END_STRING),
options.get('comment_start_string', COMMENT_START_STRING),
options.get('comment_end_string', COMMENT_END_STRING),
options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
getbool(options, 'trim_blocks', TRIM_BLOCKS),
NEWLINE_SEQUENCE, frozenset(extensions),
cache_size=0,
auto_reload=False
)
if getbool(options, 'newstyle_gettext'):
environment.newstyle_gettext = True
source = fileobj.read().decode(options.get('encoding', 'utf-8'))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError, e:
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno)
#: nicer import names
i18n = InternationalizationExtension
do = ExprStmtExtension
loopcontrols = LoopControlExtension
with_ = WithExtension
autoescape = AutoEscapeExtension
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.visitor
~~~~~~~~~~~~~~
This module implements a visitor for the nodes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from jinja2.nodes import Node
class NodeVisitor(object):
"""Walks the abstract syntax tree and call visitor functions for every
node found. The visitor functions may return values which will be
forwarded by the `visit` method.
Per default the visitor functions for the nodes are ``'visit_'`` +
class name of the node. So a `TryFinally` node visit function would
be `visit_TryFinally`. This behavior can be changed by overriding
the `get_visitor` function. If no visitor function exists for a node
(return value `None`) the `generic_visit` visitor is used instead.
"""
def get_visitor(self, node):
"""Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead.
"""
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None)
def visit(self, node, *args, **kwargs):
"""Visit a node."""
f = self.get_visitor(node)
if f is not None:
return f(node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
def generic_visit(self, node, *args, **kwargs):
"""Called if no explicit visitor function exists for a node."""
for node in node.iter_child_nodes():
self.visit(node, *args, **kwargs)
class NodeTransformer(NodeVisitor):
"""Walks the abstract syntax tree and allows modifications of nodes.
The `NodeTransformer` will walk the AST and use the return value of the
visitor functions to replace or remove the old node. If the return
value of the visitor function is `None` the node will be removed
from the previous location otherwise it's replaced with the return
value. The return value may be the original node in which case no
replacement takes place.
"""
def generic_visit(self, node, *args, **kwargs):
for field, old_value in node.iter_fields():
if isinstance(old_value, list):
new_values = []
for value in old_value:
if isinstance(value, Node):
value = self.visit(value, *args, **kwargs)
if value is None:
continue
elif not isinstance(value, Node):
new_values.extend(value)
continue
new_values.append(value)
old_value[:] = new_values
elif isinstance(old_value, Node):
new_node = self.visit(old_value, *args, **kwargs)
if new_node is None:
delattr(node, field)
else:
setattr(node, field, new_node)
return node
def visit_list(self, node, *args, **kwargs):
"""As transformers may return lists in some places this method
can be used to enforce a list as return value.
"""
rv = self.visit(node, *args, **kwargs)
if not isinstance(rv, list):
rv = [rv]
return rv
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.parser
~~~~~~~~~~~~~
Implements the template parser.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
from jinja2.utils import next
from jinja2.lexer import describe_token, describe_token_expr
#: statements that callinto
_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
'macro', 'include', 'from', 'import',
'set'])
_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])
class Parser(object):
"""This is the central parsing class Jinja2 uses. It's passed to
extensions and can be used to parse expressions or statements.
"""
def __init__(self, environment, source, name=None, filename=None,
state=None):
self.environment = environment
self.stream = environment._tokenize(source, name, filename, state)
self.name = name
self.filename = filename
self.closed = False
self.extensions = {}
for extension in environment.iter_extensions():
for tag in extension.tags:
self.extensions[tag] = extension.parse
self._last_identifier = 0
self._tag_stack = []
self._end_token_stack = []
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename)
def _fail_ut_eof(self, name, end_token_stack, lineno):
expected = []
for exprs in end_token_stack:
expected.extend(map(describe_token_expr, exprs))
if end_token_stack:
currently_looking = ' or '.join(
"'%s'" % describe_token_expr(expr)
for expr in end_token_stack[-1])
else:
currently_looking = None
if name is None:
message = ['Unexpected end of template.']
else:
message = ['Encountered unknown tag \'%s\'.' % name]
if currently_looking:
if name is not None and name in expected:
message.append('You probably made a nesting mistake. Jinja '
'is expecting this tag, but currently looking '
'for %s.' % currently_looking)
else:
message.append('Jinja was looking for the following tags: '
'%s.' % currently_looking)
if self._tag_stack:
message.append('The innermost block that needs to be '
'closed is \'%s\'.' % self._tag_stack[-1])
self.fail(' '.join(message), lineno)
def fail_unknown_tag(self, name, lineno=None):
"""Called if the parser encounters an unknown tag. Tries to fail
with a human readable error message that could help to identify
the problem.
"""
return self._fail_ut_eof(name, self._end_token_stack, lineno)
def fail_eof(self, end_tokens=None, lineno=None):
"""Like fail_unknown_tag but for end of template situations."""
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno)
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return False
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv
def parse_statement(self):
"""Parse a single statement."""
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _statement_keywords:
return getattr(self, 'parse_' + self.stream.current.value)()
if token.value == 'call':
return self.parse_call_block()
if token.value == 'filter':
return self.parse_filter_block()
ext = self.extensions.get(token.value)
if ext is not None:
return ext(self)
# did not work out, remove the token we pushed by accident
# from the stack so that the unknown tag fail function can
# produce a proper error message.
self._tag_stack.pop()
pop_tag = False
self.fail_unknown_tag(token.value, token.lineno)
finally:
if pop_tag:
self._tag_stack.pop()
def parse_statements(self, end_tokens, drop_needle=False):
"""Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
"""
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort of end of statement token and parsing those here.
self.stream.expect('block_end')
result = self.subparse(end_tokens)
# we reached the end of the template too early, the subparser
# does not check for this, so we do that now
if self.stream.current.type == 'eof':
self.fail_eof(end_tokens)
if drop_needle:
next(self.stream)
return result
def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target()
self.stream.expect('assign')
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno)
def parse_if(self):
"""Parse an if construct."""
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
'name:endif'))
token = next(self.stream)
if token.test('name:elif'):
new_node = nodes.If(lineno=self.stream.current.lineno)
node.else_ = [new_node]
node = new_node
continue
elif token.test('name:else'):
node.else_ = self.parse_statements(('name:endif',),
drop_needle=True)
else:
node.else_ = []
break
return result
def parse_block(self):
node = nodes.Block(lineno=next(self.stream).lineno)
node.name = self.stream.expect('name').value
node.scoped = self.stream.skip_if('name:scoped')
# common problem people encounter when switching from django
# to jinja. we do not support hyphens in block names, so let's
# raise a nicer error message in that case.
if self.stream.current.type == 'sub':
self.fail('Block names in Jinja have to be valid Python '
'identifiers and may not contain hypens, use an '
'underscore instead.')
node.body = self.parse_statements(('name:endblock',), drop_needle=True)
self.stream.skip_if('name:' + node.name)
return node
def parse_extends(self):
node = nodes.Extends(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
return node
def parse_import_context(self, node, default):
if self.stream.current.test_any('name:with', 'name:without') and \
self.stream.look().test('name:context'):
node.with_context = next(self.stream).value == 'with'
self.stream.skip()
else:
node.with_context = default
return node
def parse_include(self):
node = nodes.Include(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
if self.stream.current.test('name:ignore') and \
self.stream.look().test('name:missing'):
node.ignore_missing = True
self.stream.skip(2)
else:
node.ignore_missing = False
return self.parse_import_context(node, True)
def parse_import(self):
node = nodes.Import(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
self.stream.expect('name:as')
node.target = self.parse_assign_target(name_only=True).name
return self.parse_import_context(node, False)
def parse_from(self):
node = nodes.FromImport(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
self.stream.expect('name:import')
node.names = []
def parse_context():
if self.stream.current.value in ('with', 'without') and \
self.stream.look().test('name:context'):
node.with_context = next(self.stream).value == 'with'
self.stream.skip()
return True
return False
while 1:
if node.names:
self.stream.expect('comma')
if self.stream.current.type == 'name':
if parse_context():
break
target = self.parse_assign_target(name_only=True)
if target.name.startswith('_'):
self.fail('names starting with an underline can not '
'be imported', target.lineno,
exc=TemplateAssertionError)
if self.stream.skip_if('name:as'):
alias = self.parse_assign_target(name_only=True)
node.names.append((target.name, alias.name))
else:
node.names.append(target.name)
if parse_context() or self.stream.current.type != 'comma':
break
else:
break
if not hasattr(node, 'with_context'):
node.with_context = False
self.stream.skip_if('comma')
return node
def parse_signature(self, node):
node.args = args = []
node.defaults = defaults = []
self.stream.expect('lparen')
while self.stream.current.type != 'rparen':
if args:
self.stream.expect('comma')
arg = self.parse_assign_target(name_only=True)
arg.set_ctx('param')
if self.stream.skip_if('assign'):
defaults.append(self.parse_expression())
args.append(arg)
self.stream.expect('rparen')
def parse_call_block(self):
node = nodes.CallBlock(lineno=next(self.stream).lineno)
if self.stream.current.type == 'lparen':
self.parse_signature(node)
else:
node.args = []
node.defaults = []
node.call = self.parse_expression()
if not isinstance(node.call, nodes.Call):
self.fail('expected call', node.lineno)
node.body = self.parse_statements(('name:endcall',), drop_needle=True)
return node
def parse_filter_block(self):
node = nodes.FilterBlock(lineno=next(self.stream).lineno)
node.filter = self.parse_filter(None, start_inline=True)
node.body = self.parse_statements(('name:endfilter',),
drop_needle=True)
return node
def parse_macro(self):
node = nodes.Macro(lineno=next(self.stream).lineno)
node.name = self.parse_assign_target(name_only=True).name
self.parse_signature(node)
node.body = self.parse_statements(('name:endmacro',),
drop_needle=True)
return node
def parse_print(self):
node = nodes.Output(lineno=next(self.stream).lineno)
node.nodes = []
while self.stream.current.type != 'block_end':
if node.nodes:
self.stream.expect('comma')
node.nodes.append(self.parse_expression())
return node
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function.
"""
if name_only:
token = self.stream.expect('name')
target = nodes.Name(token.value, 'store', lineno=token.lineno)
else:
if with_tuple:
target = self.parse_tuple(simplified=True,
extra_end_rules=extra_end_rules)
else:
target = self.parse_primary()
target.set_ctx('store')
if not target.can_assign():
self.fail('can\'t assign to %r' % target.__class__.
__name__.lower(), target.lineno)
return target
def parse_expression(self, with_condexpr=True):
"""Parse an expression. Per default all expressions are parsed, if
the optional `with_condexpr` parameter is set to `False` conditional
expressions are not parsed.
"""
if with_condexpr:
return self.parse_condexpr()
return self.parse_or()
def parse_condexpr(self):
lineno = self.stream.current.lineno
expr1 = self.parse_or()
while self.stream.skip_if('name:if'):
expr2 = self.parse_or()
if self.stream.skip_if('name:else'):
expr3 = self.parse_condexpr()
else:
expr3 = None
expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
lineno = self.stream.current.lineno
return expr1
def parse_or(self):
lineno = self.stream.current.lineno
left = self.parse_and()
while self.stream.skip_if('name:or'):
right = self.parse_and()
left = nodes.Or(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_and(self):
lineno = self.stream.current.lineno
left = self.parse_not()
while self.stream.skip_if('name:and'):
right = self.parse_not()
left = nodes.And(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_not(self):
if self.stream.current.test('name:not'):
lineno = next(self.stream).lineno
return nodes.Not(self.parse_not(), lineno=lineno)
return self.parse_compare()
def parse_compare(self):
lineno = self.stream.current.lineno
expr = self.parse_add()
ops = []
while 1:
token_type = self.stream.current.type
if token_type in _compare_operators:
next(self.stream)
ops.append(nodes.Operand(token_type, self.parse_add()))
elif self.stream.skip_if('name:in'):
ops.append(nodes.Operand('in', self.parse_add()))
elif self.stream.current.test('name:not') and \
self.stream.look().test('name:in'):
self.stream.skip(2)
ops.append(nodes.Operand('notin', self.parse_add()))
else:
break
lineno = self.stream.current.lineno
if not ops:
return expr
return nodes.Compare(expr, ops, lineno=lineno)
def parse_add(self):
lineno = self.stream.current.lineno
left = self.parse_sub()
while self.stream.current.type == 'add':
next(self.stream)
right = self.parse_sub()
left = nodes.Add(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_sub(self):
lineno = self.stream.current.lineno
left = self.parse_concat()
while self.stream.current.type == 'sub':
next(self.stream)
right = self.parse_concat()
left = nodes.Sub(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_concat(self):
lineno = self.stream.current.lineno
args = [self.parse_mul()]
while self.stream.current.type == 'tilde':
next(self.stream)
args.append(self.parse_mul())
if len(args) == 1:
return args[0]
return nodes.Concat(args, lineno=lineno)
def parse_mul(self):
lineno = self.stream.current.lineno
left = self.parse_div()
while self.stream.current.type == 'mul':
next(self.stream)
right = self.parse_div()
left = nodes.Mul(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_div(self):
lineno = self.stream.current.lineno
left = self.parse_floordiv()
while self.stream.current.type == 'div':
next(self.stream)
right = self.parse_floordiv()
left = nodes.Div(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_floordiv(self):
lineno = self.stream.current.lineno
left = self.parse_mod()
while self.stream.current.type == 'floordiv':
next(self.stream)
right = self.parse_mod()
left = nodes.FloorDiv(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_mod(self):
lineno = self.stream.current.lineno
left = self.parse_pow()
while self.stream.current.type == 'mod':
next(self.stream)
right = self.parse_pow()
left = nodes.Mod(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_pow(self):
lineno = self.stream.current.lineno
left = self.parse_unary()
while self.stream.current.type == 'pow':
next(self.stream)
right = self.parse_unary()
left = nodes.Pow(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_unary(self, with_filter=True):
token_type = self.stream.current.type
lineno = self.stream.current.lineno
if token_type == 'sub':
next(self.stream)
node = nodes.Neg(self.parse_unary(False), lineno=lineno)
elif token_type == 'add':
next(self.stream)
node = nodes.Pos(self.parse_unary(False), lineno=lineno)
else:
node = self.parse_primary()
node = self.parse_postfix(node)
if with_filter:
node = self.parse_filter_expr(node)
return node
def parse_primary(self):
token = self.stream.current
if token.type == 'name':
if token.value in ('true', 'false', 'True', 'False'):
node = nodes.Const(token.value in ('true', 'True'),
lineno=token.lineno)
elif token.value in ('none', 'None'):
node = nodes.Const(None, lineno=token.lineno)
else:
node = nodes.Name(token.value, 'load', lineno=token.lineno)
next(self.stream)
elif token.type == 'string':
next(self.stream)
buf = [token.value]
lineno = token.lineno
while self.stream.current.type == 'string':
buf.append(self.stream.current.value)
next(self.stream)
node = nodes.Const(''.join(buf), lineno=lineno)
elif token.type in ('integer', 'float'):
next(self.stream)
node = nodes.Const(token.value, lineno=token.lineno)
elif token.type == 'lparen':
next(self.stream)
node = self.parse_tuple(explicit_parentheses=True)
self.stream.expect('rparen')
elif token.type == 'lbracket':
node = self.parse_list()
elif token.type == 'lbrace':
node = self.parse_dict()
else:
self.fail("unexpected '%s'" % describe_token(token), token.lineno)
return node
def parse_tuple(self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False):
"""Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not.
"""
lineno = self.stream.current.lineno
if simplified:
parse = self.parse_primary
elif with_condexpr:
parse = self.parse_expression
else:
parse = lambda: self.parse_expression(with_condexpr=False)
args = []
is_tuple = False
while 1:
if args:
self.stream.expect('comma')
if self.is_tuple_end(extra_end_rules):
break
args.append(parse())
if self.stream.current.type == 'comma':
is_tuple = True
else:
break
lineno = self.stream.current.lineno
if not is_tuple:
if args:
return args[0]
# if we don't have explicit parentheses, an empty tuple is
# not a valid expression. This would mean nothing (literally
# nothing) in the spot of an expression would be an empty
# tuple.
if not explicit_parentheses:
self.fail('Expected an expression, got \'%s\'' %
describe_token(self.stream.current))
return nodes.Tuple(args, 'load', lineno=lineno)
def parse_list(self):
token = self.stream.expect('lbracket')
items = []
while self.stream.current.type != 'rbracket':
if items:
self.stream.expect('comma')
if self.stream.current.type == 'rbracket':
break
items.append(self.parse_expression())
self.stream.expect('rbracket')
return nodes.List(items, lineno=token.lineno)
def parse_dict(self):
token = self.stream.expect('lbrace')
items = []
while self.stream.current.type != 'rbrace':
if items:
self.stream.expect('comma')
if self.stream.current.type == 'rbrace':
break
key = self.parse_expression()
self.stream.expect('colon')
value = self.parse_expression()
items.append(nodes.Pair(key, value, lineno=key.lineno))
self.stream.expect('rbrace')
return nodes.Dict(items, lineno=token.lineno)
def parse_postfix(self, node):
while 1:
token_type = self.stream.current.type
if token_type == 'dot' or token_type == 'lbracket':
node = self.parse_subscript(node)
# calls are valid both after postfix expressions (getattr
# and getitem) as well as filters and tests
elif token_type == 'lparen':
node = self.parse_call(node)
else:
break
return node
def parse_filter_expr(self, node):
while 1:
token_type = self.stream.current.type
if token_type == 'pipe':
node = self.parse_filter(node)
elif token_type == 'name' and self.stream.current.value == 'is':
node = self.parse_test(node)
# calls are valid both after postfix expressions (getattr
# and getitem) as well as filters and tests
elif token_type == 'lparen':
node = self.parse_call(node)
else:
break
return node
def parse_subscript(self, node):
token = next(self.stream)
if token.type == 'dot':
attr_token = self.stream.current
next(self.stream)
if attr_token.type == 'name':
return nodes.Getattr(node, attr_token.value, 'load',
lineno=token.lineno)
elif attr_token.type != 'integer':
self.fail('expected name or number', attr_token.lineno)
arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
if token.type == 'lbracket':
priority_on_attribute = False
args = []
while self.stream.current.type != 'rbracket':
if args:
self.stream.expect('comma')
args.append(self.parse_subscribed())
self.stream.expect('rbracket')
if len(args) == 1:
arg = args[0]
else:
arg = nodes.Tuple(args, 'load', lineno=token.lineno)
return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
self.fail('expected subscript expression', self.lineno)
def parse_subscribed(self):
lineno = self.stream.current.lineno
if self.stream.current.type == 'colon':
next(self.stream)
args = [None]
else:
node = self.parse_expression()
if self.stream.current.type != 'colon':
return node
next(self.stream)
args = [node]
if self.stream.current.type == 'colon':
args.append(None)
elif self.stream.current.type not in ('rbracket', 'comma'):
args.append(self.parse_expression())
else:
args.append(None)
if self.stream.current.type == 'colon':
next(self.stream)
if self.stream.current.type not in ('rbracket', 'comma'):
args.append(self.parse_expression())
else:
args.append(None)
else:
args.append(None)
return nodes.Slice(lineno=lineno, *args)
def parse_call(self, node):
token = self.stream.expect('lparen')
args = []
kwargs = []
dyn_args = dyn_kwargs = None
require_comma = False
def ensure(expr):
if not expr:
self.fail('invalid syntax for function call expression',
token.lineno)
while self.stream.current.type != 'rparen':
if require_comma:
self.stream.expect('comma')
# support for trailing comma
if self.stream.current.type == 'rparen':
break
if self.stream.current.type == 'mul':
ensure(dyn_args is None and dyn_kwargs is None)
next(self.stream)
dyn_args = self.parse_expression()
elif self.stream.current.type == 'pow':
ensure(dyn_kwargs is None)
next(self.stream)
dyn_kwargs = self.parse_expression()
else:
ensure(dyn_args is None and dyn_kwargs is None)
if self.stream.current.type == 'name' and \
self.stream.look().type == 'assign':
key = self.stream.current.value
self.stream.skip(2)
value = self.parse_expression()
kwargs.append(nodes.Keyword(key, value,
lineno=value.lineno))
else:
ensure(not kwargs)
args.append(self.parse_expression())
require_comma = True
self.stream.expect('rparen')
if node is None:
return args, kwargs, dyn_args, dyn_kwargs
return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,
lineno=token.lineno)
def parse_filter(self, node, start_inline=False):
while self.stream.current.type == 'pipe' or start_inline:
if not start_inline:
next(self.stream)
token = self.stream.expect('name')
name = token.value
while self.stream.current.type == 'dot':
next(self.stream)
name += '.' + self.stream.expect('name').value
if self.stream.current.type == 'lparen':
args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
else:
args = []
kwargs = []
dyn_args = dyn_kwargs = None
node = nodes.Filter(node, name, args, kwargs, dyn_args,
dyn_kwargs, lineno=token.lineno)
start_inline = False
return node
def parse_test(self, node):
token = next(self.stream)
if self.stream.current.test('name:not'):
next(self.stream)
negated = True
else:
negated = False
name = self.stream.expect('name').value
while self.stream.current.type == 'dot':
next(self.stream)
name += '.' + self.stream.expect('name').value
dyn_args = dyn_kwargs = None
kwargs = []
if self.stream.current.type == 'lparen':
args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
elif self.stream.current.type in ('name', 'string', 'integer',
'float', 'lparen', 'lbracket',
'lbrace') and not \
self.stream.current.test_any('name:else', 'name:or',
'name:and'):
if self.stream.current.test('name:is'):
self.fail('You cannot chain multiple tests with is')
args = [self.parse_expression()]
else:
args = []
node = nodes.Test(node, name, args, kwargs, dyn_args,
dyn_kwargs, lineno=token.lineno)
if negated:
node = nodes.Not(node, lineno=token.lineno)
return node
def subparse(self, end_tokens=None):
body = []
data_buffer = []
add_data = data_buffer.append
if end_tokens is not None:
self._end_token_stack.append(end_tokens)
def flush_data():
if data_buffer:
lineno = data_buffer[0].lineno
body.append(nodes.Output(data_buffer[:], lineno=lineno))
del data_buffer[:]
try:
while self.stream:
token = self.stream.current
if token.type == 'data':
if token.value:
add_data(nodes.TemplateData(token.value,
lineno=token.lineno))
next(self.stream)
elif token.type == 'variable_begin':
next(self.stream)
add_data(self.parse_tuple(with_condexpr=True))
self.stream.expect('variable_end')
elif token.type == 'block_begin':
flush_data()
next(self.stream)
if end_tokens is not None and \
self.stream.current.test_any(*end_tokens):
return body
rv = self.parse_statement()
if isinstance(rv, list):
body.extend(rv)
else:
body.append(rv)
self.stream.expect('block_end')
else:
raise AssertionError('internal parsing error')
flush_data()
finally:
if end_tokens is not None:
self._end_token_stack.pop()
return body
def parse(self):
"""Parse the whole template into a `Template` node."""
result = nodes.Template(self.subparse(), lineno=1)
result.set_environment(self.environment)
return result
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.loaders
~~~~~~~~~~~~~~
Jinja loader classes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import weakref
from types import ModuleType
from os import path
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
from jinja2.exceptions import TemplateNotFound
from jinja2.utils import LRUCache, open_if_exists, internalcode
def split_template_path(template):
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in template.split('/'):
if path.sep in piece \
or (path.altsep and path.altsep in piece) or \
piece == path.pardir:
raise TemplateNotFound(template)
elif piece and piece != '.':
pieces.append(piece)
return pieces
class BaseLoader(object):
"""Baseclass for all loaders. Subclass this and override `get_source` to
implement a custom loading mechanism. The environment provides a
`get_template` method that calls the loader's `load` method to get the
:class:`Template` object.
A very basic example for a loader that looks up templates on the file
system could look like this::
from jinja2 import BaseLoader, TemplateNotFound
from os.path import join, exists, getmtime
class MyLoader(BaseLoader):
def __init__(self, path):
self.path = path
def get_source(self, environment, template):
path = join(self.path, template)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with file(path) as f:
source = f.read().decode('utf-8')
return source, path, lambda: mtime == getmtime(path)
"""
#: if set to `False` it indicates that the loader cannot provide access
#: to the source of templates.
#:
#: .. versionadded:: 2.4
has_source_access = True
def get_source(self, environment, template):
"""Get the template source, filename and reload helper for a template.
It's passed the environment and template name and has to return a
tuple in the form ``(source, filename, uptodate)`` or raise a
`TemplateNotFound` error if it can't locate the template.
The source part of the returned tuple must be the source of the
template as unicode string or a ASCII bytestring. The filename should
be the name of the file on the filesystem if it was loaded from there,
otherwise `None`. The filename is used by python for the tracebacks
if no loader extension is used.
The last item in the tuple is the `uptodate` function. If auto
reloading is enabled it's always called to check if the template
changed. No arguments are passed so the function must store the
old state somewhere (for example in a closure). If it returns `False`
the template will be reloaded.
"""
if not self.has_source_access:
raise RuntimeError('%s cannot provide access to the source' %
self.__class__.__name__)
raise TemplateNotFound(template)
def list_templates(self):
"""Iterates over all templates. If the loader does not support that
it should raise a :exc:`TypeError` which is the default behavior.
"""
raise TypeError('this loader cannot iterate over all templates')
@internalcode
def load(self, environment, name, globals=None):
"""Loads a template. This method looks up the template in the cache
or loads one by calling :meth:`get_source`. Subclasses should not
override this method as loaders working on collections of other
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
will not call this method but `get_source` directly.
"""
code = None
if globals is None:
globals = {}
# first we try to get the source for this template together
# with the filename and the uptodate function.
source, filename, uptodate = self.get_source(environment, name)
# try to load the code from the bytecode cache if there is a
# bytecode cache configured.
bcc = environment.bytecode_cache
if bcc is not None:
bucket = bcc.get_bucket(environment, name, filename, source)
code = bucket.code
# if we don't have code so far (not cached, no longer up to
# date) etc. we compile the template
if code is None:
code = environment.compile(source, name, filename)
# if the bytecode cache is available and the bucket doesn't
# have a code so far, we give the bucket the new code and put
# it back to the bytecode cache.
if bcc is not None and bucket.code is None:
bucket.code = code
bcc.set_bucket(bucket)
return environment.template_class.from_code(environment, code,
globals, uptodate)
class FileSystemLoader(BaseLoader):
"""Loads templates from the file system. This loader can find templates
in folders on the file system and is the preferred way to load them.
The loader takes the path to the templates as string, or if multiple
locations are wanted a list of them which is then looked up in the
given order:
>>> loader = FileSystemLoader('/path/to/templates')
>>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
Per default the template encoding is ``'utf-8'`` which can be changed
by setting the `encoding` parameter to something else.
"""
def __init__(self, searchpath, encoding='utf-8'):
if isinstance(searchpath, basestring):
searchpath = [searchpath]
self.searchpath = list(searchpath)
self.encoding = encoding
def get_source(self, environment, template):
pieces = split_template_path(template)
for searchpath in self.searchpath:
filename = path.join(searchpath, *pieces)
f = open_if_exists(filename)
if f is None:
continue
try:
contents = f.read().decode(self.encoding)
finally:
f.close()
mtime = path.getmtime(filename)
def uptodate():
try:
return path.getmtime(filename) == mtime
except OSError:
return False
return contents, filename, uptodate
raise TemplateNotFound(template)
def list_templates(self):
found = set()
for searchpath in self.searchpath:
for dirpath, dirnames, filenames in os.walk(searchpath):
for filename in filenames:
template = os.path.join(dirpath, filename) \
[len(searchpath):].strip(os.path.sep) \
.replace(os.path.sep, '/')
if template[:2] == './':
template = template[2:]
if template not in found:
found.add(template)
return sorted(found)
class PackageLoader(BaseLoader):
"""Load templates from python eggs or packages. It is constructed with
the name of the python package and the path to the templates in that
package::
loader = PackageLoader('mypackage', 'views')
If the package path is not given, ``'templates'`` is assumed.
Per default the template encoding is ``'utf-8'`` which can be changed
by setting the `encoding` parameter to something else. Due to the nature
of eggs it's only possible to reload templates if the package was loaded
from the file system and not a zip file.
"""
def __init__(self, package_name, package_path='templates',
encoding='utf-8'):
from pkg_resources import DefaultProvider, ResourceManager, \
get_provider
provider = get_provider(package_name)
self.encoding = encoding
self.manager = ResourceManager()
self.filesystem_bound = isinstance(provider, DefaultProvider)
self.provider = provider
self.package_path = package_path
def get_source(self, environment, template):
pieces = split_template_path(template)
p = '/'.join((self.package_path,) + tuple(pieces))
if not self.provider.has_resource(p):
raise TemplateNotFound(template)
filename = uptodate = None
if self.filesystem_bound:
filename = self.provider.get_resource_filename(self.manager, p)
mtime = path.getmtime(filename)
def uptodate():
try:
return path.getmtime(filename) == mtime
except OSError:
return False
source = self.provider.get_resource_string(self.manager, p)
return source.decode(self.encoding), filename, uptodate
def list_templates(self):
path = self.package_path
if path[:2] == './':
path = path[2:]
elif path == '.':
path = ''
offset = len(path)
results = []
def _walk(path):
for filename in self.provider.resource_listdir(path):
fullname = path + '/' + filename
if self.provider.resource_isdir(fullname):
_walk(fullname)
else:
results.append(fullname[offset:].lstrip('/'))
_walk(path)
results.sort()
return results
class DictLoader(BaseLoader):
"""Loads a template from a python dict. It's passed a dict of unicode
strings bound to template names. This loader is useful for unittesting:
>>> loader = DictLoader({'index.html': 'source here'})
Because auto reloading is rarely useful this is disabled per default.
"""
def __init__(self, mapping):
self.mapping = mapping
def get_source(self, environment, template):
if template in self.mapping:
source = self.mapping[template]
return source, None, lambda: source != self.mapping.get(template)
raise TemplateNotFound(template)
def list_templates(self):
return sorted(self.mapping)
class FunctionLoader(BaseLoader):
"""A loader that is passed a function which does the loading. The
function becomes the name of the template passed and has to return either
an unicode string with the template source, a tuple in the form ``(source,
filename, uptodatefunc)`` or `None` if the template does not exist.
>>> def load_template(name):
... if name == 'index.html':
... return '...'
...
>>> loader = FunctionLoader(load_template)
The `uptodatefunc` is a function that is called if autoreload is enabled
and has to return `True` if the template is still up to date. For more
details have a look at :meth:`BaseLoader.get_source` which has the same
return value.
"""
def __init__(self, load_func):
self.load_func = load_func
def get_source(self, environment, template):
rv = self.load_func(template)
if rv is None:
raise TemplateNotFound(template)
elif isinstance(rv, basestring):
return rv, None, None
return rv
class PrefixLoader(BaseLoader):
"""A loader that is passed a dict of loaders where each loader is bound
to a prefix. The prefix is delimited from the template by a slash per
default, which can be changed by setting the `delimiter` argument to
something else::
loader = PrefixLoader({
'app1': PackageLoader('mypackage.app1'),
'app2': PackageLoader('mypackage.app2')
})
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
by loading ``'app2/index.html'`` the file from the second.
"""
def __init__(self, mapping, delimiter='/'):
self.mapping = mapping
self.delimiter = delimiter
def get_source(self, environment, template):
try:
prefix, name = template.split(self.delimiter, 1)
loader = self.mapping[prefix]
except (ValueError, KeyError):
raise TemplateNotFound(template)
try:
return loader.get_source(environment, name)
except TemplateNotFound:
# re-raise the exception with the correct fileame here.
# (the one that includes the prefix)
raise TemplateNotFound(template)
def list_templates(self):
result = []
for prefix, loader in self.mapping.iteritems():
for template in loader.list_templates():
result.append(prefix + self.delimiter + template)
return result
class ChoiceLoader(BaseLoader):
"""This loader works like the `PrefixLoader` just that no prefix is
specified. If a template could not be found by one loader the next one
is tried.
>>> loader = ChoiceLoader([
... FileSystemLoader('/path/to/user/templates'),
... FileSystemLoader('/path/to/system/templates')
... ])
This is useful if you want to allow users to override builtin templates
from a different location.
"""
def __init__(self, loaders):
self.loaders = loaders
def get_source(self, environment, template):
for loader in self.loaders:
try:
return loader.get_source(environment, template)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
def list_templates(self):
found = set()
for loader in self.loaders:
found.update(loader.list_templates())
return sorted(found)
class _TemplateModule(ModuleType):
"""Like a normal module but with support for weak references"""
class ModuleLoader(BaseLoader):
"""This loader loads templates from precompiled templates.
Example usage:
>>> loader = ChoiceLoader([
... ModuleLoader('/path/to/compiled/templates'),
... FileSystemLoader('/path/to/templates')
... ])
Templates can be precompiled with :meth:`Environment.compile_templates`.
"""
has_source_access = False
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, basestring):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
@staticmethod
def get_template_key(name):
return 'tmpl_' + sha1(name.encode('utf-8')).hexdigest()
@staticmethod
def get_module_filename(name):
return ModuleLoader.get_template_key(name) + '.py'
@internalcode
def load(self, environment, name, globals=None):
key = self.get_template_key(name)
module = '%s.%s' % (self.package_name, key)
mod = getattr(self.module, module, None)
if mod is None:
try:
mod = __import__(module, None, None, ['root'])
except ImportError:
raise TemplateNotFound(name)
# remove the entry from sys.modules, we only want the attribute
# on the module object we have stored on the loader.
sys.modules.pop(module, None)
return environment.template_class.from_module_dict(
environment, mod.__dict__, globals)
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.tests
~~~~~~~~~~~~
Jinja test functions. Used with the "is" operator.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
from jinja2.runtime import Undefined
try:
from collections import Mapping as MappingType
except ImportError:
import UserDict
MappingType = (UserDict.UserDict, UserDict.DictMixin, dict)
# nose, nothing here to test
__test__ = False
number_re = re.compile(r'^-?\d+(\.\d+)?$')
regex_type = type(number_re)
try:
test_callable = callable
except NameError:
def test_callable(x):
return hasattr(x, '__call__')
def test_odd(value):
"""Return true if the variable is odd."""
return value % 2 == 1
def test_even(value):
"""Return true if the variable is even."""
return value % 2 == 0
def test_divisibleby(value, num):
"""Check if a variable is divisible by a number."""
return value % num == 0
def test_defined(value):
"""Return true if the variable is defined:
.. sourcecode:: jinja
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the :func:`default` filter for a simple way to set undefined
variables.
"""
return not isinstance(value, Undefined)
def test_undefined(value):
"""Like :func:`defined` but the other way round."""
return isinstance(value, Undefined)
def test_none(value):
"""Return true if the variable is none."""
return value is None
def test_lower(value):
"""Return true if the variable is lowercased."""
return unicode(value).islower()
def test_upper(value):
"""Return true if the variable is uppercased."""
return unicode(value).isupper()
def test_string(value):
"""Return true if the object is a string."""
return isinstance(value, basestring)
def test_mapping(value):
"""Return true if the object is a mapping (dict etc.).
.. versionadded:: 2.6
"""
return isinstance(value, MappingType)
def test_number(value):
"""Return true if the variable is a number."""
return isinstance(value, (int, long, float, complex))
def test_sequence(value):
"""Return true if the variable is a sequence. Sequences are variables
that are iterable.
"""
try:
len(value)
value.__getitem__
except:
return False
return True
def test_sameas(value, other):
"""Check if an object points to the same memory address than another
object:
.. sourcecode:: jinja
{% if foo.attribute is sameas false %}
the foo attribute really is the `False` singleton
{% endif %}
"""
return value is other
def test_iterable(value):
"""Check if it's possible to iterate over an object."""
try:
iter(value)
except TypeError:
return False
return True
def test_escaped(value):
"""Check if the value is escaped."""
return hasattr(value, '__html__')
TESTS = {
'odd': test_odd,
'even': test_even,
'divisibleby': test_divisibleby,
'defined': test_defined,
'undefined': test_undefined,
'none': test_none,
'lower': test_lower,
'upper': test_upper,
'string': test_string,
'mapping': test_mapping,
'number': test_number,
'sequence': test_sequence,
'iterable': test_iterable,
'callable': test_callable,
'sameas': test_sameas,
'escaped': test_escaped
}
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.filters
~~~~~~~~~~~~~~
Bundled jinja filters.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import math
from random import choice
from operator import itemgetter
from itertools import imap, groupby
from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode
from jinja2.runtime import Undefined
from jinja2.exceptions import FilterArgumentError, SecurityError
_word_re = re.compile(r'\w+(?u)')
def contextfilter(f):
"""Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
"""
f.contextfilter = True
return f
def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f
def environmentfilter(f):
"""Decorator for marking evironment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
"""
f.environmentfilter = True
return f
def make_attrgetter(environment, attribute):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes.
"""
if not isinstance(attribute, basestring) or '.' not in attribute:
return lambda x: environment.getitem(x, attribute)
attribute = attribute.split('.')
def attrgetter(item):
for part in attribute:
item = environment.getitem(item, part)
return item
return attrgetter
def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(unicode(value))
@evalcontextfilter
def do_replace(eval_ctx, s, old, new, count=None):
"""Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
"""
if count is None:
count = -1
if not eval_ctx.autoescape:
return unicode(s).replace(unicode(old), unicode(new), count)
if hasattr(old, '__html__') or hasattr(new, '__html__') and \
not hasattr(s, '__html__'):
s = escape(s)
else:
s = soft_unicode(s)
return s.replace(soft_unicode(old), soft_unicode(new), count)
def do_upper(s):
"""Convert a value to uppercase."""
return soft_unicode(s).upper()
def do_lower(s):
"""Convert a value to lowercase."""
return soft_unicode(s).lower()
@evalcontextfilter
def do_xmlattr(_eval_ctx, d, autospace=True):
"""Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped:
.. sourcecode:: html+jinja
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
.. sourcecode:: html
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item
if the filter returned something unless the second parameter is false.
"""
rv = u' '.join(
u'%s="%s"' % (escape(key), escape(value))
for key, value in d.iteritems()
if value is not None and not isinstance(value, Undefined)
)
if autospace and rv:
rv = u' ' + rv
if _eval_ctx.autoescape:
rv = Markup(rv)
return rv
def do_capitalize(s):
"""Capitalize a value. The first character will be uppercase, all others
lowercase.
"""
return soft_unicode(s).capitalize()
def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return soft_unicode(s).title()
def do_dictsort(value, case_sensitive=False, by='key'):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dicsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by key, case insensitive, sorted
normally and ordered by value.
"""
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError('You can only sort by either '
'"key" or "value"')
def sort_func(item):
value = item[pos]
if isinstance(value, basestring) and not case_sensitive:
value = value.lower()
return value
return sorted(value.items(), key=sort_func)
@environmentfilter
def do_sort(environment, value, reverse=False, case_sensitive=False,
attribute=None):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
if not case_sensitive:
def sort_func(item):
if isinstance(item, basestring):
item = item.lower()
return item
else:
sort_func = None
if attribute is not None:
getter = make_attrgetter(environment, attribute)
def sort_func(item, processor=sort_func or (lambda x: x)):
return processor(getter(item))
return sorted(value, key=sort_func, reverse=reverse)
def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }}
"""
if (boolean and not value) or isinstance(value, Undefined):
return default_value
return value
@evalcontextfilter
def do_join(eval_ctx, value, d=u'', attribute=None):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
.. sourcecode:: jinja
{{ users|join(', ', attribute='username') }}
.. versionadded:: 2.6
The `attribute` parameter was added.
"""
if attribute is not None:
value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return unicode(d).join(imap(unicode, value))
# if the delimiter doesn't have an html representation we check
# if any of the items has. If yes we do a coercion to Markup
if not hasattr(d, '__html__'):
value = list(value)
do_escape = False
for idx, item in enumerate(value):
if hasattr(item, '__html__'):
do_escape = True
else:
value[idx] = unicode(item)
if do_escape:
d = escape(d)
else:
d = unicode(d)
return d.join(value)
# no html involved, to normal joining
return soft_unicode(d).join(imap(soft_unicode, value))
def do_center(value, width=80):
"""Centers the value in a field of a given width."""
return unicode(value).center(width)
@environmentfilter
def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return iter(seq).next()
except StopIteration:
return environment.undefined('No first item, sequence was empty.')
@environmentfilter
def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return iter(reversed(seq)).next()
except StopIteration:
return environment.undefined('No last item, sequence was empty.')
@environmentfilter
def do_random(environment, seq):
"""Return a random item from the sequence."""
try:
return choice(seq)
except IndexError:
return environment.undefined('No random item, sequence was empty.')
def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
"""
bytes = float(value)
base = binary and 1024 or 1000
prefixes = [
(binary and "KiB" or "kB"),
(binary and "MiB" or "MB"),
(binary and "GiB" or "GB"),
(binary and "TiB" or "TB"),
(binary and "PiB" or "PB"),
(binary and "EiB" or "EB"),
(binary and "ZiB" or "ZB"),
(binary and "YiB" or "YB")
]
if bytes == 1:
return "1 Byte"
elif bytes < base:
return "%d Bytes" % bytes
else:
for i, prefix in enumerate(prefixes):
unit = base * base ** (i + 1)
if bytes < unit:
return "%.1f %s" % ((bytes / unit), prefix)
return "%.1f %s" % ((bytes / unit), prefix)
def do_pprint(value, verbose=False):
"""Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter
is truthy the output will be more verbose (this requires `pretty`)
"""
return pformat(value, verbose=verbose)
@evalcontextfilter
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
"""
rv = urlize(value, trim_url_limit, nofollow)
if eval_ctx.autoescape:
rv = Markup(rv)
return rv
def do_indent(s, width=4, indentfirst=False):
"""Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
{{ mytext|indent(2, true) }}
indent by two spaces and indent the first line too.
"""
indention = u' ' * width
rv = (u'\n' + indention).join(s.splitlines())
if indentfirst:
rv = indention + rv
return rv
def do_truncate(s, length=255, killwords=False, end='...'):
"""Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will try to save the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter.
.. sourcecode jinja::
{{ mytext|truncate(300, false, '»') }}
truncate mytext to 300 chars, don't split up words, use a
right pointing double arrow as ellipsis sign.
"""
if len(s) <= length:
return s
elif killwords:
return s[:length] + end
words = s.split(' ')
result = []
m = 0
for word in words:
m += len(word) + 1
if m > length:
break
result.append(word)
result.append(end)
return u' '.join(result)
@environmentfilter
def do_wordwrap(environment, s, width=79, break_long_words=True):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`.
"""
import textwrap
return environment.newline_sequence.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordcount(s):
"""Count the words in that string."""
return len(_word_re.findall(s))
def do_int(value, default=0):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
"""
try:
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (TypeError, ValueError):
return default
def do_float(value, default=0.0):
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, ValueError):
return default
def do_format(value, *args, **kwargs):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
if args and kwargs:
raise FilterArgumentError('can\'t handle positional and keyword '
'arguments at the same time')
return soft_unicode(value) % (kwargs or args)
def do_trim(value):
"""Strip leading and trailing whitespace."""
return soft_unicode(value).strip()
def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(unicode(value)).striptags()
def do_slice(value, slices, fill_with=None):
"""Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it's used to fill missing
values on the last iteration.
"""
seq = list(value)
length = len(seq)
items_per_slice = length // slices
slices_with_extra = length % slices
offset = 0
for slice_number in xrange(slices):
start = offset + slice_number * items_per_slice
if slice_number < slices_with_extra:
offset += 1
end = offset + (slice_number + 1) * items_per_slice
tmp = seq[start:end]
if fill_with is not None and slice_number >= slices_with_extra:
tmp.append(fill_with)
yield tmp
def do_batch(value, linecount, fill_with=None):
"""
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
"""
result = []
tmp = []
for item in value:
if len(tmp) == linecount:
yield tmp
tmp = []
tmp.append(item)
if tmp:
if fill_with is not None and len(tmp) < linecount:
tmp += [fill_with] * (linecount - len(tmp))
yield tmp
def do_round(value, precision=0, method='common'):
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
If you don't specify a method ``'common'`` is used.
.. sourcecode:: jinja
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If
you need a real integer, pipe it through `int`:
.. sourcecode:: jinja
{{ 42.55|round|int }}
-> 43
"""
if not method in ('common', 'ceil', 'floor'):
raise FilterArgumentError('method must be common, ceil or floor')
if method == 'common':
return round(value, precision)
func = getattr(math, method)
return func(value * (10 ** precision)) / (10 ** precision)
@environmentfilter
def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
"""
expr = make_attrgetter(environment, attribute)
return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
class _GroupTuple(tuple):
__slots__ = ()
grouper = property(itemgetter(0))
list = property(itemgetter(1))
def __new__(cls, (key, value)):
return tuple.__new__(cls, (key, list(value)))
@environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The `attribute` parameter was added to allow suming up over
attributes. Also the `start` parameter was moved on to the right.
"""
if attribute is not None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start)
def do_list(value):
"""Convert the value into a list. If it was a string the returned list
will be a list of characters.
"""
return list(value)
def do_mark_safe(value):
"""Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
"""
return Markup(value)
def do_mark_unsafe(value):
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
return unicode(value)
def do_reverse(value):
"""Reverse the object or return an iterator the iterates over it the other
way round.
"""
if isinstance(value, basestring):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable')
@environmentfilter
def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo["bar"]`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
if environment.sandboxed and not \
environment.is_safe_attribute(obj, name, value):
return environment.unsafe_undefined(obj, name)
return value
return environment.undefined(obj=obj, name=name)
FILTERS = {
'attr': do_attr,
'replace': do_replace,
'upper': do_upper,
'lower': do_lower,
'escape': escape,
'e': escape,
'forceescape': do_forceescape,
'capitalize': do_capitalize,
'title': do_title,
'default': do_default,
'd': do_default,
'join': do_join,
'count': len,
'dictsort': do_dictsort,
'sort': do_sort,
'length': len,
'reverse': do_reverse,
'center': do_center,
'indent': do_indent,
'title': do_title,
'capitalize': do_capitalize,
'first': do_first,
'last': do_last,
'random': do_random,
'filesizeformat': do_filesizeformat,
'pprint': do_pprint,
'truncate': do_truncate,
'wordwrap': do_wordwrap,
'wordcount': do_wordcount,
'int': do_int,
'float': do_float,
'string': soft_unicode,
'list': do_list,
'urlize': do_urlize,
'format': do_format,
'trim': do_trim,
'striptags': do_striptags,
'slice': do_slice,
'batch': do_batch,
'sum': do_sum,
'abs': abs,
'round': do_round,
'groupby': do_groupby,
'safe': do_mark_safe,
'xmlattr': do_xmlattr
}
| Python |
import gc
import unittest
from jinja2._markupsafe import Markup, escape, escape_silent
class MarkupTestCase(unittest.TestCase):
def test_markup_operations(self):
# adding two strings should escape the unsafe one
unsafe = '<script type="application/x-some-script">alert("foo");</script>'
safe = Markup('<em>username</em>')
assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)
# string interpolations are safe to use too
assert Markup('<em>%s</em>') % '<bad user>' == \
'<em><bad user></em>'
assert Markup('<em>%(username)s</em>') % {
'username': '<bad user>'
} == '<em><bad user></em>'
# an escaped object is markup too
assert type(Markup('foo') + 'bar') is Markup
# and it implements __html__ by returning itself
x = Markup("foo")
assert x.__html__() is x
# it also knows how to treat __html__ objects
class Foo(object):
def __html__(self):
return '<em>awesome</em>'
def __unicode__(self):
return 'awesome'
assert Markup(Foo()) == '<em>awesome</em>'
assert Markup('<strong>%s</strong>') % Foo() == \
'<strong><em>awesome</em></strong>'
# escaping and unescaping
assert escape('"<>&\'') == '"<>&''
assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"
assert Markup("<test>").unescape() == "<test>"
def test_all_set(self):
import jinja2._markupsafe as markup
for item in markup.__all__:
getattr(markup, item)
def test_escape_silent(self):
assert escape_silent(None) == Markup()
assert escape(None) == Markup(None)
assert escape_silent('<foo>') == Markup(u'<foo>')
class MarkupLeakTestCase(unittest.TestCase):
def test_markup_leaks(self):
counts = set()
for count in xrange(20):
for item in xrange(1000):
escape("foo")
escape("<foo>")
escape(u"foo")
escape(u"<foo>")
counts.add(len(gc.get_objects()))
assert len(counts) == 1, 'ouch, c extension seems to leak objects'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(MarkupTestCase))
# this test only tests the c extension
if not hasattr(escape, 'func_code'):
suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| Python |
# -*- coding: utf-8 -*-
"""
jinja2._markupsafe._bundle
~~~~~~~~~~~~~~~~~~~~~~~~~~
This script pulls in markupsafe from a source folder and
bundles it with Jinja2. It does not pull in the speedups
module though.
:copyright: Copyright 2010 by the Jinja team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import os
import re
def rewrite_imports(lines):
for idx, line in enumerate(lines):
new_line = re.sub(r'(import|from)\s+markupsafe\b',
r'\1 jinja2._markupsafe', line)
if new_line != line:
lines[idx] = new_line
def main():
if len(sys.argv) != 2:
print 'error: only argument is path to markupsafe'
sys.exit(1)
basedir = os.path.dirname(__file__)
markupdir = sys.argv[1]
for filename in os.listdir(markupdir):
if filename.endswith('.py'):
f = open(os.path.join(markupdir, filename))
try:
lines = list(f)
finally:
f.close()
rewrite_imports(lines)
f = open(os.path.join(basedir, filename), 'w')
try:
for line in lines:
f.write(line)
finally:
f.close()
if __name__ == '__main__':
main()
| Python |
# -*- coding: utf-8 -*-
"""
markupsafe._native
~~~~~~~~~~~~~~~~~~
Native Python implementation the C module is not compiled.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from jinja2._markupsafe import Markup
def escape(s):
"""Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
return Markup(unicode(s)
.replace('&', '&')
.replace('>', '>')
.replace('<', '<')
.replace("'", ''')
.replace('"', '"')
)
def escape_silent(s):
"""Like :func:`escape` but converts `None` into an empty
markup string.
"""
if s is None:
return Markup()
return escape(s)
def soft_unicode(s):
"""Make a string unicode if it isn't already. That way a markup
string is not converted back to unicode.
"""
if not isinstance(s, unicode):
s = unicode(s)
return s
| Python |
# -*- coding: utf-8 -*-
"""
markupsafe
~~~~~~~~~~
Implements a Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
from itertools import imap
__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
class Markup(unicode):
r"""Marks a string as being safe for inclusion in HTML/XML output without
needing to be escaped. This implements the `__html__` interface a couple
of frameworks and web applications use. :class:`Markup` is a direct
subclass of `unicode` and provides all the methods of `unicode` just that
it escapes arguments passed and always returns `Markup`.
The `escape` function returns markup objects so that double escaping can't
happen.
The constructor of the :class:`Markup` class can be used for three
different things: When passed an unicode object it's assumed to be safe,
when passed an object with an HTML representation (has an `__html__`
method) that representation is used, otherwise the object passed is
converted into a unicode string and then assumed to be safe:
>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
... def __html__(self):
... return '<a href="#">foo</a>'
...
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
If you want object passed being always treated as unsafe you can use the
:meth:`escape` classmethod to create a :class:`Markup` object:
>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
Operations on a markup string are markup aware which means that all
arguments are passed through the :func:`escape` function:
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(cls, base=u'', encoding=None, errors='strict'):
if hasattr(base, '__html__'):
base = base.__html__()
if encoding is None:
return unicode.__new__(cls, base)
return unicode.__new__(cls, base, encoding, errors)
def __html__(self):
return self
def __add__(self, other):
if hasattr(other, '__html__') or isinstance(other, basestring):
return self.__class__(unicode(self) + unicode(escape(other)))
return NotImplemented
def __radd__(self, other):
if hasattr(other, '__html__') or isinstance(other, basestring):
return self.__class__(unicode(escape(other)) + unicode(self))
return NotImplemented
def __mul__(self, num):
if isinstance(num, (int, long)):
return self.__class__(unicode.__mul__(self, num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg):
if isinstance(arg, tuple):
arg = tuple(imap(_MarkupEscapeHelper, arg))
else:
arg = _MarkupEscapeHelper(arg)
return self.__class__(unicode.__mod__(self, arg))
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
unicode.__repr__(self)
)
def join(self, seq):
return self.__class__(unicode.join(self, imap(escape, seq)))
join.__doc__ = unicode.join.__doc__
def split(self, *args, **kwargs):
return map(self.__class__, unicode.split(self, *args, **kwargs))
split.__doc__ = unicode.split.__doc__
def rsplit(self, *args, **kwargs):
return map(self.__class__, unicode.rsplit(self, *args, **kwargs))
rsplit.__doc__ = unicode.rsplit.__doc__
def splitlines(self, *args, **kwargs):
return map(self.__class__, unicode.splitlines(self, *args, **kwargs))
splitlines.__doc__ = unicode.splitlines.__doc__
def unescape(self):
r"""Unescape markup again into an unicode string. This also resolves
known HTML4 and XHTML entities:
>>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
"""
from jinja2._markupsafe._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ('#x', '#X'):
return unichr(int(name[2:], 16))
elif name.startswith('#'):
return unichr(int(name[1:]))
except ValueError:
pass
return u''
return _entity_re.sub(handle_match, unicode(self))
def striptags(self):
r"""Unescape markup into an unicode string and strip all tags. This
also resolves known HTML4 and XHTML entities. Whitespace is
normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
"""
stripped = u' '.join(_striptags_re.sub('', self).split())
return Markup(stripped).unescape()
@classmethod
def escape(cls, s):
"""Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
def make_wrapper(name):
orig = getattr(unicode, name)
def func(self, *args, **kwargs):
args = _escape_argspec(list(args), enumerate(args))
_escape_argspec(kwargs, kwargs.iteritems())
return self.__class__(orig(self, *args, **kwargs))
func.__name__ = orig.__name__
func.__doc__ = orig.__doc__
return func
for method in '__getitem__', 'capitalize', \
'title', 'lower', 'upper', 'replace', 'ljust', \
'rjust', 'lstrip', 'rstrip', 'center', 'strip', \
'translate', 'expandtabs', 'swapcase', 'zfill':
locals()[method] = make_wrapper(method)
# new in python 2.5
if hasattr(unicode, 'partition'):
partition = make_wrapper('partition'),
rpartition = make_wrapper('rpartition')
# new in python 2.6
if hasattr(unicode, 'format'):
format = make_wrapper('format')
# not in python 3
if hasattr(unicode, '__getslice__'):
__getslice__ = make_wrapper('__getslice__')
del method, make_wrapper
def _escape_argspec(obj, iterable):
"""Helper for various string-wrapped functions."""
for key, value in iterable:
if hasattr(value, '__html__') or isinstance(value, basestring):
obj[key] = escape(value)
return obj
class _MarkupEscapeHelper(object):
"""Helper for Markup.__mod__"""
def __init__(self, obj):
self.obj = obj
__getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])
__str__ = lambda s: str(escape(s.obj))
__unicode__ = lambda s: unicode(escape(s.obj))
__repr__ = lambda s: str(escape(repr(s.obj)))
__int__ = lambda s: int(s.obj)
__float__ = lambda s: float(s.obj)
# we have to import it down here as the speedups and native
# modules imports the markup type which is define above.
try:
from jinja2._markupsafe._speedups import escape, escape_silent, soft_unicode
except ImportError:
from jinja2._markupsafe._native import escape, escape_silent, soft_unicode
| Python |
# -*- coding: utf-8 -*-
"""
markupsafe._constants
~~~~~~~~~~~~~~~~~~~~~
Highlevel implementation of the Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
HTML_ENTITIES = {
'AElig': 198,
'Aacute': 193,
'Acirc': 194,
'Agrave': 192,
'Alpha': 913,
'Aring': 197,
'Atilde': 195,
'Auml': 196,
'Beta': 914,
'Ccedil': 199,
'Chi': 935,
'Dagger': 8225,
'Delta': 916,
'ETH': 208,
'Eacute': 201,
'Ecirc': 202,
'Egrave': 200,
'Epsilon': 917,
'Eta': 919,
'Euml': 203,
'Gamma': 915,
'Iacute': 205,
'Icirc': 206,
'Igrave': 204,
'Iota': 921,
'Iuml': 207,
'Kappa': 922,
'Lambda': 923,
'Mu': 924,
'Ntilde': 209,
'Nu': 925,
'OElig': 338,
'Oacute': 211,
'Ocirc': 212,
'Ograve': 210,
'Omega': 937,
'Omicron': 927,
'Oslash': 216,
'Otilde': 213,
'Ouml': 214,
'Phi': 934,
'Pi': 928,
'Prime': 8243,
'Psi': 936,
'Rho': 929,
'Scaron': 352,
'Sigma': 931,
'THORN': 222,
'Tau': 932,
'Theta': 920,
'Uacute': 218,
'Ucirc': 219,
'Ugrave': 217,
'Upsilon': 933,
'Uuml': 220,
'Xi': 926,
'Yacute': 221,
'Yuml': 376,
'Zeta': 918,
'aacute': 225,
'acirc': 226,
'acute': 180,
'aelig': 230,
'agrave': 224,
'alefsym': 8501,
'alpha': 945,
'amp': 38,
'and': 8743,
'ang': 8736,
'apos': 39,
'aring': 229,
'asymp': 8776,
'atilde': 227,
'auml': 228,
'bdquo': 8222,
'beta': 946,
'brvbar': 166,
'bull': 8226,
'cap': 8745,
'ccedil': 231,
'cedil': 184,
'cent': 162,
'chi': 967,
'circ': 710,
'clubs': 9827,
'cong': 8773,
'copy': 169,
'crarr': 8629,
'cup': 8746,
'curren': 164,
'dArr': 8659,
'dagger': 8224,
'darr': 8595,
'deg': 176,
'delta': 948,
'diams': 9830,
'divide': 247,
'eacute': 233,
'ecirc': 234,
'egrave': 232,
'empty': 8709,
'emsp': 8195,
'ensp': 8194,
'epsilon': 949,
'equiv': 8801,
'eta': 951,
'eth': 240,
'euml': 235,
'euro': 8364,
'exist': 8707,
'fnof': 402,
'forall': 8704,
'frac12': 189,
'frac14': 188,
'frac34': 190,
'frasl': 8260,
'gamma': 947,
'ge': 8805,
'gt': 62,
'hArr': 8660,
'harr': 8596,
'hearts': 9829,
'hellip': 8230,
'iacute': 237,
'icirc': 238,
'iexcl': 161,
'igrave': 236,
'image': 8465,
'infin': 8734,
'int': 8747,
'iota': 953,
'iquest': 191,
'isin': 8712,
'iuml': 239,
'kappa': 954,
'lArr': 8656,
'lambda': 955,
'lang': 9001,
'laquo': 171,
'larr': 8592,
'lceil': 8968,
'ldquo': 8220,
'le': 8804,
'lfloor': 8970,
'lowast': 8727,
'loz': 9674,
'lrm': 8206,
'lsaquo': 8249,
'lsquo': 8216,
'lt': 60,
'macr': 175,
'mdash': 8212,
'micro': 181,
'middot': 183,
'minus': 8722,
'mu': 956,
'nabla': 8711,
'nbsp': 160,
'ndash': 8211,
'ne': 8800,
'ni': 8715,
'not': 172,
'notin': 8713,
'nsub': 8836,
'ntilde': 241,
'nu': 957,
'oacute': 243,
'ocirc': 244,
'oelig': 339,
'ograve': 242,
'oline': 8254,
'omega': 969,
'omicron': 959,
'oplus': 8853,
'or': 8744,
'ordf': 170,
'ordm': 186,
'oslash': 248,
'otilde': 245,
'otimes': 8855,
'ouml': 246,
'para': 182,
'part': 8706,
'permil': 8240,
'perp': 8869,
'phi': 966,
'pi': 960,
'piv': 982,
'plusmn': 177,
'pound': 163,
'prime': 8242,
'prod': 8719,
'prop': 8733,
'psi': 968,
'quot': 34,
'rArr': 8658,
'radic': 8730,
'rang': 9002,
'raquo': 187,
'rarr': 8594,
'rceil': 8969,
'rdquo': 8221,
'real': 8476,
'reg': 174,
'rfloor': 8971,
'rho': 961,
'rlm': 8207,
'rsaquo': 8250,
'rsquo': 8217,
'sbquo': 8218,
'scaron': 353,
'sdot': 8901,
'sect': 167,
'shy': 173,
'sigma': 963,
'sigmaf': 962,
'sim': 8764,
'spades': 9824,
'sub': 8834,
'sube': 8838,
'sum': 8721,
'sup': 8835,
'sup1': 185,
'sup2': 178,
'sup3': 179,
'supe': 8839,
'szlig': 223,
'tau': 964,
'there4': 8756,
'theta': 952,
'thetasym': 977,
'thinsp': 8201,
'thorn': 254,
'tilde': 732,
'times': 215,
'trade': 8482,
'uArr': 8657,
'uacute': 250,
'uarr': 8593,
'ucirc': 251,
'ugrave': 249,
'uml': 168,
'upsih': 978,
'upsilon': 965,
'uuml': 252,
'weierp': 8472,
'xi': 958,
'yacute': 253,
'yen': 165,
'yuml': 255,
'zeta': 950,
'zwj': 8205,
'zwnj': 8204
}
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.debug
~~~~~~~~~~~~~~~~~~~~~~
Tests the debug system.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import sys
import unittest
from jinja2.testsuite import JinjaTestCase, filesystem_loader
from jinja2 import Environment, TemplateSyntaxError
env = Environment(loader=filesystem_loader)
class DebugTestCase(JinjaTestCase):
if sys.version_info[:2] != (2, 4):
def test_runtime_error(self):
def test():
tmpl.render(fail=lambda: 1 / 0)
tmpl = env.get_template('broken.html')
self.assert_traceback_matches(test, r'''
File ".*?broken.html", line 2, in (top-level template code|<module>)
\{\{ fail\(\) \}\}
File ".*?debug.pyc?", line \d+, in <lambda>
tmpl\.render\(fail=lambda: 1 / 0\)
ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero
''')
def test_syntax_error(self):
# XXX: the .*? is necessary for python3 which does not hide
# some of the stack frames we don't want to show. Not sure
# what's up with that, but that is not that critical. Should
# be fixed though.
self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm)
File ".*?syntaxerror.html", line 4, in (template|<module>)
\{% endif %\}.*?
(jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
''')
def test_regular_syntax_error(self):
def test():
raise TemplateSyntaxError('wtf', 42)
self.assert_traceback_matches(test, r'''
File ".*debug.pyc?", line \d+, in test
raise TemplateSyntaxError\('wtf', 42\)
(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
line 42''')
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(DebugTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.utils
~~~~~~~~~~~~~~~~~~~~~~
Tests utilities jinja uses.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import gc
import unittest
import pickle
from jinja2.testsuite import JinjaTestCase
from jinja2.utils import LRUCache, escape, object_type_repr
class LRUCacheTestCase(JinjaTestCase):
def test_simple(self):
d = LRUCache(3)
d["a"] = 1
d["b"] = 2
d["c"] = 3
d["a"]
d["d"] = 4
assert len(d) == 3
assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d
def test_pickleable(self):
cache = LRUCache(2)
cache["foo"] = 42
cache["bar"] = 23
cache["foo"]
for protocol in range(3):
copy = pickle.loads(pickle.dumps(cache, protocol))
assert copy.capacity == cache.capacity
assert copy._mapping == cache._mapping
assert copy._queue == cache._queue
class HelpersTestCase(JinjaTestCase):
def test_object_type_repr(self):
class X(object):
pass
self.assert_equal(object_type_repr(42), 'int object')
self.assert_equal(object_type_repr([]), 'list object')
self.assert_equal(object_type_repr(X()),
'jinja2.testsuite.utils.X object')
self.assert_equal(object_type_repr(None), 'None')
self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis')
class MarkupLeakTestCase(JinjaTestCase):
def test_markup_leaks(self):
counts = set()
for count in xrange(20):
for item in xrange(1000):
escape("foo")
escape("<foo>")
escape(u"foo")
escape(u"<foo>")
counts.add(len(gc.get_objects()))
assert len(counts) == 1, 'ouch, c extension seems to leak objects'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(LRUCacheTestCase))
suite.addTest(unittest.makeSuite(HelpersTestCase))
# this test only tests the c extension
if not hasattr(escape, 'func_code'):
suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.ext
~~~~~~~~~~~~~~~~~~~~
Tests for the extensions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Environment, DictLoader, contextfunction, nodes
from jinja2.exceptions import TemplateAssertionError
from jinja2.ext import Extension
from jinja2.lexer import Token, count_newlines
from jinja2.utils import next
# 2.x / 3.x
try:
from io import BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
importable_object = 23
_gettext_re = re.compile(r'_\((.*?)\)(?s)')
i18n_templates = {
'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'
'{% block body %}{% endblock %}',
'child.html': '{% extends "master.html" %}{% block body %}'
'{% trans %}watch out{% endtrans %}{% endblock %}',
'plural.html': '{% trans user_count %}One user online{% pluralize %}'
'{{ user_count }} users online{% endtrans %}',
'stringformat.html': '{{ _("User: %(num)s")|format(num=user_count) }}'
}
newstyle_i18n_templates = {
'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'
'{% block body %}{% endblock %}',
'child.html': '{% extends "master.html" %}{% block body %}'
'{% trans %}watch out{% endtrans %}{% endblock %}',
'plural.html': '{% trans user_count %}One user online{% pluralize %}'
'{{ user_count }} users online{% endtrans %}',
'stringformat.html': '{{ _("User: %(num)s", num=user_count) }}',
'ngettext.html': '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',
'ngettext_long.html': '{% trans num=apples %}{{ num }} apple{% pluralize %}'
'{{ num }} apples{% endtrans %}',
'transvars1.html': '{% trans %}User: {{ num }}{% endtrans %}',
'transvars2.html': '{% trans num=count %}User: {{ num }}{% endtrans %}',
'transvars3.html': '{% trans count=num %}User: {{ count }}{% endtrans %}',
'novars.html': '{% trans %}%(hello)s{% endtrans %}',
'vars.html': '{% trans %}{{ foo }}%(foo)s{% endtrans %}',
'explicitvars.html': '{% trans foo="42" %}%(foo)s{% endtrans %}'
}
languages = {
'de': {
'missing': u'fehlend',
'watch out': u'pass auf',
'One user online': u'Ein Benutzer online',
'%(user_count)s users online': u'%(user_count)s Benutzer online',
'User: %(num)s': u'Benutzer: %(num)s',
'User: %(count)s': u'Benutzer: %(count)s',
'%(num)s apple': u'%(num)s Apfel',
'%(num)s apples': u'%(num)s Äpfel'
}
}
@contextfunction
def gettext(context, string):
language = context.get('LANGUAGE', 'en')
return languages.get(language, {}).get(string, string)
@contextfunction
def ngettext(context, s, p, n):
language = context.get('LANGUAGE', 'en')
if n != 1:
return languages.get(language, {}).get(p, p)
return languages.get(language, {}).get(s, s)
i18n_env = Environment(
loader=DictLoader(i18n_templates),
extensions=['jinja2.ext.i18n']
)
i18n_env.globals.update({
'_': gettext,
'gettext': gettext,
'ngettext': ngettext
})
newstyle_i18n_env = Environment(
loader=DictLoader(newstyle_i18n_templates),
extensions=['jinja2.ext.i18n']
)
newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)
class TestExtension(Extension):
tags = set(['test'])
ext_attr = 42
def parse(self, parser):
return nodes.Output([self.call_method('_dump', [
nodes.EnvironmentAttribute('sandboxed'),
self.attr('ext_attr'),
nodes.ImportedName(__name__ + '.importable_object'),
nodes.ContextReference()
])]).set_lineno(next(parser.stream).lineno)
def _dump(self, sandboxed, ext_attr, imported_object, context):
return '%s|%s|%s|%s' % (
sandboxed,
ext_attr,
imported_object,
context.blocks
)
class PreprocessorExtension(Extension):
def preprocess(self, source, name, filename=None):
return source.replace('[[TEST]]', '({{ foo }})')
class StreamFilterExtension(Extension):
def filter_stream(self, stream):
for token in stream:
if token.type == 'data':
for t in self.interpolate(token):
yield t
else:
yield token
def interpolate(self, token):
pos = 0
end = len(token.value)
lineno = token.lineno
while 1:
match = _gettext_re.search(token.value, pos)
if match is None:
break
value = token.value[pos:match.start()]
if value:
yield Token(lineno, 'data', value)
lineno += count_newlines(token.value)
yield Token(lineno, 'variable_begin', None)
yield Token(lineno, 'name', 'gettext')
yield Token(lineno, 'lparen', None)
yield Token(lineno, 'string', match.group(1))
yield Token(lineno, 'rparen', None)
yield Token(lineno, 'variable_end', None)
pos = match.end()
if pos < end:
yield Token(lineno, 'data', token.value[pos:])
class ExtensionsTestCase(JinjaTestCase):
def test_extend_late(self):
env = Environment()
env.add_extension('jinja2.ext.autoescape')
t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')
assert t.render() == '<test>'
def test_loop_controls(self):
env = Environment(extensions=['jinja2.ext.loopcontrols'])
tmpl = env.from_string('''
{%- for item in [1, 2, 3, 4] %}
{%- if item % 2 == 0 %}{% continue %}{% endif -%}
{{ item }}
{%- endfor %}''')
assert tmpl.render() == '13'
tmpl = env.from_string('''
{%- for item in [1, 2, 3, 4] %}
{%- if item > 2 %}{% break %}{% endif -%}
{{ item }}
{%- endfor %}''')
assert tmpl.render() == '12'
def test_do(self):
env = Environment(extensions=['jinja2.ext.do'])
tmpl = env.from_string('''
{%- set items = [] %}
{%- for char in "foo" %}
{%- do items.append(loop.index0 ~ char) %}
{%- endfor %}{{ items|join(', ') }}''')
assert tmpl.render() == '0f, 1o, 2o'
def test_with(self):
env = Environment(extensions=['jinja2.ext.with_'])
tmpl = env.from_string('''\
{% with a=42, b=23 -%}
{{ a }} = {{ b }}
{% endwith -%}
{{ a }} = {{ b }}\
''')
assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \
== ['42 = 23', '1 = 2']
def test_extension_nodes(self):
env = Environment(extensions=[TestExtension])
tmpl = env.from_string('{% test %}')
assert tmpl.render() == 'False|42|23|{}'
def test_identifier(self):
assert TestExtension.identifier == __name__ + '.TestExtension'
def test_rebinding(self):
original = Environment(extensions=[TestExtension])
overlay = original.overlay()
for env in original, overlay:
for ext in env.extensions.itervalues():
assert ext.environment is env
def test_preprocessor_extension(self):
env = Environment(extensions=[PreprocessorExtension])
tmpl = env.from_string('{[[TEST]]}')
assert tmpl.render(foo=42) == '{(42)}'
def test_streamfilter_extension(self):
env = Environment(extensions=[StreamFilterExtension])
env.globals['gettext'] = lambda x: x.upper()
tmpl = env.from_string('Foo _(bar) Baz')
out = tmpl.render()
assert out == 'Foo BAR Baz'
def test_extension_ordering(self):
class T1(Extension):
priority = 1
class T2(Extension):
priority = 2
env = Environment(extensions=[T1, T2])
ext = list(env.iter_extensions())
assert ext[0].__class__ is T1
assert ext[1].__class__ is T2
class InternationalizationTestCase(JinjaTestCase):
def test_trans(self):
tmpl = i18n_env.get_template('child.html')
assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'
def test_trans_plural(self):
tmpl = i18n_env.get_template('plural.html')
assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
def test_complex_plural(self):
tmpl = i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
'pluralize count %}{{ count }} items{% endtrans %}')
assert tmpl.render() == '2 items'
self.assert_raises(TemplateAssertionError, i18n_env.from_string,
'{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
def test_trans_stringformatting(self):
tmpl = i18n_env.get_template('stringformat.html')
assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
def test_extract(self):
from jinja2.ext import babel_extract
source = BytesIO('''
{{ gettext('Hello World') }}
{% trans %}Hello World{% endtrans %}
{% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
'''.encode('ascii')) # make python 3 happy
assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [
(2, 'gettext', u'Hello World', []),
(3, 'gettext', u'Hello World', []),
(4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])
]
def test_comment_extract(self):
from jinja2.ext import babel_extract
source = BytesIO('''
{# trans first #}
{{ gettext('Hello World') }}
{% trans %}Hello World{% endtrans %}{# trans second #}
{#: third #}
{% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
'''.encode('utf-8')) # make python 3 happy
assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [
(3, 'gettext', u'Hello World', ['first']),
(4, 'gettext', u'Hello World', ['second']),
(6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])
]
class NewstyleInternationalizationTestCase(JinjaTestCase):
def test_trans(self):
tmpl = newstyle_i18n_env.get_template('child.html')
assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'
def test_trans_plural(self):
tmpl = newstyle_i18n_env.get_template('plural.html')
assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
def test_complex_plural(self):
tmpl = newstyle_i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
'pluralize count %}{{ count }} items{% endtrans %}')
assert tmpl.render() == '2 items'
self.assert_raises(TemplateAssertionError, i18n_env.from_string,
'{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
def test_trans_stringformatting(self):
tmpl = newstyle_i18n_env.get_template('stringformat.html')
assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
def test_newstyle_plural(self):
tmpl = newstyle_i18n_env.get_template('ngettext.html')
assert tmpl.render(LANGUAGE='de', apples=1) == '1 Apfel'
assert tmpl.render(LANGUAGE='de', apples=5) == u'5 Äpfel'
def test_autoescape_support(self):
env = Environment(extensions=['jinja2.ext.autoescape',
'jinja2.ext.i18n'])
env.install_gettext_callables(lambda x: u'<strong>Wert: %(name)s</strong>',
lambda s, p, n: s, newstyle=True)
t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='
'"<test>") }}{% endautoescape %}')
assert t.render(ae=True) == '<strong>Wert: <test></strong>'
assert t.render(ae=False) == '<strong>Wert: <test></strong>'
def test_num_used_twice(self):
tmpl = newstyle_i18n_env.get_template('ngettext_long.html')
assert tmpl.render(apples=5, LANGUAGE='de') == u'5 Äpfel'
def test_num_called_num(self):
source = newstyle_i18n_env.compile('''
{% trans num=3 %}{{ num }} apple{% pluralize
%}{{ num }} apples{% endtrans %}
''', raw=True)
# quite hacky, but the only way to properly test that. The idea is
# that the generated code does not pass num twice (although that
# would work) for better performance. This only works on the
# newstyle gettext of course
assert re.search(r"l_ngettext, u?'\%\(num\)s apple', u?'\%\(num\)s "
r"apples', 3", source) is not None
def test_trans_vars(self):
t1 = newstyle_i18n_env.get_template('transvars1.html')
t2 = newstyle_i18n_env.get_template('transvars2.html')
t3 = newstyle_i18n_env.get_template('transvars3.html')
assert t1.render(num=1, LANGUAGE='de') == 'Benutzer: 1'
assert t2.render(count=23, LANGUAGE='de') == 'Benutzer: 23'
assert t3.render(num=42, LANGUAGE='de') == 'Benutzer: 42'
def test_novars_vars_escaping(self):
t = newstyle_i18n_env.get_template('novars.html')
assert t.render() == '%(hello)s'
t = newstyle_i18n_env.get_template('vars.html')
assert t.render(foo='42') == '42%(foo)s'
t = newstyle_i18n_env.get_template('explicitvars.html')
assert t.render() == '%(foo)s'
class AutoEscapeTestCase(JinjaTestCase):
def test_scoped_setting(self):
env = Environment(extensions=['jinja2.ext.autoescape'],
autoescape=True)
tmpl = env.from_string('''
{{ "<HelloWorld>" }}
{% autoescape false %}
{{ "<HelloWorld>" }}
{% endautoescape %}
{{ "<HelloWorld>" }}
''')
assert tmpl.render().split() == \
[u'<HelloWorld>', u'<HelloWorld>', u'<HelloWorld>']
env = Environment(extensions=['jinja2.ext.autoescape'],
autoescape=False)
tmpl = env.from_string('''
{{ "<HelloWorld>" }}
{% autoescape true %}
{{ "<HelloWorld>" }}
{% endautoescape %}
{{ "<HelloWorld>" }}
''')
assert tmpl.render().split() == \
[u'<HelloWorld>', u'<HelloWorld>', u'<HelloWorld>']
def test_nonvolatile(self):
env = Environment(extensions=['jinja2.ext.autoescape'],
autoescape=True)
tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')
assert tmpl.render() == ' foo="<test>"'
tmpl = env.from_string('{% autoescape false %}{{ {"foo": "<test>"}'
'|xmlattr|escape }}{% endautoescape %}')
assert tmpl.render() == ' foo="&lt;test&gt;"'
def test_volatile(self):
env = Environment(extensions=['jinja2.ext.autoescape'],
autoescape=True)
tmpl = env.from_string('{% autoescape foo %}{{ {"foo": "<test>"}'
'|xmlattr|escape }}{% endautoescape %}')
assert tmpl.render(foo=False) == ' foo="&lt;test&gt;"'
assert tmpl.render(foo=True) == ' foo="<test>"'
def test_scoping(self):
env = Environment(extensions=['jinja2.ext.autoescape'])
tmpl = env.from_string('{% autoescape true %}{% set x = "<x>" %}{{ x }}'
'{% endautoescape %}{{ x }}{{ "<y>" }}')
assert tmpl.render(x=1) == '<x>1<y>'
def test_volatile_scoping(self):
env = Environment(extensions=['jinja2.ext.autoescape'])
tmplsource = '''
{% autoescape val %}
{% macro foo(x) %}
[{{ x }}]
{% endmacro %}
{{ foo().__class__.__name__ }}
{% endautoescape %}
{{ '<testing>' }}
'''
tmpl = env.from_string(tmplsource)
assert tmpl.render(val=True).split()[0] == 'Markup'
assert tmpl.render(val=False).split()[0] == unicode.__name__
# looking at the source we should see <testing> there in raw
# (and then escaped as well)
env = Environment(extensions=['jinja2.ext.autoescape'])
pysource = env.compile(tmplsource, raw=True)
assert '<testing>\\n' in pysource
env = Environment(extensions=['jinja2.ext.autoescape'],
autoescape=True)
pysource = env.compile(tmplsource, raw=True)
assert '<testing>\\n' in pysource
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ExtensionsTestCase))
suite.addTest(unittest.makeSuite(InternationalizationTestCase))
suite.addTest(unittest.makeSuite(NewstyleInternationalizationTestCase))
suite.addTest(unittest.makeSuite(AutoEscapeTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.lexnparse
~~~~~~~~~~~~~~~~~~~~~~~~~~
All the unittests regarding lexing, parsing and syntax.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import sys
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Environment, Template, TemplateSyntaxError, \
UndefinedError, nodes
env = Environment()
# how does a string look like in jinja syntax?
if sys.version_info < (3, 0):
def jinja_string_repr(string):
return repr(string)[1:]
else:
jinja_string_repr = repr
class LexerTestCase(JinjaTestCase):
def test_raw1(self):
tmpl = env.from_string('{% raw %}foo{% endraw %}|'
'{%raw%}{{ bar }}|{% baz %}{% endraw %}')
assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'
def test_raw2(self):
tmpl = env.from_string('1 {%- raw -%} 2 {%- endraw -%} 3')
assert tmpl.render() == '123'
def test_balancing(self):
env = Environment('{%', '%}', '${', '}')
tmpl = env.from_string('''{% for item in seq
%}${{'foo': item}|upper}{% endfor %}''')
assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"
def test_comments(self):
env = Environment('<!--', '-->', '{', '}')
tmpl = env.from_string('''\
<ul>
<!--- for item in seq -->
<li>{item}</li>
<!--- endfor -->
</ul>''')
assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "
"<li>1</li>\n <li>2</li>\n</ul>")
def test_string_escapes(self):
for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':
tmpl = env.from_string('{{ %s }}' % jinja_string_repr(char))
assert tmpl.render() == char
assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'
def test_bytefallback(self):
from pprint import pformat
tmpl = env.from_string(u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''')
assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')
def test_operators(self):
from jinja2.lexer import operators
for test, expect in operators.iteritems():
if test in '([{}])':
continue
stream = env.lexer.tokenize('{{ %s }}' % test)
stream.next()
assert stream.current.type == expect
def test_normalizing(self):
for seq in '\r', '\r\n', '\n':
env = Environment(newline_sequence=seq)
tmpl = env.from_string('1\n2\r\n3\n4\n')
result = tmpl.render()
assert result.replace(seq, 'X') == '1X2X3X4'
class ParserTestCase(JinjaTestCase):
def test_php_syntax(self):
env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')
tmpl = env.from_string('''\
<!-- I'm a comment, I'm not interesting -->\
<? for item in seq -?>
<?= item ?>
<?- endfor ?>''')
assert tmpl.render(seq=range(5)) == '01234'
def test_erb_syntax(self):
env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')
tmpl = env.from_string('''\
<%# I'm a comment, I'm not interesting %>\
<% for item in seq -%>
<%= item %>
<%- endfor %>''')
assert tmpl.render(seq=range(5)) == '01234'
def test_comment_syntax(self):
env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')
tmpl = env.from_string('''\
<!--# I'm a comment, I'm not interesting -->\
<!-- for item in seq --->
${item}
<!--- endfor -->''')
assert tmpl.render(seq=range(5)) == '01234'
def test_balancing(self):
tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')
assert tmpl.render() == 'bar'
def test_start_comment(self):
tmpl = env.from_string('''{# foo comment
and bar comment #}
{% macro blub() %}foo{% endmacro %}
{{ blub() }}''')
assert tmpl.render().strip() == 'foo'
def test_line_syntax(self):
env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')
tmpl = env.from_string('''\
<%# regular comment %>
% for item in seq:
${item}
% endfor''')
assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \
range(5)
env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')
tmpl = env.from_string('''\
<%# regular comment %>
% for item in seq:
${item} ## the rest of the stuff
% endfor''')
assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \
range(5)
def test_line_syntax_priority(self):
# XXX: why is the whitespace there in front of the newline?
env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')
tmpl = env.from_string('''\
/* ignore me.
I'm a multiline comment */
## for item in seq:
* ${item} # this is just extra stuff
## endfor''')
assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'
env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')
tmpl = env.from_string('''\
/* ignore me.
I'm a multiline comment */
# for item in seq:
* ${item} ## this is just extra stuff
## extra stuff i just want to ignore
# endfor''')
assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'
def test_error_messages(self):
def assert_error(code, expected):
try:
Template(code)
except TemplateSyntaxError, e:
assert str(e) == expected, 'unexpected error message'
else:
assert False, 'that was suposed to be an error'
assert_error('{% for item in seq %}...{% endif %}',
"Encountered unknown tag 'endif'. Jinja was looking "
"for the following tags: 'endfor' or 'else'. The "
"innermost block that needs to be closed is 'for'.")
assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',
"Encountered unknown tag 'endfor'. Jinja was looking for "
"the following tags: 'elif' or 'else' or 'endif'. The "
"innermost block that needs to be closed is 'if'.")
assert_error('{% if foo %}',
"Unexpected end of template. Jinja was looking for the "
"following tags: 'elif' or 'else' or 'endif'. The "
"innermost block that needs to be closed is 'if'.")
assert_error('{% for item in seq %}',
"Unexpected end of template. Jinja was looking for the "
"following tags: 'endfor' or 'else'. The innermost block "
"that needs to be closed is 'for'.")
assert_error('{% block foo-bar-baz %}',
"Block names in Jinja have to be valid Python identifiers "
"and may not contain hypens, use an underscore instead.")
assert_error('{% unknown_tag %}',
"Encountered unknown tag 'unknown_tag'.")
class SyntaxTestCase(JinjaTestCase):
def test_call(self):
env = Environment()
env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g
tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")
assert tmpl.render() == 'abdfh'
def test_slicing(self):
tmpl = env.from_string('{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}')
assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
def test_attr(self):
tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")
assert tmpl.render(foo={'bar': 42}) == '42|42'
def test_subscript(self):
tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")
assert tmpl.render(foo=[0, 1, 2]) == '0|2'
def test_tuple(self):
tmpl = env.from_string('{{ () }}|{{ (1,) }}|{{ (1, 2) }}')
assert tmpl.render() == '()|(1,)|(1, 2)'
def test_math(self):
tmpl = env.from_string('{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}')
assert tmpl.render() == '1.5|8'
def test_div(self):
tmpl = env.from_string('{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}')
assert tmpl.render() == '1|1.5|1'
def test_unary(self):
tmpl = env.from_string('{{ +3 }}|{{ -3 }}')
assert tmpl.render() == '3|-3'
def test_concat(self):
tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")
assert tmpl.render() == '[1, 2]foo'
def test_compare(self):
tmpl = env.from_string('{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|'
'{{ 2 == 2 }}|{{ 1 <= 1 }}')
assert tmpl.render() == 'True|True|True|True|True'
def test_inop(self):
tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}')
assert tmpl.render() == 'True|False'
def test_literals(self):
tmpl = env.from_string('{{ [] }}|{{ {} }}|{{ () }}')
assert tmpl.render().lower() == '[]|{}|()'
def test_bool(self):
tmpl = env.from_string('{{ true and false }}|{{ false '
'or true }}|{{ not false }}')
assert tmpl.render() == 'False|True|True'
def test_grouping(self):
tmpl = env.from_string('{{ (true and false) or (false and true) and not false }}')
assert tmpl.render() == 'False'
def test_django_attr(self):
tmpl = env.from_string('{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}')
assert tmpl.render() == '1|1'
def test_conditional_expression(self):
tmpl = env.from_string('''{{ 0 if true else 1 }}''')
assert tmpl.render() == '0'
def test_short_conditional_expression(self):
tmpl = env.from_string('<{{ 1 if false }}>')
assert tmpl.render() == '<>'
tmpl = env.from_string('<{{ (1 if false).bar }}>')
self.assert_raises(UndefinedError, tmpl.render)
def test_filter_priority(self):
tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')
assert tmpl.render() == 'FOOBAR'
def test_function_calls(self):
tests = [
(True, '*foo, bar'),
(True, '*foo, *bar'),
(True, '*foo, bar=42'),
(True, '**foo, *bar'),
(True, '**foo, bar'),
(False, 'foo, bar'),
(False, 'foo, bar=42'),
(False, 'foo, bar=23, *args'),
(False, 'a, b=c, *d, **e'),
(False, '*foo, **bar')
]
for should_fail, sig in tests:
if should_fail:
self.assert_raises(TemplateSyntaxError,
env.from_string, '{{ foo(%s) }}' % sig)
else:
env.from_string('foo(%s)' % sig)
def test_tuple_expr(self):
for tmpl in [
'{{ () }}',
'{{ (1, 2) }}',
'{{ (1, 2,) }}',
'{{ 1, }}',
'{{ 1, 2 }}',
'{% for foo, bar in seq %}...{% endfor %}',
'{% for x in foo, bar %}...{% endfor %}',
'{% for x in foo, %}...{% endfor %}'
]:
assert env.from_string(tmpl)
def test_trailing_comma(self):
tmpl = env.from_string('{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}')
assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'
def test_block_end_name(self):
env.from_string('{% block foo %}...{% endblock foo %}')
self.assert_raises(TemplateSyntaxError, env.from_string,
'{% block x %}{% endblock y %}')
def test_contant_casing(self):
for const in True, False, None:
tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % (
str(const), str(const).lower(), str(const).upper()
))
assert tmpl.render() == '%s|%s|' % (const, const)
def test_test_chaining(self):
self.assert_raises(TemplateSyntaxError, env.from_string,
'{{ foo is string is sequence }}')
env.from_string('{{ 42 is string or 42 is number }}'
).render() == 'True'
def test_string_concatenation(self):
tmpl = env.from_string('{{ "foo" "bar" "baz" }}')
assert tmpl.render() == 'foobarbaz'
def test_notin(self):
bar = xrange(100)
tmpl = env.from_string('''{{ not 42 in bar }}''')
assert tmpl.render(bar=bar) == unicode(not 42 in bar)
def test_implicit_subscribed_tuple(self):
class Foo(object):
def __getitem__(self, x):
return x
t = env.from_string('{{ foo[1, 2] }}')
assert t.render(foo=Foo()) == u'(1, 2)'
def test_raw2(self):
tmpl = env.from_string('{% raw %}{{ FOO }} and {% BAR %}{% endraw %}')
assert tmpl.render() == '{{ FOO }} and {% BAR %}'
def test_const(self):
tmpl = env.from_string('{{ true }}|{{ false }}|{{ none }}|'
'{{ none is defined }}|{{ missing is defined }}')
assert tmpl.render() == 'True|False|None|True|False'
def test_neg_filter_priority(self):
node = env.parse('{{ -1|foo }}')
assert isinstance(node.body[0].nodes[0], nodes.Filter)
assert isinstance(node.body[0].nodes[0].node, nodes.Neg)
def test_const_assign(self):
constass1 = '''{% set true = 42 %}'''
constass2 = '''{% for none in seq %}{% endfor %}'''
for tmpl in constass1, constass2:
self.assert_raises(TemplateSyntaxError, env.from_string, tmpl)
def test_localset(self):
tmpl = env.from_string('''{% set foo = 0 %}\
{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\
{{ foo }}''')
assert tmpl.render() == '0'
def test_parse_unary(self):
tmpl = env.from_string('{{ -foo["bar"] }}')
assert tmpl.render(foo={'bar': 42}) == '-42'
tmpl = env.from_string('{{ -foo["bar"]|abs }}')
assert tmpl.render(foo={'bar': 42}) == '42'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(LexerTestCase))
suite.addTest(unittest.makeSuite(ParserTestCase))
suite.addTest(unittest.makeSuite(SyntaxTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.imports
~~~~~~~~~~~~~~~~~~~~~~~~
Tests the import features (with includes).
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Environment, DictLoader
from jinja2.exceptions import TemplateNotFound, TemplatesNotFound
test_env = Environment(loader=DictLoader(dict(
module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',
header='[{{ foo }}|{{ 23 }}]',
o_printer='({{ o }})'
)))
test_env.globals['bar'] = 23
class ImportsTestCase(JinjaTestCase):
def test_context_imports(self):
t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')
assert t.render(foo=42) == '[|23]'
t = test_env.from_string('{% import "module" as m without context %}{{ m.test() }}')
assert t.render(foo=42) == '[|23]'
t = test_env.from_string('{% import "module" as m with context %}{{ m.test() }}')
assert t.render(foo=42) == '[42|23]'
t = test_env.from_string('{% from "module" import test %}{{ test() }}')
assert t.render(foo=42) == '[|23]'
t = test_env.from_string('{% from "module" import test without context %}{{ test() }}')
assert t.render(foo=42) == '[|23]'
t = test_env.from_string('{% from "module" import test with context %}{{ test() }}')
assert t.render(foo=42) == '[42|23]'
def test_trailing_comma(self):
test_env.from_string('{% from "foo" import bar, baz with context %}')
test_env.from_string('{% from "foo" import bar, baz, with context %}')
test_env.from_string('{% from "foo" import bar, with context %}')
test_env.from_string('{% from "foo" import bar, with, context %}')
test_env.from_string('{% from "foo" import bar, with with context %}')
def test_exports(self):
m = test_env.from_string('''
{% macro toplevel() %}...{% endmacro %}
{% macro __private() %}...{% endmacro %}
{% set variable = 42 %}
{% for item in [1] %}
{% macro notthere() %}{% endmacro %}
{% endfor %}
''').module
assert m.toplevel() == '...'
assert not hasattr(m, '__missing')
assert m.variable == 42
assert not hasattr(m, 'notthere')
class IncludesTestCase(JinjaTestCase):
def test_context_include(self):
t = test_env.from_string('{% include "header" %}')
assert t.render(foo=42) == '[42|23]'
t = test_env.from_string('{% include "header" with context %}')
assert t.render(foo=42) == '[42|23]'
t = test_env.from_string('{% include "header" without context %}')
assert t.render(foo=42) == '[|23]'
def test_choice_includes(self):
t = test_env.from_string('{% include ["missing", "header"] %}')
assert t.render(foo=42) == '[42|23]'
t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}')
assert t.render(foo=42) == ''
t = test_env.from_string('{% include ["missing", "missing2"] %}')
self.assert_raises(TemplateNotFound, t.render)
try:
t.render()
except TemplatesNotFound, e:
assert e.templates == ['missing', 'missing2']
assert e.name == 'missing2'
else:
assert False, 'thou shalt raise'
def test_includes(t, **ctx):
ctx['foo'] = 42
assert t.render(ctx) == '[42|23]'
t = test_env.from_string('{% include ["missing", "header"] %}')
test_includes(t)
t = test_env.from_string('{% include x %}')
test_includes(t, x=['missing', 'header'])
t = test_env.from_string('{% include [x, "header"] %}')
test_includes(t, x='missing')
t = test_env.from_string('{% include x %}')
test_includes(t, x='header')
t = test_env.from_string('{% include x %}')
test_includes(t, x='header')
t = test_env.from_string('{% include [x] %}')
test_includes(t, x='header')
def test_include_ignoring_missing(self):
t = test_env.from_string('{% include "missing" %}')
self.assert_raises(TemplateNotFound, t.render)
for extra in '', 'with context', 'without context':
t = test_env.from_string('{% include "missing" ignore missing ' +
extra + ' %}')
assert t.render() == ''
def test_context_include_with_overrides(self):
env = Environment(loader=DictLoader(dict(
main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
item="{{ item }}"
)))
assert env.get_template("main").render() == "123"
def test_unoptimized_scopes(self):
t = test_env.from_string("""
{% macro outer(o) %}
{% macro inner() %}
{% include "o_printer" %}
{% endmacro %}
{{ inner() }}
{% endmacro %}
{{ outer("FOO") }}
""")
assert t.render().strip() == '(FOO)'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ImportsTestCase))
suite.addTest(unittest.makeSuite(IncludesTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.core_tags
~~~~~~~~~~~~~~~~~~~~~~~~~~
Test the core tags like for and if.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Environment, TemplateSyntaxError, UndefinedError, \
DictLoader
env = Environment()
class ForLoopTestCase(JinjaTestCase):
def test_simple(self):
tmpl = env.from_string('{% for item in seq %}{{ item }}{% endfor %}')
assert tmpl.render(seq=range(10)) == '0123456789'
def test_else(self):
tmpl = env.from_string('{% for item in seq %}XXX{% else %}...{% endfor %}')
assert tmpl.render() == '...'
def test_empty_blocks(self):
tmpl = env.from_string('<{% for item in seq %}{% else %}{% endfor %}>')
assert tmpl.render() == '<>'
def test_context_vars(self):
tmpl = env.from_string('''{% for item in seq -%}
{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{
loop.length }}###{% endfor %}''')
one, two, _ = tmpl.render(seq=[0, 1]).split('###')
(one_index, one_index0, one_revindex, one_revindex0, one_first,
one_last, one_length) = one.split('|')
(two_index, two_index0, two_revindex, two_revindex0, two_first,
two_last, two_length) = two.split('|')
assert int(one_index) == 1 and int(two_index) == 2
assert int(one_index0) == 0 and int(two_index0) == 1
assert int(one_revindex) == 2 and int(two_revindex) == 1
assert int(one_revindex0) == 1 and int(two_revindex0) == 0
assert one_first == 'True' and two_first == 'False'
assert one_last == 'False' and two_last == 'True'
assert one_length == two_length == '2'
def test_cycling(self):
tmpl = env.from_string('''{% for item in seq %}{{
loop.cycle('<1>', '<2>') }}{% endfor %}{%
for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')
output = tmpl.render(seq=range(4), through=('<1>', '<2>'))
assert output == '<1><2>' * 4
def test_scope(self):
tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')
output = tmpl.render(seq=range(10))
assert not output
def test_varlen(self):
def inner():
for item in range(5):
yield item
tmpl = env.from_string('{% for item in iter %}{{ item }}{% endfor %}')
output = tmpl.render(iter=inner())
assert output == '01234'
def test_noniter(self):
tmpl = env.from_string('{% for item in none %}...{% endfor %}')
self.assert_raises(TypeError, tmpl.render)
def test_recursive(self):
tmpl = env.from_string('''{% for item in seq recursive -%}
[{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
{%- endfor %}''')
assert tmpl.render(seq=[
dict(a=1, b=[dict(a=1), dict(a=2)]),
dict(a=2, b=[dict(a=1), dict(a=2)]),
dict(a=3, b=[dict(a='a')])
]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'
def test_looploop(self):
tmpl = env.from_string('''{% for row in table %}
{%- set rowloop = loop -%}
{% for cell in row -%}
[{{ rowloop.index }}|{{ loop.index }}]
{%- endfor %}
{%- endfor %}''')
assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'
def test_reversed_bug(self):
tmpl = env.from_string('{% for i in items %}{{ i }}'
'{% if not loop.last %}'
',{% endif %}{% endfor %}')
assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'
def test_loop_errors(self):
tmpl = env.from_string('''{% for item in [1] if loop.index
== 0 %}...{% endfor %}''')
self.assert_raises(UndefinedError, tmpl.render)
tmpl = env.from_string('''{% for item in [] %}...{% else
%}{{ loop }}{% endfor %}''')
assert tmpl.render() == ''
def test_loop_filter(self):
tmpl = env.from_string('{% for item in range(10) if item '
'is even %}[{{ item }}]{% endfor %}')
assert tmpl.render() == '[0][2][4][6][8]'
tmpl = env.from_string('''
{%- for item in range(10) if item is even %}[{{
loop.index }}:{{ item }}]{% endfor %}''')
assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'
def test_loop_unassignable(self):
self.assert_raises(TemplateSyntaxError, env.from_string,
'{% for loop in seq %}...{% endfor %}')
def test_scoped_special_var(self):
t = env.from_string('{% for s in seq %}[{{ loop.first }}{% for c in s %}'
'|{{ loop.first }}{% endfor %}]{% endfor %}')
assert t.render(seq=('ab', 'cd')) == '[True|True|False][False|True|False]'
def test_scoped_loop_var(self):
t = env.from_string('{% for x in seq %}{{ loop.first }}'
'{% for y in seq %}{% endfor %}{% endfor %}')
assert t.render(seq='ab') == 'TrueFalse'
t = env.from_string('{% for x in seq %}{% for y in seq %}'
'{{ loop.first }}{% endfor %}{% endfor %}')
assert t.render(seq='ab') == 'TrueFalseTrueFalse'
def test_recursive_empty_loop_iter(self):
t = env.from_string('''
{%- for item in foo recursive -%}{%- endfor -%}
''')
assert t.render(dict(foo=[])) == ''
def test_call_in_loop(self):
t = env.from_string('''
{%- macro do_something() -%}
[{{ caller() }}]
{%- endmacro %}
{%- for i in [1, 2, 3] %}
{%- call do_something() -%}
{{ i }}
{%- endcall %}
{%- endfor -%}
''')
assert t.render() == '[1][2][3]'
def test_scoping_bug(self):
t = env.from_string('''
{%- for item in foo %}...{{ item }}...{% endfor %}
{%- macro item(a) %}...{{ a }}...{% endmacro %}
{{- item(2) -}}
''')
assert t.render(foo=(1,)) == '...1......2...'
def test_unpacking(self):
tmpl = env.from_string('{% for a, b, c in [[1, 2, 3]] %}'
'{{ a }}|{{ b }}|{{ c }}{% endfor %}')
assert tmpl.render() == '1|2|3'
class IfConditionTestCase(JinjaTestCase):
def test_simple(self):
tmpl = env.from_string('''{% if true %}...{% endif %}''')
assert tmpl.render() == '...'
def test_elif(self):
tmpl = env.from_string('''{% if false %}XXX{% elif true
%}...{% else %}XXX{% endif %}''')
assert tmpl.render() == '...'
def test_else(self):
tmpl = env.from_string('{% if false %}XXX{% else %}...{% endif %}')
assert tmpl.render() == '...'
def test_empty(self):
tmpl = env.from_string('[{% if true %}{% else %}{% endif %}]')
assert tmpl.render() == '[]'
def test_complete(self):
tmpl = env.from_string('{% if a %}A{% elif b %}B{% elif c == d %}'
'C{% else %}D{% endif %}')
assert tmpl.render(a=0, b=False, c=42, d=42.0) == 'C'
def test_no_scope(self):
tmpl = env.from_string('{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}')
assert tmpl.render(a=True) == '1'
tmpl = env.from_string('{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}')
assert tmpl.render() == '1'
class MacrosTestCase(JinjaTestCase):
env = Environment(trim_blocks=True)
def test_simple(self):
tmpl = self.env.from_string('''\
{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}
{{ say_hello('Peter') }}''')
assert tmpl.render() == 'Hello Peter!'
def test_scoping(self):
tmpl = self.env.from_string('''\
{% macro level1(data1) %}
{% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}
{{ level2('bar') }}{% endmacro %}
{{ level1('foo') }}''')
assert tmpl.render() == 'foo|bar'
def test_arguments(self):
tmpl = self.env.from_string('''\
{% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}
{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}''')
assert tmpl.render() == '||c|d|a||c|d|a|b|c|d|1|2|3|d'
def test_varargs(self):
tmpl = self.env.from_string('''\
{% macro test() %}{{ varargs|join('|') }}{% endmacro %}\
{{ test(1, 2, 3) }}''')
assert tmpl.render() == '1|2|3'
def test_simple_call(self):
tmpl = self.env.from_string('''\
{% macro test() %}[[{{ caller() }}]]{% endmacro %}\
{% call test() %}data{% endcall %}''')
assert tmpl.render() == '[[data]]'
def test_complex_call(self):
tmpl = self.env.from_string('''\
{% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\
{% call(data) test() %}{{ data }}{% endcall %}''')
assert tmpl.render() == '[[data]]'
def test_caller_undefined(self):
tmpl = self.env.from_string('''\
{% set caller = 42 %}\
{% macro test() %}{{ caller is not defined }}{% endmacro %}\
{{ test() }}''')
assert tmpl.render() == 'True'
def test_include(self):
self.env = Environment(loader=DictLoader({'include':
'{% macro test(foo) %}[{{ foo }}]{% endmacro %}'}))
tmpl = self.env.from_string('{% from "include" import test %}{{ test("foo") }}')
assert tmpl.render() == '[foo]'
def test_macro_api(self):
tmpl = self.env.from_string('{% macro foo(a, b) %}{% endmacro %}'
'{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}'
'{% macro baz() %}{{ caller() }}{% endmacro %}')
assert tmpl.module.foo.arguments == ('a', 'b')
assert tmpl.module.foo.defaults == ()
assert tmpl.module.foo.name == 'foo'
assert not tmpl.module.foo.caller
assert not tmpl.module.foo.catch_kwargs
assert not tmpl.module.foo.catch_varargs
assert tmpl.module.bar.arguments == ()
assert tmpl.module.bar.defaults == ()
assert not tmpl.module.bar.caller
assert tmpl.module.bar.catch_kwargs
assert tmpl.module.bar.catch_varargs
assert tmpl.module.baz.caller
def test_callself(self):
tmpl = self.env.from_string('{% macro foo(x) %}{{ x }}{% if x > 1 %}|'
'{{ foo(x - 1) }}{% endif %}{% endmacro %}'
'{{ foo(5) }}')
assert tmpl.render() == '5|4|3|2|1'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ForLoopTestCase))
suite.addTest(unittest.makeSuite(IfConditionTestCase))
suite.addTest(unittest.makeSuite(MacrosTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.tests
~~~~~~~~~~~~~~~~~~~~~~
Who tests the tests?
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Markup, Environment
env = Environment()
class TestsTestCase(JinjaTestCase):
def test_defined(self):
tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}')
assert tmpl.render() == 'False|True'
def test_even(self):
tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''')
assert tmpl.render() == 'False|True'
def test_odd(self):
tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''')
assert tmpl.render() == 'True|False'
def test_lower(self):
tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''')
assert tmpl.render() == 'True|False'
def test_typechecks(self):
tmpl = env.from_string('''
{{ 42 is undefined }}
{{ 42 is defined }}
{{ 42 is none }}
{{ none is none }}
{{ 42 is number }}
{{ 42 is string }}
{{ "foo" is string }}
{{ "foo" is sequence }}
{{ [1] is sequence }}
{{ range is callable }}
{{ 42 is callable }}
{{ range(5) is iterable }}
{{ {} is mapping }}
{{ mydict is mapping }}
{{ [] is mapping }}
''')
class MyDict(dict):
pass
assert tmpl.render(mydict=MyDict()).split() == [
'False', 'True', 'False', 'True', 'True', 'False',
'True', 'True', 'True', 'True', 'False', 'True',
'True', 'True', 'False'
]
def test_sequence(self):
tmpl = env.from_string(
'{{ [1, 2, 3] is sequence }}|'
'{{ "foo" is sequence }}|'
'{{ 42 is sequence }}'
)
assert tmpl.render() == 'True|True|False'
def test_upper(self):
tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')
assert tmpl.render() == 'True|False'
def test_sameas(self):
tmpl = env.from_string('{{ foo is sameas false }}|'
'{{ 0 is sameas false }}')
assert tmpl.render(foo=False) == 'True|False'
def test_no_paren_for_arg1(self):
tmpl = env.from_string('{{ foo is sameas none }}')
assert tmpl.render(foo=None) == 'True'
def test_escaped(self):
env = Environment(autoescape=True)
tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}')
assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestsTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.filters
~~~~~~~~~~~~~~~~~~~~~~~~
Tests for the jinja filters.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Markup, Environment
env = Environment()
class FilterTestCase(JinjaTestCase):
def test_capitalize(self):
tmpl = env.from_string('{{ "foo bar"|capitalize }}')
assert tmpl.render() == 'Foo bar'
def test_center(self):
tmpl = env.from_string('{{ "foo"|center(9) }}')
assert tmpl.render() == ' foo '
def test_default(self):
tmpl = env.from_string(
"{{ missing|default('no') }}|{{ false|default('no') }}|"
"{{ false|default('no', true) }}|{{ given|default('no') }}"
)
assert tmpl.render(given='yes') == 'no|False|no|yes'
def test_dictsort(self):
tmpl = env.from_string(
'{{ foo|dictsort }}|'
'{{ foo|dictsort(true) }}|'
'{{ foo|dictsort(false, "value") }}'
)
out = tmpl.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})
assert out == ("[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]|"
"[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]|"
"[('aa', 0), ('b', 1), ('c', 2), ('AB', 3)]")
def test_batch(self):
tmpl = env.from_string("{{ foo|batch(3)|list }}|"
"{{ foo|batch(3, 'X')|list }}")
out = tmpl.render(foo=range(10))
assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"
"[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")
def test_slice(self):
tmpl = env.from_string('{{ foo|slice(3)|list }}|'
'{{ foo|slice(3, "X")|list }}')
out = tmpl.render(foo=range(10))
assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"
"[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")
def test_escape(self):
tmpl = env.from_string('''{{ '<">&'|escape }}''')
out = tmpl.render()
assert out == '<">&'
def test_striptags(self):
tmpl = env.from_string('''{{ foo|striptags }}''')
out = tmpl.render(foo=' <p>just a small \n <a href="#">'
'example</a> link</p>\n<p>to a webpage</p> '
'<!-- <p>and some commented stuff</p> -->')
assert out == 'just a small example link to a webpage'
def test_filesizeformat(self):
tmpl = env.from_string(
'{{ 100|filesizeformat }}|'
'{{ 1000|filesizeformat }}|'
'{{ 1000000|filesizeformat }}|'
'{{ 1000000000|filesizeformat }}|'
'{{ 1000000000000|filesizeformat }}|'
'{{ 100|filesizeformat(true) }}|'
'{{ 1000|filesizeformat(true) }}|'
'{{ 1000000|filesizeformat(true) }}|'
'{{ 1000000000|filesizeformat(true) }}|'
'{{ 1000000000000|filesizeformat(true) }}'
)
out = tmpl.render()
assert out == (
'100 Bytes|0.0 kB|0.0 MB|0.0 GB|0.0 TB|100 Bytes|'
'1000 Bytes|1.0 KiB|0.9 MiB|0.9 GiB'
)
def test_first(self):
tmpl = env.from_string('{{ foo|first }}')
out = tmpl.render(foo=range(10))
assert out == '0'
def test_float(self):
tmpl = env.from_string('{{ "42"|float }}|'
'{{ "ajsghasjgd"|float }}|'
'{{ "32.32"|float }}')
out = tmpl.render()
assert out == '42.0|0.0|32.32'
def test_format(self):
tmpl = env.from_string('''{{ "%s|%s"|format("a", "b") }}''')
out = tmpl.render()
assert out == 'a|b'
def test_indent(self):
tmpl = env.from_string('{{ foo|indent(2) }}|{{ foo|indent(2, true) }}')
text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2)
out = tmpl.render(foo=text)
assert out == ('foo bar foo bar\n foo bar foo bar| '
'foo bar foo bar\n foo bar foo bar')
def test_int(self):
tmpl = env.from_string('{{ "42"|int }}|{{ "ajsghasjgd"|int }}|'
'{{ "32.32"|int }}')
out = tmpl.render()
assert out == '42|0|32'
def test_join(self):
tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')
out = tmpl.render()
assert out == '1|2|3'
env2 = Environment(autoescape=True)
tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')
assert tmpl.render() == '<foo><span>foo</span>'
def test_join_attribute(self):
class User(object):
def __init__(self, username):
self.username = username
tmpl = env.from_string('''{{ users|join(', ', 'username') }}''')
assert tmpl.render(users=map(User, ['foo', 'bar'])) == 'foo, bar'
def test_last(self):
tmpl = env.from_string('''{{ foo|last }}''')
out = tmpl.render(foo=range(10))
assert out == '9'
def test_length(self):
tmpl = env.from_string('''{{ "hello world"|length }}''')
out = tmpl.render()
assert out == '11'
def test_lower(self):
tmpl = env.from_string('''{{ "FOO"|lower }}''')
out = tmpl.render()
assert out == 'foo'
def test_pprint(self):
from pprint import pformat
tmpl = env.from_string('''{{ data|pprint }}''')
data = range(1000)
assert tmpl.render(data=data) == pformat(data)
def test_random(self):
tmpl = env.from_string('''{{ seq|random }}''')
seq = range(100)
for _ in range(10):
assert int(tmpl.render(seq=seq)) in seq
def test_reverse(self):
tmpl = env.from_string('{{ "foobar"|reverse|join }}|'
'{{ [1, 2, 3]|reverse|list }}')
assert tmpl.render() == 'raboof|[3, 2, 1]'
def test_string(self):
x = [1, 2, 3, 4, 5]
tmpl = env.from_string('''{{ obj|string }}''')
assert tmpl.render(obj=x) == unicode(x)
def test_title(self):
tmpl = env.from_string('''{{ "foo bar"|title }}''')
assert tmpl.render() == "Foo Bar"
def test_truncate(self):
tmpl = env.from_string(
'{{ data|truncate(15, true, ">>>") }}|'
'{{ data|truncate(15, false, ">>>") }}|'
'{{ smalldata|truncate(15) }}'
)
out = tmpl.render(data='foobar baz bar' * 1000,
smalldata='foobar baz bar')
assert out == 'foobar baz barf>>>|foobar baz >>>|foobar baz bar'
def test_upper(self):
tmpl = env.from_string('{{ "foo"|upper }}')
assert tmpl.render() == 'FOO'
def test_urlize(self):
tmpl = env.from_string('{{ "foo http://www.example.com/ bar"|urlize }}')
assert tmpl.render() == 'foo <a href="http://www.example.com/">'\
'http://www.example.com/</a> bar'
def test_wordcount(self):
tmpl = env.from_string('{{ "foo bar baz"|wordcount }}')
assert tmpl.render() == '3'
def test_block(self):
tmpl = env.from_string('{% filter lower|escape %}<HEHE>{% endfilter %}')
assert tmpl.render() == '<hehe>'
def test_chaining(self):
tmpl = env.from_string('''{{ ['<foo>', '<bar>']|first|upper|escape }}''')
assert tmpl.render() == '<FOO>'
def test_sum(self):
tmpl = env.from_string('''{{ [1, 2, 3, 4, 5, 6]|sum }}''')
assert tmpl.render() == '21'
def test_sum_attributes(self):
tmpl = env.from_string('''{{ values|sum('value') }}''')
assert tmpl.render(values=[
{'value': 23},
{'value': 1},
{'value': 18},
]) == '42'
def test_sum_attributes_nested(self):
tmpl = env.from_string('''{{ values|sum('real.value') }}''')
assert tmpl.render(values=[
{'real': {'value': 23}},
{'real': {'value': 1}},
{'real': {'value': 18}},
]) == '42'
def test_abs(self):
tmpl = env.from_string('''{{ -1|abs }}|{{ 1|abs }}''')
assert tmpl.render() == '1|1', tmpl.render()
def test_round_positive(self):
tmpl = env.from_string('{{ 2.7|round }}|{{ 2.1|round }}|'
"{{ 2.1234|round(3, 'floor') }}|"
"{{ 2.1|round(0, 'ceil') }}")
assert tmpl.render() == '3.0|2.0|2.123|3.0', tmpl.render()
def test_round_negative(self):
tmpl = env.from_string('{{ 21.3|round(-1)}}|'
"{{ 21.3|round(-1, 'ceil')}}|"
"{{ 21.3|round(-1, 'floor')}}")
assert tmpl.render() == '20.0|30.0|20.0',tmpl.render()
def test_xmlattr(self):
tmpl = env.from_string("{{ {'foo': 42, 'bar': 23, 'fish': none, "
"'spam': missing, 'blub:blub': '<?>'}|xmlattr }}")
out = tmpl.render().split()
assert len(out) == 3
assert 'foo="42"' in out
assert 'bar="23"' in out
assert 'blub:blub="<?>"' in out
def test_sort1(self):
tmpl = env.from_string('{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}')
assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
def test_sort2(self):
tmpl = env.from_string('{{ "".join(["c", "A", "b", "D"]|sort) }}')
assert tmpl.render() == 'AbcD'
def test_sort3(self):
tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')
assert tmpl.render() == "['Bar', 'blah', 'foo']"
def test_sort4(self):
class Magic(object):
def __init__(self, value):
self.value = value
def __unicode__(self):
return unicode(self.value)
tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')
assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'
def test_groupby(self):
tmpl = env.from_string('''
{%- for grouper, list in [{'foo': 1, 'bar': 2},
{'foo': 2, 'bar': 3},
{'foo': 1, 'bar': 1},
{'foo': 3, 'bar': 4}]|groupby('foo') -%}
{{ grouper }}{% for x in list %}: {{ x.foo }}, {{ x.bar }}{% endfor %}|
{%- endfor %}''')
assert tmpl.render().split('|') == [
"1: 1, 2: 1, 1",
"2: 2, 3",
"3: 3, 4",
""
]
def test_groupby_tuple_index(self):
tmpl = env.from_string('''
{%- for grouper, list in [('a', 1), ('a', 2), ('b', 1)]|groupby(0) -%}
{{ grouper }}{% for x in list %}:{{ x.1 }}{% endfor %}|
{%- endfor %}''')
assert tmpl.render() == 'a:1:2|b:1|'
def test_groupby_multidot(self):
class Date(object):
def __init__(self, day, month, year):
self.day = day
self.month = month
self.year = year
class Article(object):
def __init__(self, title, *date):
self.date = Date(*date)
self.title = title
articles = [
Article('aha', 1, 1, 1970),
Article('interesting', 2, 1, 1970),
Article('really?', 3, 1, 1970),
Article('totally not', 1, 1, 1971)
]
tmpl = env.from_string('''
{%- for year, list in articles|groupby('date.year') -%}
{{ year }}{% for x in list %}[{{ x.title }}]{% endfor %}|
{%- endfor %}''')
assert tmpl.render(articles=articles).split('|') == [
'1970[aha][interesting][really?]',
'1971[totally not]',
''
]
def test_filtertag(self):
tmpl = env.from_string("{% filter upper|replace('FOO', 'foo') %}"
"foobar{% endfilter %}")
assert tmpl.render() == 'fooBAR'
def test_replace(self):
env = Environment()
tmpl = env.from_string('{{ string|replace("o", 42) }}')
assert tmpl.render(string='<foo>') == '<f4242>'
env = Environment(autoescape=True)
tmpl = env.from_string('{{ string|replace("o", 42) }}')
assert tmpl.render(string='<foo>') == '<f4242>'
tmpl = env.from_string('{{ string|replace("<", 42) }}')
assert tmpl.render(string='<foo>') == '42foo>'
tmpl = env.from_string('{{ string|replace("o", ">x<") }}')
assert tmpl.render(string=Markup('foo')) == 'f>x<>x<'
def test_forceescape(self):
tmpl = env.from_string('{{ x|forceescape }}')
assert tmpl.render(x=Markup('<div />')) == u'<div />'
def test_safe(self):
env = Environment(autoescape=True)
tmpl = env.from_string('{{ "<div>foo</div>"|safe }}')
assert tmpl.render() == '<div>foo</div>'
tmpl = env.from_string('{{ "<div>foo</div>" }}')
assert tmpl.render() == '<div>foo</div>'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(FilterTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.regression
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests corner cases and bugs.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \
TemplateNotFound, PrefixLoader
env = Environment()
class CornerTestCase(JinjaTestCase):
def test_assigned_scoping(self):
t = env.from_string('''
{%- for item in (1, 2, 3, 4) -%}
[{{ item }}]
{%- endfor %}
{{- item -}}
''')
assert t.render(item=42) == '[1][2][3][4]42'
t = env.from_string('''
{%- for item in (1, 2, 3, 4) -%}
[{{ item }}]
{%- endfor %}
{%- set item = 42 %}
{{- item -}}
''')
assert t.render() == '[1][2][3][4]42'
t = env.from_string('''
{%- set item = 42 %}
{%- for item in (1, 2, 3, 4) -%}
[{{ item }}]
{%- endfor %}
{{- item -}}
''')
assert t.render() == '[1][2][3][4]42'
def test_closure_scoping(self):
t = env.from_string('''
{%- set wrapper = "<FOO>" %}
{%- for item in (1, 2, 3, 4) %}
{%- macro wrapper() %}[{{ item }}]{% endmacro %}
{{- wrapper() }}
{%- endfor %}
{{- wrapper -}}
''')
assert t.render() == '[1][2][3][4]<FOO>'
t = env.from_string('''
{%- for item in (1, 2, 3, 4) %}
{%- macro wrapper() %}[{{ item }}]{% endmacro %}
{{- wrapper() }}
{%- endfor %}
{%- set wrapper = "<FOO>" %}
{{- wrapper -}}
''')
assert t.render() == '[1][2][3][4]<FOO>'
t = env.from_string('''
{%- for item in (1, 2, 3, 4) %}
{%- macro wrapper() %}[{{ item }}]{% endmacro %}
{{- wrapper() }}
{%- endfor %}
{{- wrapper -}}
''')
assert t.render(wrapper=23) == '[1][2][3][4]23'
class BugTestCase(JinjaTestCase):
def test_keyword_folding(self):
env = Environment()
env.filters['testing'] = lambda value, some: value + some
assert env.from_string("{{ 'test'|testing(some='stuff') }}") \
.render() == 'teststuff'
def test_extends_output_bugs(self):
env = Environment(loader=DictLoader({
'parent.html': '(({% block title %}{% endblock %}))'
}))
t = env.from_string('{% if expr %}{% extends "parent.html" %}{% endif %}'
'[[{% block title %}title{% endblock %}]]'
'{% for item in [1, 2, 3] %}({{ item }}){% endfor %}')
assert t.render(expr=False) == '[[title]](1)(2)(3)'
assert t.render(expr=True) == '((title))'
def test_urlize_filter_escaping(self):
tmpl = env.from_string('{{ "http://www.example.org/<foo"|urlize }}')
assert tmpl.render() == '<a href="http://www.example.org/<foo">http://www.example.org/<foo</a>'
def test_loop_call_loop(self):
tmpl = env.from_string('''
{% macro test() %}
{{ caller() }}
{% endmacro %}
{% for num1 in range(5) %}
{% call test() %}
{% for num2 in range(10) %}
{{ loop.index }}
{% endfor %}
{% endcall %}
{% endfor %}
''')
assert tmpl.render().split() == map(unicode, range(1, 11)) * 5
def test_weird_inline_comment(self):
env = Environment(line_statement_prefix='%')
self.assert_raises(TemplateSyntaxError, env.from_string,
'% for item in seq {# missing #}\n...% endfor')
def test_old_macro_loop_scoping_bug(self):
tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}'
'{% macro i() %}3{% endmacro %}{{ i() }}')
assert tmpl.render() == '123'
def test_partial_conditional_assignments(self):
tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}')
assert tmpl.render(a=23) == '23'
assert tmpl.render(b=True) == '42'
def test_stacked_locals_scoping_bug(self):
env = Environment(line_statement_prefix='#')
t = env.from_string('''\
# for j in [1, 2]:
# set x = 1
# for i in [1, 2]:
# print x
# if i % 2 == 0:
# set x = x + 1
# endif
# endfor
# endfor
# if a
# print 'A'
# elif b
# print 'B'
# elif c == d
# print 'C'
# else
# print 'D'
# endif
''')
assert t.render(a=0, b=False, c=42, d=42.0) == '1111C'
def test_stacked_locals_scoping_bug_twoframe(self):
t = Template('''
{% set x = 1 %}
{% for item in foo %}
{% if item == 1 %}
{% set x = 2 %}
{% endif %}
{% endfor %}
{{ x }}
''')
rv = t.render(foo=[1]).strip()
assert rv == u'1'
def test_call_with_args(self):
t = Template("""{% macro dump_users(users) -%}
<ul>
{%- for user in users -%}
<li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
{%- endfor -%}
</ul>
{%- endmacro -%}
{% call(user) dump_users(list_of_user) -%}
<dl>
<dl>Realname</dl>
<dd>{{ user.realname|e }}</dd>
<dl>Description</dl>
<dd>{{ user.description }}</dd>
</dl>
{% endcall %}""")
assert [x.strip() for x in t.render(list_of_user=[{
'username':'apo',
'realname':'something else',
'description':'test'
}]).splitlines()] == [
u'<ul><li><p>apo</p><dl>',
u'<dl>Realname</dl>',
u'<dd>something else</dd>',
u'<dl>Description</dl>',
u'<dd>test</dd>',
u'</dl>',
u'</li></ul>'
]
def test_empty_if_condition_fails(self):
self.assert_raises(TemplateSyntaxError, Template, '{% if %}....{% endif %}')
self.assert_raises(TemplateSyntaxError, Template, '{% if foo %}...{% elif %}...{% endif %}')
self.assert_raises(TemplateSyntaxError, Template, '{% for x in %}..{% endfor %}')
def test_recursive_loop_bug(self):
tpl1 = Template("""
{% for p in foo recursive%}
{{p.bar}}
{% for f in p.fields recursive%}
{{f.baz}}
{{p.bar}}
{% if f.rec %}
{{ loop(f.sub) }}
{% endif %}
{% endfor %}
{% endfor %}
""")
tpl2 = Template("""
{% for p in foo%}
{{p.bar}}
{% for f in p.fields recursive%}
{{f.baz}}
{{p.bar}}
{% if f.rec %}
{{ loop(f.sub) }}
{% endif %}
{% endfor %}
{% endfor %}
""")
def test_correct_prefix_loader_name(self):
env = Environment(loader=PrefixLoader({
'foo': DictLoader({})
}))
try:
env.get_template('foo/bar.html')
except TemplateNotFound, e:
assert e.name == 'foo/bar.html'
else:
assert False, 'expected error here'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(CornerTestCase))
suite.addTest(unittest.makeSuite(BugTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.loader
~~~~~~~~~~~~~~~~~~~~~~~
Test the loaders.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import tempfile
import shutil
import unittest
from jinja2.testsuite import JinjaTestCase, dict_loader, \
package_loader, filesystem_loader, function_loader, \
choice_loader, prefix_loader
from jinja2 import Environment, loaders
from jinja2.loaders import split_template_path
from jinja2.exceptions import TemplateNotFound
class LoaderTestCase(JinjaTestCase):
def test_dict_loader(self):
env = Environment(loader=dict_loader)
tmpl = env.get_template('justdict.html')
assert tmpl.render().strip() == 'FOO'
self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
def test_package_loader(self):
env = Environment(loader=package_loader)
tmpl = env.get_template('test.html')
assert tmpl.render().strip() == 'BAR'
self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
def test_filesystem_loader(self):
env = Environment(loader=filesystem_loader)
tmpl = env.get_template('test.html')
assert tmpl.render().strip() == 'BAR'
tmpl = env.get_template('foo/test.html')
assert tmpl.render().strip() == 'FOO'
self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
def test_choice_loader(self):
env = Environment(loader=choice_loader)
tmpl = env.get_template('justdict.html')
assert tmpl.render().strip() == 'FOO'
tmpl = env.get_template('test.html')
assert tmpl.render().strip() == 'BAR'
self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
def test_function_loader(self):
env = Environment(loader=function_loader)
tmpl = env.get_template('justfunction.html')
assert tmpl.render().strip() == 'FOO'
self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
def test_prefix_loader(self):
env = Environment(loader=prefix_loader)
tmpl = env.get_template('a/test.html')
assert tmpl.render().strip() == 'BAR'
tmpl = env.get_template('b/justdict.html')
assert tmpl.render().strip() == 'FOO'
self.assert_raises(TemplateNotFound, env.get_template, 'missing')
def test_caching(self):
changed = False
class TestLoader(loaders.BaseLoader):
def get_source(self, environment, template):
return u'foo', None, lambda: not changed
env = Environment(loader=TestLoader(), cache_size=-1)
tmpl = env.get_template('template')
assert tmpl is env.get_template('template')
changed = True
assert tmpl is not env.get_template('template')
changed = False
env = Environment(loader=TestLoader(), cache_size=0)
assert env.get_template('template') \
is not env.get_template('template')
env = Environment(loader=TestLoader(), cache_size=2)
t1 = env.get_template('one')
t2 = env.get_template('two')
assert t2 is env.get_template('two')
assert t1 is env.get_template('one')
t3 = env.get_template('three')
assert 'one' in env.cache
assert 'two' not in env.cache
assert 'three' in env.cache
def test_split_template_path(self):
assert split_template_path('foo/bar') == ['foo', 'bar']
assert split_template_path('./foo/bar') == ['foo', 'bar']
self.assert_raises(TemplateNotFound, split_template_path, '../foo')
class ModuleLoaderTestCase(JinjaTestCase):
archive = None
def compile_down(self, zip='deflated', py_compile=False):
super(ModuleLoaderTestCase, self).setup()
log = []
self.reg_env = Environment(loader=prefix_loader)
if zip is not None:
self.archive = tempfile.mkstemp(suffix='.zip')[1]
else:
self.archive = tempfile.mkdtemp()
self.reg_env.compile_templates(self.archive, zip=zip,
log_function=log.append,
py_compile=py_compile)
self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))
return ''.join(log)
def teardown(self):
super(ModuleLoaderTestCase, self).teardown()
if hasattr(self, 'mod_env'):
if os.path.isfile(self.archive):
os.remove(self.archive)
else:
shutil.rmtree(self.archive)
self.archive = None
def test_log(self):
log = self.compile_down()
assert 'Compiled "a/foo/test.html" as ' \
'tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a' in log
assert 'Finished compiling templates' in log
assert 'Could not compile "a/syntaxerror.html": ' \
'Encountered unknown tag \'endif\'' in log
def _test_common(self):
tmpl1 = self.reg_env.get_template('a/test.html')
tmpl2 = self.mod_env.get_template('a/test.html')
assert tmpl1.render() == tmpl2.render()
tmpl1 = self.reg_env.get_template('b/justdict.html')
tmpl2 = self.mod_env.get_template('b/justdict.html')
assert tmpl1.render() == tmpl2.render()
def test_deflated_zip_compile(self):
self.compile_down(zip='deflated')
self._test_common()
def test_stored_zip_compile(self):
self.compile_down(zip='stored')
self._test_common()
def test_filesystem_compile(self):
self.compile_down(zip=None)
self._test_common()
def test_weak_references(self):
self.compile_down()
tmpl = self.mod_env.get_template('a/test.html')
key = loaders.ModuleLoader.get_template_key('a/test.html')
name = self.mod_env.loader.module.__name__
assert hasattr(self.mod_env.loader.module, key)
assert name in sys.modules
# unset all, ensure the module is gone from sys.modules
self.mod_env = tmpl = None
try:
import gc
gc.collect()
except:
pass
assert name not in sys.modules
def test_byte_compilation(self):
log = self.compile_down(py_compile=True)
assert 'Byte-compiled "a/test.html"' in log
tmpl1 = self.mod_env.get_template('a/test.html')
mod = self.mod_env.loader.module. \
tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490
assert mod.__file__.endswith('.pyc')
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(LoaderTestCase))
suite.addTest(unittest.makeSuite(ModuleLoaderTestCase))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.doctests
~~~~~~~~~~~~~~~~~~~~~~~~~
The doctests. Collects all tests we want to test from
the Jinja modules.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
import doctest
def suite():
from jinja2 import utils, sandbox, runtime, meta, loaders, \
ext, environment, bccache, nodes
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(utils))
suite.addTest(doctest.DocTestSuite(sandbox))
suite.addTest(doctest.DocTestSuite(runtime))
suite.addTest(doctest.DocTestSuite(meta))
suite.addTest(doctest.DocTestSuite(loaders))
suite.addTest(doctest.DocTestSuite(ext))
suite.addTest(doctest.DocTestSuite(environment))
suite.addTest(doctest.DocTestSuite(bccache))
suite.addTest(doctest.DocTestSuite(nodes))
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite
~~~~~~~~~~~~~~~~
All the unittests of Jinja2. These tests can be executed by
either running run-tests.py using multiple Python versions at
the same time.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import re
import sys
import unittest
from traceback import format_exception
from jinja2 import loaders
here = os.path.dirname(os.path.abspath(__file__))
dict_loader = loaders.DictLoader({
'justdict.html': 'FOO'
})
package_loader = loaders.PackageLoader('jinja2.testsuite.res', 'templates')
filesystem_loader = loaders.FileSystemLoader(here + '/res/templates')
function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)
choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])
prefix_loader = loaders.PrefixLoader({
'a': filesystem_loader,
'b': dict_loader
})
class JinjaTestCase(unittest.TestCase):
### use only these methods for testing. If you need standard
### unittest method, wrap them!
def setup(self):
pass
def teardown(self):
pass
def setUp(self):
self.setup()
def tearDown(self):
self.teardown()
def assert_equal(self, a, b):
return self.assertEqual(a, b)
def assert_raises(self, *args, **kwargs):
return self.assertRaises(*args, **kwargs)
def assert_traceback_matches(self, callback, expected_tb):
try:
callback()
except Exception, e:
tb = format_exception(*sys.exc_info())
if re.search(expected_tb.strip(), ''.join(tb)) is None:
raise self.fail('Traceback did not match:\n\n%s\nexpected:\n%s'
% (''.join(tb), expected_tb))
else:
self.fail('Expected exception')
def suite():
from jinja2.testsuite import ext, filters, tests, core_tags, \
loader, inheritance, imports, lexnparse, security, api, \
regression, debug, utils, doctests
suite = unittest.TestSuite()
suite.addTest(ext.suite())
suite.addTest(filters.suite())
suite.addTest(tests.suite())
suite.addTest(core_tags.suite())
suite.addTest(loader.suite())
suite.addTest(inheritance.suite())
suite.addTest(imports.suite())
suite.addTest(lexnparse.suite())
suite.addTest(security.suite())
suite.addTest(api.suite())
suite.addTest(regression.suite())
suite.addTest(debug.suite())
suite.addTest(utils.suite())
# doctests will not run on python 3 currently. Too many issues
# with that, do not test that on that platform.
if sys.version_info < (3, 0):
suite.addTest(doctests.suite())
return suite
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.api
~~~~~~~~~~~~~~~~~~~~
Tests the public API and related stuff.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Environment, Undefined, DebugUndefined, \
StrictUndefined, UndefinedError, meta, \
is_undefined, Template, DictLoader
from jinja2.utils import Cycler
env = Environment()
class ExtendedAPITestCase(JinjaTestCase):
def test_item_and_attribute(self):
from jinja2.sandbox import SandboxedEnvironment
for env in Environment(), SandboxedEnvironment():
# the |list is necessary for python3
tmpl = env.from_string('{{ foo.items()|list }}')
assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
tmpl = env.from_string('{{ foo|attr("items")()|list }}')
assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
tmpl = env.from_string('{{ foo["items"] }}')
assert tmpl.render(foo={'items': 42}) == '42'
def test_finalizer(self):
def finalize_none_empty(value):
if value is None:
value = u''
return value
env = Environment(finalize=finalize_none_empty)
tmpl = env.from_string('{% for item in seq %}|{{ item }}{% endfor %}')
assert tmpl.render(seq=(None, 1, "foo")) == '||1|foo'
tmpl = env.from_string('<{{ none }}>')
assert tmpl.render() == '<>'
def test_cycler(self):
items = 1, 2, 3
c = Cycler(*items)
for item in items + items:
assert c.current == item
assert c.next() == item
c.next()
assert c.current == 2
c.reset()
assert c.current == 1
def test_expressions(self):
expr = env.compile_expression("foo")
assert expr() is None
assert expr(foo=42) == 42
expr2 = env.compile_expression("foo", undefined_to_none=False)
assert is_undefined(expr2())
expr = env.compile_expression("42 + foo")
assert expr(foo=42) == 84
def test_template_passthrough(self):
t = Template('Content')
assert env.get_template(t) is t
assert env.select_template([t]) is t
assert env.get_or_select_template([t]) is t
assert env.get_or_select_template(t) is t
def test_autoescape_autoselect(self):
def select_autoescape(name):
if name is None or '.' not in name:
return False
return name.endswith('.html')
env = Environment(autoescape=select_autoescape,
loader=DictLoader({
'test.txt': '{{ foo }}',
'test.html': '{{ foo }}'
}))
t = env.get_template('test.txt')
assert t.render(foo='<foo>') == '<foo>'
t = env.get_template('test.html')
assert t.render(foo='<foo>') == '<foo>'
t = env.from_string('{{ foo }}')
assert t.render(foo='<foo>') == '<foo>'
class MetaTestCase(JinjaTestCase):
def test_find_undeclared_variables(self):
ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
x = meta.find_undeclared_variables(ast)
assert x == set(['bar'])
ast = env.parse('{% set foo = 42 %}{{ bar + foo }}'
'{% macro meh(x) %}{{ x }}{% endmacro %}'
'{% for item in seq %}{{ muh(item) + meh(seq) }}{% endfor %}')
x = meta.find_undeclared_variables(ast)
assert x == set(['bar', 'seq', 'muh'])
def test_find_refererenced_templates(self):
ast = env.parse('{% extends "layout.html" %}{% include helper %}')
i = meta.find_referenced_templates(ast)
assert i.next() == 'layout.html'
assert i.next() is None
assert list(i) == []
ast = env.parse('{% extends "layout.html" %}'
'{% from "test.html" import a, b as c %}'
'{% import "meh.html" as meh %}'
'{% include "muh.html" %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html']
def test_find_included_templates(self):
ast = env.parse('{% include ["foo.html", "bar.html"] %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html']
ast = env.parse('{% include ("foo.html", "bar.html") %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html']
ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html', None]
ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')
i = meta.find_referenced_templates(ast)
assert list(i) == ['foo.html', 'bar.html', None]
class StreamingTestCase(JinjaTestCase):
def test_basic_streaming(self):
tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "
"}} - {{ item }}</li>{%- endfor %}</ul>")
stream = tmpl.stream(seq=range(4))
self.assert_equal(stream.next(), '<ul>')
self.assert_equal(stream.next(), '<li>1 - 0</li>')
self.assert_equal(stream.next(), '<li>2 - 1</li>')
self.assert_equal(stream.next(), '<li>3 - 2</li>')
self.assert_equal(stream.next(), '<li>4 - 3</li>')
self.assert_equal(stream.next(), '</ul>')
def test_buffered_streaming(self):
tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "
"}} - {{ item }}</li>{%- endfor %}</ul>")
stream = tmpl.stream(seq=range(4))
stream.enable_buffering(size=3)
self.assert_equal(stream.next(), u'<ul><li>1 - 0</li><li>2 - 1</li>')
self.assert_equal(stream.next(), u'<li>3 - 2</li><li>4 - 3</li></ul>')
def test_streaming_behavior(self):
tmpl = env.from_string("")
stream = tmpl.stream()
assert not stream.buffered
stream.enable_buffering(20)
assert stream.buffered
stream.disable_buffering()
assert not stream.buffered
class UndefinedTestCase(JinjaTestCase):
def test_stopiteration_is_undefined(self):
def test():
raise StopIteration()
t = Template('A{{ test() }}B')
assert t.render(test=test) == 'AB'
t = Template('A{{ test().missingattribute }}B')
self.assert_raises(UndefinedError, t.render, test=test)
def test_undefined_and_special_attributes(self):
try:
Undefined('Foo').__dict__
except AttributeError:
pass
else:
assert False, "Expected actual attribute error"
def test_default_undefined(self):
env = Environment(undefined=Undefined)
self.assert_equal(env.from_string('{{ missing }}').render(), u'')
self.assert_raises(UndefinedError,
env.from_string('{{ missing.attribute }}').render)
self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')
self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42), '')
self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')
def test_debug_undefined(self):
env = Environment(undefined=DebugUndefined)
self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}')
self.assert_raises(UndefinedError,
env.from_string('{{ missing.attribute }}').render)
self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')
self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42),
u"{{ no such element: int object['missing'] }}")
self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')
def test_strict_undefined(self):
env = Environment(undefined=StrictUndefined)
self.assert_raises(UndefinedError, env.from_string('{{ missing }}').render)
self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render)
self.assert_raises(UndefinedError, env.from_string('{{ missing|list }}').render)
self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
self.assert_raises(UndefinedError, env.from_string('{{ foo.missing }}').render, foo=42)
self.assert_raises(UndefinedError, env.from_string('{{ not missing }}').render)
def test_indexing_gives_undefined(self):
t = Template("{{ var[42].foo }}")
self.assert_raises(UndefinedError, t.render, var=0)
def test_none_gives_proper_error(self):
try:
Environment().getattr(None, 'split')()
except UndefinedError, e:
assert e.message == "'None' has no attribute 'split'"
else:
assert False, 'expected exception'
def test_object_repr(self):
try:
Undefined(obj=42, name='upper')()
except UndefinedError, e:
assert e.message == "'int object' has no attribute 'upper'"
else:
assert False, 'expected exception'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ExtendedAPITestCase))
suite.addTest(unittest.makeSuite(MetaTestCase))
suite.addTest(unittest.makeSuite(StreamingTestCase))
suite.addTest(unittest.makeSuite(UndefinedTestCase))
return suite
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.