Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
QMTechDaughterboard.__init__
(self, io_standard)
because the board can be used with FPGAs core boards from different vendors, the constructor needs the vendor specific IOStandard
because the board can be used with FPGAs core boards from different vendors, the constructor needs the vendor specific IOStandard
def __init__(self, io_standard) -> None: """ because the board can be used with FPGAs core boards from different vendors, the constructor needs the vendor specific IOStandard """ self.io = [ ("serial", 0, Subsignal("rx", Pins("J2:15")), Subsignal("tx", Pins("J2:16")), io_standard ), ("user_led", 0, Pins("J2:40"), io_standard), ("user_led", 1, Pins("J2:39"), io_standard), ("user_led", 2, Pins("J2:38"), io_standard), ("user_led", 3, Pins("J2:37"), io_standard), ("user_led", 4, Pins("J2:36"), io_standard), ("user_btn", 0, Pins("J3:7"), io_standard), ("user_btn", 1, Pins("J2:44"), io_standard), ("user_btn", 2, Pins("J2:43"), io_standard), ("user_btn", 3, Pins("J2:42"), io_standard), ("user_btn", 4, Pins("J2:41"), io_standard), # GMII Ethernet ("eth_clocks", 0, Subsignal("tx", Pins("J3:22")), Subsignal("gtx", Pins("J3:29")), Subsignal("rx", Pins("J3:37")), io_standard ), ("eth", 0, # rst is hardwired on the board #Subsignal("rst_n", Pins("-")), Subsignal("int_n", Pins("J3:26")), Subsignal("mdio", Pins("J3:15")), Subsignal("mdc", Pins("J3:16")), Subsignal("rx_dv", Pins("J3:42")), Subsignal("rx_er", Pins("J3:32")), Subsignal("rx_data", Pins("J3:41 J3:40 J3:39 J3:38 J3:36 J3:35 J3:34 J3:33")), Subsignal("tx_en", Pins("J3:28")), Subsignal("tx_er", Pins("J3:17")), Subsignal("tx_data", Pins("J3:27 J3:25 J3:24 J3:23 J3:21 J3:20 J3:19 J3:18")), Subsignal("col", Pins("J3:31")), Subsignal("crs", Pins("J3:30")), io_standard ), # Seven Segment ("seven_seg_ctl", 0, Pins("J2:33"), io_standard), ("seven_seg_ctl", 1, Pins("J2:27"), io_standard), ("seven_seg_ctl", 2, Pins("J2:35"), io_standard), ("seven_seg", 0, Pins("J2:31 J2:26 J2:28 J2:32 J2:34 J2:29 J2:25 J2:30"), io_standard), # VGA ("vga", 0, Subsignal("hsync_n", Pins("J3:44")), Subsignal("vsync_n", Pins("J3:43")), Subsignal("r", Pins("J3:57 J3:56 J3:59 J3:58 J3:60")), Subsignal("g", Pins("J3:51 J3:50 J3:53 J3:52 J3:54 J3:55")), Subsignal("b", Pins("J3:46 J3:45 J3:48 J3:47 J3:49")), io_standard ), # PullUp resistors are on the board, so we don't need them in the FPGA ("sdcard", 0, Subsignal("data", Pins("J3:10 J3:9 J3:14 J3:13")), Subsignal("cmd", Pins("J3:12")), Subsignal("clk", Pins("J3:11")), Subsignal("cd", Pins("J3:8")), Misc("SLEW=FAST"), io_standard, ), ]
[ "def", "__init__", "(", "self", ",", "io_standard", ")", "->", "None", ":", "self", ".", "io", "=", "[", "(", "\"serial\"", ",", "0", ",", "Subsignal", "(", "\"rx\"", ",", "Pins", "(", "\"J2:15\"", ")", ")", ",", "Subsignal", "(", "\"tx\"", ",", "Pins", "(", "\"J2:16\"", ")", ")", ",", "io_standard", ")", ",", "(", "\"user_led\"", ",", "0", ",", "Pins", "(", "\"J2:40\"", ")", ",", "io_standard", ")", ",", "(", "\"user_led\"", ",", "1", ",", "Pins", "(", "\"J2:39\"", ")", ",", "io_standard", ")", ",", "(", "\"user_led\"", ",", "2", ",", "Pins", "(", "\"J2:38\"", ")", ",", "io_standard", ")", ",", "(", "\"user_led\"", ",", "3", ",", "Pins", "(", "\"J2:37\"", ")", ",", "io_standard", ")", ",", "(", "\"user_led\"", ",", "4", ",", "Pins", "(", "\"J2:36\"", ")", ",", "io_standard", ")", ",", "(", "\"user_btn\"", ",", "0", ",", "Pins", "(", "\"J3:7\"", ")", ",", "io_standard", ")", ",", "(", "\"user_btn\"", ",", "1", ",", "Pins", "(", "\"J2:44\"", ")", ",", "io_standard", ")", ",", "(", "\"user_btn\"", ",", "2", ",", "Pins", "(", "\"J2:43\"", ")", ",", "io_standard", ")", ",", "(", "\"user_btn\"", ",", "3", ",", "Pins", "(", "\"J2:42\"", ")", ",", "io_standard", ")", ",", "(", "\"user_btn\"", ",", "4", ",", "Pins", "(", "\"J2:41\"", ")", ",", "io_standard", ")", ",", "# GMII Ethernet", "(", "\"eth_clocks\"", ",", "0", ",", "Subsignal", "(", "\"tx\"", ",", "Pins", "(", "\"J3:22\"", ")", ")", ",", "Subsignal", "(", "\"gtx\"", ",", "Pins", "(", "\"J3:29\"", ")", ")", ",", "Subsignal", "(", "\"rx\"", ",", "Pins", "(", "\"J3:37\"", ")", ")", ",", "io_standard", ")", ",", "(", "\"eth\"", ",", "0", ",", "# rst is hardwired on the board", "#Subsignal(\"rst_n\", Pins(\"-\")),", "Subsignal", "(", "\"int_n\"", ",", "Pins", "(", "\"J3:26\"", ")", ")", ",", "Subsignal", "(", "\"mdio\"", ",", "Pins", "(", "\"J3:15\"", ")", ")", ",", "Subsignal", "(", "\"mdc\"", ",", "Pins", "(", "\"J3:16\"", ")", ")", ",", "Subsignal", "(", "\"rx_dv\"", ",", "Pins", "(", "\"J3:42\"", ")", ")", ",", "Subsignal", "(", "\"rx_er\"", ",", "Pins", "(", "\"J3:32\"", ")", ")", ",", "Subsignal", "(", "\"rx_data\"", ",", "Pins", "(", "\"J3:41 J3:40 J3:39 J3:38 J3:36 J3:35 J3:34 J3:33\"", ")", ")", ",", "Subsignal", "(", "\"tx_en\"", ",", "Pins", "(", "\"J3:28\"", ")", ")", ",", "Subsignal", "(", "\"tx_er\"", ",", "Pins", "(", "\"J3:17\"", ")", ")", ",", "Subsignal", "(", "\"tx_data\"", ",", "Pins", "(", "\"J3:27 J3:25 J3:24 J3:23 J3:21 J3:20 J3:19 J3:18\"", ")", ")", ",", "Subsignal", "(", "\"col\"", ",", "Pins", "(", "\"J3:31\"", ")", ")", ",", "Subsignal", "(", "\"crs\"", ",", "Pins", "(", "\"J3:30\"", ")", ")", ",", "io_standard", ")", ",", "# Seven Segment", "(", "\"seven_seg_ctl\"", ",", "0", ",", "Pins", "(", "\"J2:33\"", ")", ",", "io_standard", ")", ",", "(", "\"seven_seg_ctl\"", ",", "1", ",", "Pins", "(", "\"J2:27\"", ")", ",", "io_standard", ")", ",", "(", "\"seven_seg_ctl\"", ",", "2", ",", "Pins", "(", "\"J2:35\"", ")", ",", "io_standard", ")", ",", "(", "\"seven_seg\"", ",", "0", ",", "Pins", "(", "\"J2:31 J2:26 J2:28 J2:32 J2:34 J2:29 J2:25 J2:30\"", ")", ",", "io_standard", ")", ",", "# VGA", "(", "\"vga\"", ",", "0", ",", "Subsignal", "(", "\"hsync_n\"", ",", "Pins", "(", "\"J3:44\"", ")", ")", ",", "Subsignal", "(", "\"vsync_n\"", ",", "Pins", "(", "\"J3:43\"", ")", ")", ",", "Subsignal", "(", "\"r\"", ",", "Pins", "(", "\"J3:57 J3:56 J3:59 J3:58 J3:60\"", ")", ")", ",", "Subsignal", "(", "\"g\"", ",", "Pins", "(", "\"J3:51 J3:50 J3:53 J3:52 J3:54 J3:55\"", ")", ")", ",", "Subsignal", "(", "\"b\"", ",", "Pins", "(", "\"J3:46 J3:45 J3:48 J3:47 J3:49\"", ")", ")", ",", "io_standard", ")", ",", "# PullUp resistors are on the board, so we don't need them in the FPGA", "(", "\"sdcard\"", ",", "0", ",", "Subsignal", "(", "\"data\"", ",", "Pins", "(", "\"J3:10 J3:9 J3:14 J3:13\"", ")", ")", ",", "Subsignal", "(", "\"cmd\"", ",", "Pins", "(", "\"J3:12\"", ")", ")", ",", "Subsignal", "(", "\"clk\"", ",", "Pins", "(", "\"J3:11\"", ")", ")", ",", "Subsignal", "(", "\"cd\"", ",", "Pins", "(", "\"J3:8\"", ")", ")", ",", "Misc", "(", "\"SLEW=FAST\"", ")", ",", "io_standard", ",", ")", ",", "]" ]
[ 9, 4 ]
[ 82, 9 ]
python
en
['en', 'error', 'th']
False
create_model
(architecture, classes_num)
Create a model Args: architecture(dict): architecture information, name(such as ResNet50) is needed image(variable): model input variable classes_num(int): num of classes Returns: out(variable): model output variable
Create a model
def create_model(architecture, classes_num): """ Create a model Args: architecture(dict): architecture information, name(such as ResNet50) is needed image(variable): model input variable classes_num(int): num of classes Returns: out(variable): model output variable """ name = architecture["name"] params = architecture.get("params", {}) return architectures.__dict__[name](class_dim=classes_num, **params)
[ "def", "create_model", "(", "architecture", ",", "classes_num", ")", ":", "name", "=", "architecture", "[", "\"name\"", "]", "params", "=", "architecture", ".", "get", "(", "\"params\"", ",", "{", "}", ")", "return", "architectures", ".", "__dict__", "[", "name", "]", "(", "class_dim", "=", "classes_num", ",", "*", "*", "params", ")" ]
[ 38, 0 ]
[ 53, 72 ]
python
en
['en', 'error', 'th']
False
create_loss
(feeds, out, architecture, classes_num=1000, epsilon=None, use_mix=False, use_distillation=False)
Create a loss for optimization, such as: 1. CrossEnotry loss 2. CrossEnotry loss with label smoothing 3. CrossEnotry loss with mix(mixup, cutmix, fmix) 4. CrossEnotry loss with label smoothing and (mixup, cutmix, fmix) 5. GoogLeNet loss Args: out(variable): model output variable feeds(dict): dict of model input variables architecture(dict): architecture information, name(such as ResNet50) is needed classes_num(int): num of classes epsilon(float): parameter for label smoothing, 0.0 <= epsilon <= 1.0 use_mix(bool): whether to use mix(include mixup, cutmix, fmix) Returns: loss(variable): loss variable
Create a loss for optimization, such as: 1. CrossEnotry loss 2. CrossEnotry loss with label smoothing 3. CrossEnotry loss with mix(mixup, cutmix, fmix) 4. CrossEnotry loss with label smoothing and (mixup, cutmix, fmix) 5. GoogLeNet loss
def create_loss(feeds, out, architecture, classes_num=1000, epsilon=None, use_mix=False, use_distillation=False): """ Create a loss for optimization, such as: 1. CrossEnotry loss 2. CrossEnotry loss with label smoothing 3. CrossEnotry loss with mix(mixup, cutmix, fmix) 4. CrossEnotry loss with label smoothing and (mixup, cutmix, fmix) 5. GoogLeNet loss Args: out(variable): model output variable feeds(dict): dict of model input variables architecture(dict): architecture information, name(such as ResNet50) is needed classes_num(int): num of classes epsilon(float): parameter for label smoothing, 0.0 <= epsilon <= 1.0 use_mix(bool): whether to use mix(include mixup, cutmix, fmix) Returns: loss(variable): loss variable """ if architecture["name"] == "GoogLeNet": assert len(out) == 3, "GoogLeNet should have 3 outputs" loss = GoogLeNetLoss(class_dim=classes_num, epsilon=epsilon) return loss(out[0], out[1], out[2], feeds["label"]) if use_distillation: assert len(out) == 2, ("distillation output length must be 2, " "but got {}".format(len(out))) loss = JSDivLoss(class_dim=classes_num, epsilon=epsilon) return loss(out[1], out[0]) if use_mix: loss = MixCELoss(class_dim=classes_num, epsilon=epsilon) feed_y_a = feeds['y_a'] feed_y_b = feeds['y_b'] feed_lam = feeds['lam'] return loss(out, feed_y_a, feed_y_b, feed_lam) else: loss = CELoss(class_dim=classes_num, epsilon=epsilon) return loss(out, feeds["label"])
[ "def", "create_loss", "(", "feeds", ",", "out", ",", "architecture", ",", "classes_num", "=", "1000", ",", "epsilon", "=", "None", ",", "use_mix", "=", "False", ",", "use_distillation", "=", "False", ")", ":", "if", "architecture", "[", "\"name\"", "]", "==", "\"GoogLeNet\"", ":", "assert", "len", "(", "out", ")", "==", "3", ",", "\"GoogLeNet should have 3 outputs\"", "loss", "=", "GoogLeNetLoss", "(", "class_dim", "=", "classes_num", ",", "epsilon", "=", "epsilon", ")", "return", "loss", "(", "out", "[", "0", "]", ",", "out", "[", "1", "]", ",", "out", "[", "2", "]", ",", "feeds", "[", "\"label\"", "]", ")", "if", "use_distillation", ":", "assert", "len", "(", "out", ")", "==", "2", ",", "(", "\"distillation output length must be 2, \"", "\"but got {}\"", ".", "format", "(", "len", "(", "out", ")", ")", ")", "loss", "=", "JSDivLoss", "(", "class_dim", "=", "classes_num", ",", "epsilon", "=", "epsilon", ")", "return", "loss", "(", "out", "[", "1", "]", ",", "out", "[", "0", "]", ")", "if", "use_mix", ":", "loss", "=", "MixCELoss", "(", "class_dim", "=", "classes_num", ",", "epsilon", "=", "epsilon", ")", "feed_y_a", "=", "feeds", "[", "'y_a'", "]", "feed_y_b", "=", "feeds", "[", "'y_b'", "]", "feed_lam", "=", "feeds", "[", "'lam'", "]", "return", "loss", "(", "out", ",", "feed_y_a", ",", "feed_y_b", ",", "feed_lam", ")", "else", ":", "loss", "=", "CELoss", "(", "class_dim", "=", "classes_num", ",", "epsilon", "=", "epsilon", ")", "return", "loss", "(", "out", ",", "feeds", "[", "\"label\"", "]", ")" ]
[ 56, 0 ]
[ 102, 40 ]
python
en
['en', 'error', 'th']
False
create_metric
(out, label, architecture, topk=5, classes_num=1000, use_distillation=False, mode="train")
Create measures of model accuracy, such as top1 and top5 Args: out(variable): model output variable feeds(dict): dict of model input variables(included label) topk(int): usually top5 classes_num(int): num of classes use_distillation(bool): whether to use distillation training mode(str): mode, train/valid Returns: fetchs(dict): dict of measures
Create measures of model accuracy, such as top1 and top5
def create_metric(out, label, architecture, topk=5, classes_num=1000, use_distillation=False, mode="train"): """ Create measures of model accuracy, such as top1 and top5 Args: out(variable): model output variable feeds(dict): dict of model input variables(included label) topk(int): usually top5 classes_num(int): num of classes use_distillation(bool): whether to use distillation training mode(str): mode, train/valid Returns: fetchs(dict): dict of measures """ if architecture["name"] == "GoogLeNet": assert len(out) == 3, "GoogLeNet should have 3 outputs" out = out[0] else: # just need student label to get metrics if use_distillation: out = out[1] softmax_out = F.softmax(out) fetchs = OrderedDict() # set top1 to fetchs top1 = paddle.metric.accuracy(softmax_out, label=label, k=1) # set topk to fetchs k = min(topk, classes_num) topk = paddle.metric.accuracy(softmax_out, label=label, k=k) # multi cards' eval if mode != "train" and paddle.distributed.get_world_size() > 1: top1 = paddle.distributed.all_reduce( top1, op=paddle.distributed.ReduceOp. SUM) / paddle.distributed.get_world_size() topk = paddle.distributed.all_reduce( topk, op=paddle.distributed.ReduceOp. SUM) / paddle.distributed.get_world_size() fetchs['top1'] = top1 topk_name = 'top{}'.format(k) fetchs[topk_name] = topk return fetchs
[ "def", "create_metric", "(", "out", ",", "label", ",", "architecture", ",", "topk", "=", "5", ",", "classes_num", "=", "1000", ",", "use_distillation", "=", "False", ",", "mode", "=", "\"train\"", ")", ":", "if", "architecture", "[", "\"name\"", "]", "==", "\"GoogLeNet\"", ":", "assert", "len", "(", "out", ")", "==", "3", ",", "\"GoogLeNet should have 3 outputs\"", "out", "=", "out", "[", "0", "]", "else", ":", "# just need student label to get metrics", "if", "use_distillation", ":", "out", "=", "out", "[", "1", "]", "softmax_out", "=", "F", ".", "softmax", "(", "out", ")", "fetchs", "=", "OrderedDict", "(", ")", "# set top1 to fetchs", "top1", "=", "paddle", ".", "metric", ".", "accuracy", "(", "softmax_out", ",", "label", "=", "label", ",", "k", "=", "1", ")", "# set topk to fetchs", "k", "=", "min", "(", "topk", ",", "classes_num", ")", "topk", "=", "paddle", ".", "metric", ".", "accuracy", "(", "softmax_out", ",", "label", "=", "label", ",", "k", "=", "k", ")", "# multi cards' eval", "if", "mode", "!=", "\"train\"", "and", "paddle", ".", "distributed", ".", "get_world_size", "(", ")", ">", "1", ":", "top1", "=", "paddle", ".", "distributed", ".", "all_reduce", "(", "top1", ",", "op", "=", "paddle", ".", "distributed", ".", "ReduceOp", ".", "SUM", ")", "/", "paddle", ".", "distributed", ".", "get_world_size", "(", ")", "topk", "=", "paddle", ".", "distributed", ".", "all_reduce", "(", "topk", ",", "op", "=", "paddle", ".", "distributed", ".", "ReduceOp", ".", "SUM", ")", "/", "paddle", ".", "distributed", ".", "get_world_size", "(", ")", "fetchs", "[", "'top1'", "]", "=", "top1", "topk_name", "=", "'top{}'", ".", "format", "(", "k", ")", "fetchs", "[", "topk_name", "]", "=", "topk", "return", "fetchs" ]
[ 105, 0 ]
[ 155, 17 ]
python
en
['en', 'error', 'th']
False
create_fetchs
(feeds, net, config, mode="train")
Create fetchs as model outputs(included loss and measures), will call create_loss and create_metric(if use_mix). Args: out(variable): model output variable feeds(dict): dict of model input variables. If use mix_up, it will not include label. architecture(dict): architecture information, name(such as ResNet50) is needed topk(int): usually top5 classes_num(int): num of classes epsilon(float): parameter for label smoothing, 0.0 <= epsilon <= 1.0 use_mix(bool): whether to use mix(include mixup, cutmix, fmix) Returns: fetchs(dict): dict of model outputs(included loss and measures)
Create fetchs as model outputs(included loss and measures), will call create_loss and create_metric(if use_mix).
def create_fetchs(feeds, net, config, mode="train"): """ Create fetchs as model outputs(included loss and measures), will call create_loss and create_metric(if use_mix). Args: out(variable): model output variable feeds(dict): dict of model input variables. If use mix_up, it will not include label. architecture(dict): architecture information, name(such as ResNet50) is needed topk(int): usually top5 classes_num(int): num of classes epsilon(float): parameter for label smoothing, 0.0 <= epsilon <= 1.0 use_mix(bool): whether to use mix(include mixup, cutmix, fmix) Returns: fetchs(dict): dict of model outputs(included loss and measures) """ architecture = config.ARCHITECTURE topk = config.topk classes_num = config.classes_num epsilon = config.get('ls_epsilon') use_mix = config.get('use_mix') and mode == 'train' use_distillation = config.get('use_distillation') out = net(feeds["image"]) fetchs = OrderedDict() fetchs['loss'] = create_loss(feeds, out, architecture, classes_num, epsilon, use_mix, use_distillation) if not use_mix: metric = create_metric( out, feeds["label"], architecture, topk, classes_num, use_distillation, mode=mode) fetchs.update(metric) return fetchs
[ "def", "create_fetchs", "(", "feeds", ",", "net", ",", "config", ",", "mode", "=", "\"train\"", ")", ":", "architecture", "=", "config", ".", "ARCHITECTURE", "topk", "=", "config", ".", "topk", "classes_num", "=", "config", ".", "classes_num", "epsilon", "=", "config", ".", "get", "(", "'ls_epsilon'", ")", "use_mix", "=", "config", ".", "get", "(", "'use_mix'", ")", "and", "mode", "==", "'train'", "use_distillation", "=", "config", ".", "get", "(", "'use_distillation'", ")", "out", "=", "net", "(", "feeds", "[", "\"image\"", "]", ")", "fetchs", "=", "OrderedDict", "(", ")", "fetchs", "[", "'loss'", "]", "=", "create_loss", "(", "feeds", ",", "out", ",", "architecture", ",", "classes_num", ",", "epsilon", ",", "use_mix", ",", "use_distillation", ")", "if", "not", "use_mix", ":", "metric", "=", "create_metric", "(", "out", ",", "feeds", "[", "\"label\"", "]", ",", "architecture", ",", "topk", ",", "classes_num", ",", "use_distillation", ",", "mode", "=", "mode", ")", "fetchs", ".", "update", "(", "metric", ")", "return", "fetchs" ]
[ 158, 0 ]
[ 200, 17 ]
python
en
['en', 'error', 'th']
False
create_optimizer
(config, parameter_list=None)
Create an optimizer using config, usually including learning rate and regularization. Args: config(dict): such as { 'LEARNING_RATE': {'function': 'Cosine', 'params': {'lr': 0.1} }, 'OPTIMIZER': {'function': 'Momentum', 'params':{'momentum': 0.9}, 'regularizer': {'function': 'L2', 'factor': 0.0001} } } Returns: an optimizer instance
Create an optimizer using config, usually including learning rate and regularization.
def create_optimizer(config, parameter_list=None): """ Create an optimizer using config, usually including learning rate and regularization. Args: config(dict): such as { 'LEARNING_RATE': {'function': 'Cosine', 'params': {'lr': 0.1} }, 'OPTIMIZER': {'function': 'Momentum', 'params':{'momentum': 0.9}, 'regularizer': {'function': 'L2', 'factor': 0.0001} } } Returns: an optimizer instance """ # create learning_rate instance lr_config = config['LEARNING_RATE'] lr_config['params'].update({ 'epochs': config['epochs'], 'step_each_epoch': config['total_images'] // config['TRAIN']['batch_size'], }) lr = LearningRateBuilder(**lr_config)() # create optimizer instance opt_config = config['OPTIMIZER'] opt = OptimizerBuilder(**opt_config) return opt(lr, parameter_list), lr
[ "def", "create_optimizer", "(", "config", ",", "parameter_list", "=", "None", ")", ":", "# create learning_rate instance", "lr_config", "=", "config", "[", "'LEARNING_RATE'", "]", "lr_config", "[", "'params'", "]", ".", "update", "(", "{", "'epochs'", ":", "config", "[", "'epochs'", "]", ",", "'step_each_epoch'", ":", "config", "[", "'total_images'", "]", "//", "config", "[", "'TRAIN'", "]", "[", "'batch_size'", "]", ",", "}", ")", "lr", "=", "LearningRateBuilder", "(", "*", "*", "lr_config", ")", "(", ")", "# create optimizer instance", "opt_config", "=", "config", "[", "'OPTIMIZER'", "]", "opt", "=", "OptimizerBuilder", "(", "*", "*", "opt_config", ")", "return", "opt", "(", "lr", ",", "parameter_list", ")", ",", "lr" ]
[ 203, 0 ]
[ 238, 38 ]
python
en
['en', 'error', 'th']
False
run
(dataloader, config, net, optimizer=None, lr_scheduler=None, epoch=0, mode='train')
Feed data to the model and fetch the measures and loss Args: dataloader(paddle dataloader): exe(): program(): fetchs(dict): dict of measures and the loss epoch(int): epoch of training or validation model(str): log only Returns:
Feed data to the model and fetch the measures and loss
def run(dataloader, config, net, optimizer=None, lr_scheduler=None, epoch=0, mode='train'): """ Feed data to the model and fetch the measures and loss Args: dataloader(paddle dataloader): exe(): program(): fetchs(dict): dict of measures and the loss epoch(int): epoch of training or validation model(str): log only Returns: """ print_interval = config.get("print_interval", 10) use_mix = config.get("use_mix", False) and mode == "train" metric_list = [ ("loss", AverageMeter( 'loss', '7.5f', postfix=",")), ("lr", AverageMeter( 'lr', 'f', postfix=",", need_avg=False)), ("batch_time", AverageMeter( 'batch_cost', '.5f', postfix=" s,")), ("reader_time", AverageMeter( 'reader_cost', '.5f', postfix=" s,")), ] if not use_mix: topk_name = 'top{}'.format(config.topk) metric_list.insert( 1, (topk_name, AverageMeter( topk_name, '.5f', postfix=","))) metric_list.insert( 1, ("top1", AverageMeter( "top1", '.5f', postfix=","))) metric_list = OrderedDict(metric_list) tic = time.time() for idx, batch in enumerate(dataloader()): # avoid statistics from warmup time if idx == 10: metric_list["batch_time"].reset() metric_list["reader_time"].reset() metric_list['reader_time'].update(time.time() - tic) batch_size = len(batch[0]) feeds = create_feeds(batch, use_mix) fetchs = create_fetchs(feeds, net, config, mode) if mode == 'train': avg_loss = fetchs['loss'] avg_loss.backward() optimizer.step() optimizer.clear_grad() metric_list['lr'].update( optimizer._global_learning_rate().numpy()[0], batch_size) if lr_scheduler is not None: if lr_scheduler.update_specified: curr_global_counter = lr_scheduler.step_each_epoch * epoch + idx update = max( 0, curr_global_counter - lr_scheduler.update_start_step ) % lr_scheduler.update_step_interval == 0 if update: lr_scheduler.step() else: lr_scheduler.step() for name, fetch in fetchs.items(): metric_list[name].update(fetch.numpy()[0], batch_size) metric_list["batch_time"].update(time.time() - tic) tic = time.time() fetchs_str = ' '.join([ str(metric_list[key].mean) if "time" in key else str(metric_list[key].value) for key in metric_list ]) if idx % print_interval == 0: ips_info = "ips: {:.5f} images/sec.".format( batch_size / metric_list["batch_time"].avg) if mode == 'eval': logger.info("{:s} step:{:<4d}, {:s} {:s}".format( mode, idx, fetchs_str, ips_info)) else: epoch_str = "epoch:{:<3d}".format(epoch) step_str = "{:s} step:{:<4d}".format(mode, idx) logger.info("{:s}, {:s}, {:s} {:s}".format( logger.coloring(epoch_str, "HEADER") if idx == 0 else epoch_str, logger.coloring(step_str, "PURPLE"), logger.coloring(fetchs_str, 'OKGREEN'), logger.coloring(ips_info, 'OKGREEN'))) end_str = ' '.join([str(m.mean) for m in metric_list.values()] + [metric_list['batch_time'].total]) ips_info = "ips: {:.5f} images/sec.".format( batch_size * metric_list["batch_time"].count / metric_list["batch_time"].sum) if mode == 'eval': logger.info("END {:s} {:s} {:s}".format(mode, end_str, ips_info)) else: end_epoch_str = "END epoch:{:<3d}".format(epoch) logger.info("{:s} {:s} {:s} {:s}".format( logger.coloring(end_epoch_str, "RED"), logger.coloring(mode, "PURPLE"), logger.coloring(end_str, "OKGREEN"), logger.coloring(ips_info, "OKGREEN"), )) # return top1_acc in order to save the best model if mode == 'valid': return metric_list['top1'].avg
[ "def", "run", "(", "dataloader", ",", "config", ",", "net", ",", "optimizer", "=", "None", ",", "lr_scheduler", "=", "None", ",", "epoch", "=", "0", ",", "mode", "=", "'train'", ")", ":", "print_interval", "=", "config", ".", "get", "(", "\"print_interval\"", ",", "10", ")", "use_mix", "=", "config", ".", "get", "(", "\"use_mix\"", ",", "False", ")", "and", "mode", "==", "\"train\"", "metric_list", "=", "[", "(", "\"loss\"", ",", "AverageMeter", "(", "'loss'", ",", "'7.5f'", ",", "postfix", "=", "\",\"", ")", ")", ",", "(", "\"lr\"", ",", "AverageMeter", "(", "'lr'", ",", "'f'", ",", "postfix", "=", "\",\"", ",", "need_avg", "=", "False", ")", ")", ",", "(", "\"batch_time\"", ",", "AverageMeter", "(", "'batch_cost'", ",", "'.5f'", ",", "postfix", "=", "\" s,\"", ")", ")", ",", "(", "\"reader_time\"", ",", "AverageMeter", "(", "'reader_cost'", ",", "'.5f'", ",", "postfix", "=", "\" s,\"", ")", ")", ",", "]", "if", "not", "use_mix", ":", "topk_name", "=", "'top{}'", ".", "format", "(", "config", ".", "topk", ")", "metric_list", ".", "insert", "(", "1", ",", "(", "topk_name", ",", "AverageMeter", "(", "topk_name", ",", "'.5f'", ",", "postfix", "=", "\",\"", ")", ")", ")", "metric_list", ".", "insert", "(", "1", ",", "(", "\"top1\"", ",", "AverageMeter", "(", "\"top1\"", ",", "'.5f'", ",", "postfix", "=", "\",\"", ")", ")", ")", "metric_list", "=", "OrderedDict", "(", "metric_list", ")", "tic", "=", "time", ".", "time", "(", ")", "for", "idx", ",", "batch", "in", "enumerate", "(", "dataloader", "(", ")", ")", ":", "# avoid statistics from warmup time", "if", "idx", "==", "10", ":", "metric_list", "[", "\"batch_time\"", "]", ".", "reset", "(", ")", "metric_list", "[", "\"reader_time\"", "]", ".", "reset", "(", ")", "metric_list", "[", "'reader_time'", "]", ".", "update", "(", "time", ".", "time", "(", ")", "-", "tic", ")", "batch_size", "=", "len", "(", "batch", "[", "0", "]", ")", "feeds", "=", "create_feeds", "(", "batch", ",", "use_mix", ")", "fetchs", "=", "create_fetchs", "(", "feeds", ",", "net", ",", "config", ",", "mode", ")", "if", "mode", "==", "'train'", ":", "avg_loss", "=", "fetchs", "[", "'loss'", "]", "avg_loss", ".", "backward", "(", ")", "optimizer", ".", "step", "(", ")", "optimizer", ".", "clear_grad", "(", ")", "metric_list", "[", "'lr'", "]", ".", "update", "(", "optimizer", ".", "_global_learning_rate", "(", ")", ".", "numpy", "(", ")", "[", "0", "]", ",", "batch_size", ")", "if", "lr_scheduler", "is", "not", "None", ":", "if", "lr_scheduler", ".", "update_specified", ":", "curr_global_counter", "=", "lr_scheduler", ".", "step_each_epoch", "*", "epoch", "+", "idx", "update", "=", "max", "(", "0", ",", "curr_global_counter", "-", "lr_scheduler", ".", "update_start_step", ")", "%", "lr_scheduler", ".", "update_step_interval", "==", "0", "if", "update", ":", "lr_scheduler", ".", "step", "(", ")", "else", ":", "lr_scheduler", ".", "step", "(", ")", "for", "name", ",", "fetch", "in", "fetchs", ".", "items", "(", ")", ":", "metric_list", "[", "name", "]", ".", "update", "(", "fetch", ".", "numpy", "(", ")", "[", "0", "]", ",", "batch_size", ")", "metric_list", "[", "\"batch_time\"", "]", ".", "update", "(", "time", ".", "time", "(", ")", "-", "tic", ")", "tic", "=", "time", ".", "time", "(", ")", "fetchs_str", "=", "' '", ".", "join", "(", "[", "str", "(", "metric_list", "[", "key", "]", ".", "mean", ")", "if", "\"time\"", "in", "key", "else", "str", "(", "metric_list", "[", "key", "]", ".", "value", ")", "for", "key", "in", "metric_list", "]", ")", "if", "idx", "%", "print_interval", "==", "0", ":", "ips_info", "=", "\"ips: {:.5f} images/sec.\"", ".", "format", "(", "batch_size", "/", "metric_list", "[", "\"batch_time\"", "]", ".", "avg", ")", "if", "mode", "==", "'eval'", ":", "logger", ".", "info", "(", "\"{:s} step:{:<4d}, {:s} {:s}\"", ".", "format", "(", "mode", ",", "idx", ",", "fetchs_str", ",", "ips_info", ")", ")", "else", ":", "epoch_str", "=", "\"epoch:{:<3d}\"", ".", "format", "(", "epoch", ")", "step_str", "=", "\"{:s} step:{:<4d}\"", ".", "format", "(", "mode", ",", "idx", ")", "logger", ".", "info", "(", "\"{:s}, {:s}, {:s} {:s}\"", ".", "format", "(", "logger", ".", "coloring", "(", "epoch_str", ",", "\"HEADER\"", ")", "if", "idx", "==", "0", "else", "epoch_str", ",", "logger", ".", "coloring", "(", "step_str", ",", "\"PURPLE\"", ")", ",", "logger", ".", "coloring", "(", "fetchs_str", ",", "'OKGREEN'", ")", ",", "logger", ".", "coloring", "(", "ips_info", ",", "'OKGREEN'", ")", ")", ")", "end_str", "=", "' '", ".", "join", "(", "[", "str", "(", "m", ".", "mean", ")", "for", "m", "in", "metric_list", ".", "values", "(", ")", "]", "+", "[", "metric_list", "[", "'batch_time'", "]", ".", "total", "]", ")", "ips_info", "=", "\"ips: {:.5f} images/sec.\"", ".", "format", "(", "batch_size", "*", "metric_list", "[", "\"batch_time\"", "]", ".", "count", "/", "metric_list", "[", "\"batch_time\"", "]", ".", "sum", ")", "if", "mode", "==", "'eval'", ":", "logger", ".", "info", "(", "\"END {:s} {:s} {:s}\"", ".", "format", "(", "mode", ",", "end_str", ",", "ips_info", ")", ")", "else", ":", "end_epoch_str", "=", "\"END epoch:{:<3d}\"", ".", "format", "(", "epoch", ")", "logger", ".", "info", "(", "\"{:s} {:s} {:s} {:s}\"", ".", "format", "(", "logger", ".", "coloring", "(", "end_epoch_str", ",", "\"RED\"", ")", ",", "logger", ".", "coloring", "(", "mode", ",", "\"PURPLE\"", ")", ",", "logger", ".", "coloring", "(", "end_str", ",", "\"OKGREEN\"", ")", ",", "logger", ".", "coloring", "(", "ips_info", ",", "\"OKGREEN\"", ")", ",", ")", ")", "# return top1_acc in order to save the best model", "if", "mode", "==", "'valid'", ":", "return", "metric_list", "[", "'top1'", "]", ".", "avg" ]
[ 254, 0 ]
[ 375, 38 ]
python
en
['en', 'error', 'th']
False
make_signed_jwt
(signer, payload, key_id=None)
Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for the payload.
Make a signed JWT.
def make_signed_jwt(signer, payload, key_id=None): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} if key_id is not None: header['kid'] = key_id segments = [ _helpers._urlsafe_b64encode(_helpers._json_encode(header)), _helpers._urlsafe_b64encode(_helpers._json_encode(payload)), ] signing_input = b'.'.join(segments) signature = signer.sign(signing_input) segments.append(_helpers._urlsafe_b64encode(signature)) logger.debug(str(segments)) return b'.'.join(segments)
[ "def", "make_signed_jwt", "(", "signer", ",", "payload", ",", "key_id", "=", "None", ")", ":", "header", "=", "{", "'typ'", ":", "'JWT'", ",", "'alg'", ":", "'RS256'", "}", "if", "key_id", "is", "not", "None", ":", "header", "[", "'kid'", "]", "=", "key_id", "segments", "=", "[", "_helpers", ".", "_urlsafe_b64encode", "(", "_helpers", ".", "_json_encode", "(", "header", ")", ")", ",", "_helpers", ".", "_urlsafe_b64encode", "(", "_helpers", ".", "_json_encode", "(", "payload", ")", ")", ",", "]", "signing_input", "=", "b'.'", ".", "join", "(", "segments", ")", "signature", "=", "signer", ".", "sign", "(", "signing_input", ")", "segments", ".", "append", "(", "_helpers", ".", "_urlsafe_b64encode", "(", "signature", ")", ")", "logger", ".", "debug", "(", "str", "(", "segments", ")", ")", "return", "b'.'", ".", "join", "(", "segments", ")" ]
[ 73, 0 ]
[ 101, 30 ]
python
en
['en', 'da', 'en']
True
_verify_signature
(message, signature, certs)
Verifies signed content using a list of certificates. Args: message: string or bytes, The message to verify. signature: string or bytes, The signature on the message. certs: iterable, certificates in PEM format. Raises: AppIdentityError: If none of the certificates can verify the message against the signature.
Verifies signed content using a list of certificates.
def _verify_signature(message, signature, certs): """Verifies signed content using a list of certificates. Args: message: string or bytes, The message to verify. signature: string or bytes, The signature on the message. certs: iterable, certificates in PEM format. Raises: AppIdentityError: If none of the certificates can verify the message against the signature. """ for pem in certs: verifier = Verifier.from_string(pem, is_x509_cert=True) if verifier.verify(message, signature): return # If we have not returned, no certificate confirms the signature. raise AppIdentityError('Invalid token signature')
[ "def", "_verify_signature", "(", "message", ",", "signature", ",", "certs", ")", ":", "for", "pem", "in", "certs", ":", "verifier", "=", "Verifier", ".", "from_string", "(", "pem", ",", "is_x509_cert", "=", "True", ")", "if", "verifier", ".", "verify", "(", "message", ",", "signature", ")", ":", "return", "# If we have not returned, no certificate confirms the signature.", "raise", "AppIdentityError", "(", "'Invalid token signature'", ")" ]
[ 104, 0 ]
[ 122, 53 ]
python
en
['en', 'en', 'en']
True
_check_audience
(payload_dict, audience)
Checks audience field from a JWT payload. Does nothing if the passed in ``audience`` is null. Args: payload_dict: dict, A dictionary containing a JWT payload. audience: string or NoneType, an audience to check for in the JWT payload. Raises: AppIdentityError: If there is no ``'aud'`` field in the payload dictionary but there is an ``audience`` to check. AppIdentityError: If the ``'aud'`` field in the payload dictionary does not match the ``audience``.
Checks audience field from a JWT payload.
def _check_audience(payload_dict, audience): """Checks audience field from a JWT payload. Does nothing if the passed in ``audience`` is null. Args: payload_dict: dict, A dictionary containing a JWT payload. audience: string or NoneType, an audience to check for in the JWT payload. Raises: AppIdentityError: If there is no ``'aud'`` field in the payload dictionary but there is an ``audience`` to check. AppIdentityError: If the ``'aud'`` field in the payload dictionary does not match the ``audience``. """ if audience is None: return audience_in_payload = payload_dict.get('aud') if audience_in_payload is None: raise AppIdentityError( 'No aud field in token: {0}'.format(payload_dict)) if audience_in_payload != audience: raise AppIdentityError('Wrong recipient, {0} != {1}: {2}'.format( audience_in_payload, audience, payload_dict))
[ "def", "_check_audience", "(", "payload_dict", ",", "audience", ")", ":", "if", "audience", "is", "None", ":", "return", "audience_in_payload", "=", "payload_dict", ".", "get", "(", "'aud'", ")", "if", "audience_in_payload", "is", "None", ":", "raise", "AppIdentityError", "(", "'No aud field in token: {0}'", ".", "format", "(", "payload_dict", ")", ")", "if", "audience_in_payload", "!=", "audience", ":", "raise", "AppIdentityError", "(", "'Wrong recipient, {0} != {1}: {2}'", ".", "format", "(", "audience_in_payload", ",", "audience", ",", "payload_dict", ")", ")" ]
[ 125, 0 ]
[ 150, 57 ]
python
en
['en', 'en', 'en']
True
_verify_time_range
(payload_dict)
Verifies the issued at and expiration from a JWT payload. Makes sure the current time (in UTC) falls between the issued at and expiration for the JWT (with some skew allowed for via ``CLOCK_SKEW_SECS``). Args: payload_dict: dict, A dictionary containing a JWT payload. Raises: AppIdentityError: If there is no ``'iat'`` field in the payload dictionary. AppIdentityError: If there is no ``'exp'`` field in the payload dictionary. AppIdentityError: If the JWT expiration is too far in the future (i.e. if the expiration would imply a token lifetime longer than what is allowed.) AppIdentityError: If the token appears to have been issued in the future (up to clock skew). AppIdentityError: If the token appears to have expired in the past (up to clock skew).
Verifies the issued at and expiration from a JWT payload.
def _verify_time_range(payload_dict): """Verifies the issued at and expiration from a JWT payload. Makes sure the current time (in UTC) falls between the issued at and expiration for the JWT (with some skew allowed for via ``CLOCK_SKEW_SECS``). Args: payload_dict: dict, A dictionary containing a JWT payload. Raises: AppIdentityError: If there is no ``'iat'`` field in the payload dictionary. AppIdentityError: If there is no ``'exp'`` field in the payload dictionary. AppIdentityError: If the JWT expiration is too far in the future (i.e. if the expiration would imply a token lifetime longer than what is allowed.) AppIdentityError: If the token appears to have been issued in the future (up to clock skew). AppIdentityError: If the token appears to have expired in the past (up to clock skew). """ # Get the current time to use throughout. now = int(time.time()) # Make sure issued at and expiration are in the payload. issued_at = payload_dict.get('iat') if issued_at is None: raise AppIdentityError( 'No iat field in token: {0}'.format(payload_dict)) expiration = payload_dict.get('exp') if expiration is None: raise AppIdentityError( 'No exp field in token: {0}'.format(payload_dict)) # Make sure the expiration gives an acceptable token lifetime. if expiration >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: {0}'.format(payload_dict)) # Make sure (up to clock skew) that the token wasn't issued in the future. earliest = issued_at - CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format( now, earliest, payload_dict)) # Make sure (up to clock skew) that the token isn't already expired. latest = expiration + CLOCK_SKEW_SECS if now > latest: raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format( now, latest, payload_dict))
[ "def", "_verify_time_range", "(", "payload_dict", ")", ":", "# Get the current time to use throughout.", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "# Make sure issued at and expiration are in the payload.", "issued_at", "=", "payload_dict", ".", "get", "(", "'iat'", ")", "if", "issued_at", "is", "None", ":", "raise", "AppIdentityError", "(", "'No iat field in token: {0}'", ".", "format", "(", "payload_dict", ")", ")", "expiration", "=", "payload_dict", ".", "get", "(", "'exp'", ")", "if", "expiration", "is", "None", ":", "raise", "AppIdentityError", "(", "'No exp field in token: {0}'", ".", "format", "(", "payload_dict", ")", ")", "# Make sure the expiration gives an acceptable token lifetime.", "if", "expiration", ">=", "now", "+", "MAX_TOKEN_LIFETIME_SECS", ":", "raise", "AppIdentityError", "(", "'exp field too far in future: {0}'", ".", "format", "(", "payload_dict", ")", ")", "# Make sure (up to clock skew) that the token wasn't issued in the future.", "earliest", "=", "issued_at", "-", "CLOCK_SKEW_SECS", "if", "now", "<", "earliest", ":", "raise", "AppIdentityError", "(", "'Token used too early, {0} < {1}: {2}'", ".", "format", "(", "now", ",", "earliest", ",", "payload_dict", ")", ")", "# Make sure (up to clock skew) that the token isn't already expired.", "latest", "=", "expiration", "+", "CLOCK_SKEW_SECS", "if", "now", ">", "latest", ":", "raise", "AppIdentityError", "(", "'Token used too late, {0} > {1}: {2}'", ".", "format", "(", "now", ",", "latest", ",", "payload_dict", ")", ")" ]
[ 153, 0 ]
[ 203, 39 ]
python
en
['en', 'en', 'en']
True
verify_signed_jwt_with_certs
(jwt, certs, audience=None)
Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError: if any checks are failed.
Verify a JWT against public certs.
def verify_signed_jwt_with_certs(jwt, certs, audience=None): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError: if any checks are failed. """ jwt = _helpers._to_bytes(jwt) if jwt.count(b'.') != 2: raise AppIdentityError( 'Wrong number of segments in token: {0}'.format(jwt)) header, payload, signature = jwt.split(b'.') message_to_sign = header + b'.' + payload signature = _helpers._urlsafe_b64decode(signature) # Parse token. payload_bytes = _helpers._urlsafe_b64decode(payload) try: payload_dict = json.loads(_helpers._from_bytes(payload_bytes)) except: raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes)) # Verify that the signature matches the message. _verify_signature(message_to_sign, signature, certs.values()) # Verify the issued at and created times in the payload. _verify_time_range(payload_dict) # Check audience. _check_audience(payload_dict, audience) return payload_dict
[ "def", "verify_signed_jwt_with_certs", "(", "jwt", ",", "certs", ",", "audience", "=", "None", ")", ":", "jwt", "=", "_helpers", ".", "_to_bytes", "(", "jwt", ")", "if", "jwt", ".", "count", "(", "b'.'", ")", "!=", "2", ":", "raise", "AppIdentityError", "(", "'Wrong number of segments in token: {0}'", ".", "format", "(", "jwt", ")", ")", "header", ",", "payload", ",", "signature", "=", "jwt", ".", "split", "(", "b'.'", ")", "message_to_sign", "=", "header", "+", "b'.'", "+", "payload", "signature", "=", "_helpers", ".", "_urlsafe_b64decode", "(", "signature", ")", "# Parse token.", "payload_bytes", "=", "_helpers", ".", "_urlsafe_b64decode", "(", "payload", ")", "try", ":", "payload_dict", "=", "json", ".", "loads", "(", "_helpers", ".", "_from_bytes", "(", "payload_bytes", ")", ")", "except", ":", "raise", "AppIdentityError", "(", "'Can\\'t parse token: {0}'", ".", "format", "(", "payload_bytes", ")", ")", "# Verify that the signature matches the message.", "_verify_signature", "(", "message_to_sign", ",", "signature", ",", "certs", ".", "values", "(", ")", ")", "# Verify the issued at and created times in the payload.", "_verify_time_range", "(", "payload_dict", ")", "# Check audience.", "_check_audience", "(", "payload_dict", ",", "audience", ")", "return", "payload_dict" ]
[ 206, 0 ]
[ 249, 23 ]
python
en
['en', 'fr', 'en']
True
EmailBackend.open
(self)
Ensure an open connection to the email server. Return whether or not a new connection was required (True or False) or None if an exception passed silently.
Ensure an open connection to the email server. Return whether or not a new connection was required (True or False) or None if an exception passed silently.
def open(self): """ Ensure an open connection to the email server. Return whether or not a new connection was required (True or False) or None if an exception passed silently. """ if self.connection: # Nothing to do if the connection is already open. return False # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. connection_params = {'local_hostname': DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params['timeout'] = self.timeout if self.use_ssl: connection_params.update({ 'keyfile': self.ssl_keyfile, 'certfile': self.ssl_certfile, }) try: self.connection = self.connection_class(self.host, self.port, **connection_params) # TLS/SSL are mutually exclusive, so only attempt TLS over # non-secure connections. if not self.use_ssl and self.use_tls: self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) if self.username and self.password: self.connection.login(self.username, self.password) return True except OSError: if not self.fail_silently: raise
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "connection", ":", "# Nothing to do if the connection is already open.", "return", "False", "# If local_hostname is not specified, socket.getfqdn() gets used.", "# For performance, we use the cached FQDN for local_hostname.", "connection_params", "=", "{", "'local_hostname'", ":", "DNS_NAME", ".", "get_fqdn", "(", ")", "}", "if", "self", ".", "timeout", "is", "not", "None", ":", "connection_params", "[", "'timeout'", "]", "=", "self", ".", "timeout", "if", "self", ".", "use_ssl", ":", "connection_params", ".", "update", "(", "{", "'keyfile'", ":", "self", ".", "ssl_keyfile", ",", "'certfile'", ":", "self", ".", "ssl_certfile", ",", "}", ")", "try", ":", "self", ".", "connection", "=", "self", ".", "connection_class", "(", "self", ".", "host", ",", "self", ".", "port", ",", "*", "*", "connection_params", ")", "# TLS/SSL are mutually exclusive, so only attempt TLS over", "# non-secure connections.", "if", "not", "self", ".", "use_ssl", "and", "self", ".", "use_tls", ":", "self", ".", "connection", ".", "starttls", "(", "keyfile", "=", "self", ".", "ssl_keyfile", ",", "certfile", "=", "self", ".", "ssl_certfile", ")", "if", "self", ".", "username", "and", "self", ".", "password", ":", "self", ".", "connection", ".", "login", "(", "self", ".", "username", ",", "self", ".", "password", ")", "return", "True", "except", "OSError", ":", "if", "not", "self", ".", "fail_silently", ":", "raise" ]
[ 40, 4 ]
[ 72, 21 ]
python
en
['en', 'error', 'th']
False
EmailBackend.close
(self)
Close the connection to the email server.
Close the connection to the email server.
def close(self): """Close the connection to the email server.""" if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): # This happens when calling quit() on a TLS connection # sometimes, or when the connection was already disconnected # by the server. self.connection.close() except smtplib.SMTPException: if self.fail_silently: return raise finally: self.connection = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "return", "try", ":", "try", ":", "self", ".", "connection", ".", "quit", "(", ")", "except", "(", "ssl", ".", "SSLError", ",", "smtplib", ".", "SMTPServerDisconnected", ")", ":", "# This happens when calling quit() on a TLS connection", "# sometimes, or when the connection was already disconnected", "# by the server.", "self", ".", "connection", ".", "close", "(", ")", "except", "smtplib", ".", "SMTPException", ":", "if", "self", ".", "fail_silently", ":", "return", "raise", "finally", ":", "self", ".", "connection", "=", "None" ]
[ 74, 4 ]
[ 91, 34 ]
python
en
['en', 'en', 'en']
True
EmailBackend.send_messages
(self, email_messages)
Send one or more EmailMessage objects and return the number of email messages sent.
Send one or more EmailMessage objects and return the number of email messages sent.
def send_messages(self, email_messages): """ Send one or more EmailMessage objects and return the number of email messages sent. """ if not email_messages: return 0 with self._lock: new_conn_created = self.open() if not self.connection or new_conn_created is None: # We failed silently on open(). # Trying to send would be pointless. return 0 num_sent = 0 for message in email_messages: sent = self._send(message) if sent: num_sent += 1 if new_conn_created: self.close() return num_sent
[ "def", "send_messages", "(", "self", ",", "email_messages", ")", ":", "if", "not", "email_messages", ":", "return", "0", "with", "self", ".", "_lock", ":", "new_conn_created", "=", "self", ".", "open", "(", ")", "if", "not", "self", ".", "connection", "or", "new_conn_created", "is", "None", ":", "# We failed silently on open().", "# Trying to send would be pointless.", "return", "0", "num_sent", "=", "0", "for", "message", "in", "email_messages", ":", "sent", "=", "self", ".", "_send", "(", "message", ")", "if", "sent", ":", "num_sent", "+=", "1", "if", "new_conn_created", ":", "self", ".", "close", "(", ")", "return", "num_sent" ]
[ 93, 4 ]
[ 113, 23 ]
python
en
['en', 'error', 'th']
False
EmailBackend._send
(self, email_message)
A helper method that does the actual sending.
A helper method that does the actual sending.
def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False encoding = email_message.encoding or settings.DEFAULT_CHARSET from_email = sanitize_address(email_message.from_email, encoding) recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()] message = email_message.message() try: self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) except smtplib.SMTPException: if not self.fail_silently: raise return False return True
[ "def", "_send", "(", "self", ",", "email_message", ")", ":", "if", "not", "email_message", ".", "recipients", "(", ")", ":", "return", "False", "encoding", "=", "email_message", ".", "encoding", "or", "settings", ".", "DEFAULT_CHARSET", "from_email", "=", "sanitize_address", "(", "email_message", ".", "from_email", ",", "encoding", ")", "recipients", "=", "[", "sanitize_address", "(", "addr", ",", "encoding", ")", "for", "addr", "in", "email_message", ".", "recipients", "(", ")", "]", "message", "=", "email_message", ".", "message", "(", ")", "try", ":", "self", ".", "connection", ".", "sendmail", "(", "from_email", ",", "recipients", ",", "message", ".", "as_bytes", "(", "linesep", "=", "'\\r\\n'", ")", ")", "except", "smtplib", ".", "SMTPException", ":", "if", "not", "self", ".", "fail_silently", ":", "raise", "return", "False", "return", "True" ]
[ 115, 4 ]
[ 129, 19 ]
python
en
['en', 'en', 'en']
True
setupmethod
(f)
Wraps a method so that it performs a check in debug mode if the first request was already handled.
Wraps a method so that it performs a check in debug mode if the first request was already handled.
def setupmethod(f): """Wraps a method so that it performs a check in debug mode if the first request was already handled. """ def wrapper_func(self, *args, **kwargs): if self.debug and self._got_first_request: raise AssertionError('A setup function was called after the ' 'first request was handled. This usually indicates a bug ' 'in the application where a module was not imported ' 'and decorators or other functionality was called too late.\n' 'To fix this make sure to import all your view modules, ' 'database models and everything related at a central place ' 'before the application starts serving requests.') return f(self, *args, **kwargs) return update_wrapper(wrapper_func, f)
[ "def", "setupmethod", "(", "f", ")", ":", "def", "wrapper_func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "debug", "and", "self", ".", "_got_first_request", ":", "raise", "AssertionError", "(", "'A setup function was called after the '", "'first request was handled. This usually indicates a bug '", "'in the application where a module was not imported '", "'and decorators or other functionality was called too late.\\n'", "'To fix this make sure to import all your view modules, '", "'database models and everything related at a central place '", "'before the application starts serving requests.'", ")", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "update_wrapper", "(", "wrapper_func", ",", "f", ")" ]
[ 50, 0 ]
[ 64, 42 ]
python
en
['en', 'en', 'en']
True
Flask.name
(self)
The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value. .. versionadded:: 0.8
The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.
def name(self): """The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value. .. versionadded:: 0.8 """ if self.import_name == '__main__': fn = getattr(sys.modules['__main__'], '__file__', None) if fn is None: return '__main__' return os.path.splitext(os.path.basename(fn))[0] return self.import_name
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "import_name", "==", "'__main__'", ":", "fn", "=", "getattr", "(", "sys", ".", "modules", "[", "'__main__'", "]", ",", "'__file__'", ",", "None", ")", "if", "fn", "is", "None", ":", "return", "'__main__'", "return", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "fn", ")", ")", "[", "0", "]", "return", "self", ".", "import_name" ]
[ 562, 4 ]
[ 576, 31 ]
python
en
['en', 'en', 'en']
True
Flask.propagate_exceptions
(self)
Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7
Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration value in case it's set, otherwise a sensible default is returned.
def propagate_exceptions(self): """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7 """ rv = self.config['PROPAGATE_EXCEPTIONS'] if rv is not None: return rv return self.testing or self.debug
[ "def", "propagate_exceptions", "(", "self", ")", ":", "rv", "=", "self", ".", "config", "[", "'PROPAGATE_EXCEPTIONS'", "]", "if", "rv", "is", "not", "None", ":", "return", "rv", "return", "self", ".", "testing", "or", "self", ".", "debug" ]
[ 579, 4 ]
[ 588, 41 ]
python
en
['en', 'en', 'en']
True
Flask.preserve_context_on_exception
(self)
Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7
Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration value in case it's set, otherwise a sensible default is returned.
def preserve_context_on_exception(self): """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7 """ rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION'] if rv is not None: return rv return self.debug
[ "def", "preserve_context_on_exception", "(", "self", ")", ":", "rv", "=", "self", ".", "config", "[", "'PRESERVE_CONTEXT_ON_EXCEPTION'", "]", "if", "rv", "is", "not", "None", ":", "return", "rv", "return", "self", ".", "debug" ]
[ 591, 4 ]
[ 601, 25 ]
python
en
['en', 'en', 'en']
True
Flask.logger
(self)
A :class:`logging.Logger` object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:: app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') .. versionadded:: 0.3
A :class:`logging.Logger` object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples::
def logger(self): """A :class:`logging.Logger` object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:: app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') .. versionadded:: 0.3 """ if self._logger and self._logger.name == self.logger_name: return self._logger with _logger_lock: if self._logger and self._logger.name == self.logger_name: return self._logger from flask.logging import create_logger self._logger = rv = create_logger(self) return rv
[ "def", "logger", "(", "self", ")", ":", "if", "self", ".", "_logger", "and", "self", ".", "_logger", ".", "name", "==", "self", ".", "logger_name", ":", "return", "self", ".", "_logger", "with", "_logger_lock", ":", "if", "self", ".", "_logger", "and", "self", ".", "_logger", ".", "name", "==", "self", ".", "logger_name", ":", "return", "self", ".", "_logger", "from", "flask", ".", "logging", "import", "create_logger", "self", ".", "_logger", "=", "rv", "=", "create_logger", "(", "self", ")", "return", "rv" ]
[ 604, 4 ]
[ 623, 21 ]
python
en
['en', 'en', 'en']
True
Flask.jinja_env
(self)
The Jinja2 environment used to load templates.
The Jinja2 environment used to load templates.
def jinja_env(self): """The Jinja2 environment used to load templates.""" return self.create_jinja_environment()
[ "def", "jinja_env", "(", "self", ")", ":", "return", "self", ".", "create_jinja_environment", "(", ")" ]
[ 626, 4 ]
[ 628, 46 ]
python
en
['en', 'en', 'en']
True
Flask.got_first_request
(self)
This attribute is set to ``True`` if the application started handling the first request. .. versionadded:: 0.8
This attribute is set to ``True`` if the application started handling the first request.
def got_first_request(self): """This attribute is set to ``True`` if the application started handling the first request. .. versionadded:: 0.8 """ return self._got_first_request
[ "def", "got_first_request", "(", "self", ")", ":", "return", "self", ".", "_got_first_request" ]
[ 631, 4 ]
[ 637, 38 ]
python
en
['en', 'en', 'en']
True
Flask.make_config
(self, instance_relative=False)
Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application. .. versionadded:: 0.8
Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application.
def make_config(self, instance_relative=False): """Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application. .. versionadded:: 0.8 """ root_path = self.root_path if instance_relative: root_path = self.instance_path return self.config_class(root_path, self.default_config)
[ "def", "make_config", "(", "self", ",", "instance_relative", "=", "False", ")", ":", "root_path", "=", "self", ".", "root_path", "if", "instance_relative", ":", "root_path", "=", "self", ".", "instance_path", "return", "self", ".", "config_class", "(", "root_path", ",", "self", ".", "default_config", ")" ]
[ 639, 4 ]
[ 651, 64 ]
python
en
['en', 'en', 'en']
True
Flask.auto_find_instance_path
(self)
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package.
def auto_find_instance_path(self): """Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8 """ prefix, package_path = find_package(self.import_name) if prefix is None: return os.path.join(package_path, 'instance') return os.path.join(prefix, 'var', self.name + '-instance')
[ "def", "auto_find_instance_path", "(", "self", ")", ":", "prefix", ",", "package_path", "=", "find_package", "(", "self", ".", "import_name", ")", "if", "prefix", "is", "None", ":", "return", "os", ".", "path", ".", "join", "(", "package_path", ",", "'instance'", ")", "return", "os", ".", "path", ".", "join", "(", "prefix", ",", "'var'", ",", "self", ".", "name", "+", "'-instance'", ")" ]
[ 653, 4 ]
[ 664, 67 ]
python
en
['en', 'en', 'en']
True
Flask.open_instance_resource
(self, resource, mode='rb')
Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing. :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. :param mode: resource file opening mode, default is 'rb'.
Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing.
def open_instance_resource(self, resource, mode='rb'): """Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing. :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. :param mode: resource file opening mode, default is 'rb'. """ return open(os.path.join(self.instance_path, resource), mode)
[ "def", "open_instance_resource", "(", "self", ",", "resource", ",", "mode", "=", "'rb'", ")", ":", "return", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "instance_path", ",", "resource", ")", ",", "mode", ")" ]
[ 666, 4 ]
[ 676, 69 ]
python
en
['en', 'en', 'en']
True
Flask.create_jinja_environment
(self)
Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. .. versionadded:: 0.5 .. versionchanged:: 0.11 ``Environment.auto_reload`` set in accordance with ``TEMPLATES_AUTO_RELOAD`` configuration option.
Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior.
def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior. .. versionadded:: 0.5 .. versionchanged:: 0.11 ``Environment.auto_reload`` set in accordance with ``TEMPLATES_AUTO_RELOAD`` configuration option. """ options = dict(self.jinja_options) if 'autoescape' not in options: options['autoescape'] = self.select_jinja_autoescape if 'auto_reload' not in options: if self.config['TEMPLATES_AUTO_RELOAD'] is not None: options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD'] else: options['auto_reload'] = self.debug rv = self.jinja_environment(self, **options) rv.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages, config=self.config, # request, session and g are normally added with the # context processor for efficiency reasons but for imported # templates we also want the proxies in there. request=request, session=session, g=g ) rv.filters['tojson'] = json.tojson_filter return rv
[ "def", "create_jinja_environment", "(", "self", ")", ":", "options", "=", "dict", "(", "self", ".", "jinja_options", ")", "if", "'autoescape'", "not", "in", "options", ":", "options", "[", "'autoescape'", "]", "=", "self", ".", "select_jinja_autoescape", "if", "'auto_reload'", "not", "in", "options", ":", "if", "self", ".", "config", "[", "'TEMPLATES_AUTO_RELOAD'", "]", "is", "not", "None", ":", "options", "[", "'auto_reload'", "]", "=", "self", ".", "config", "[", "'TEMPLATES_AUTO_RELOAD'", "]", "else", ":", "options", "[", "'auto_reload'", "]", "=", "self", ".", "debug", "rv", "=", "self", ".", "jinja_environment", "(", "self", ",", "*", "*", "options", ")", "rv", ".", "globals", ".", "update", "(", "url_for", "=", "url_for", ",", "get_flashed_messages", "=", "get_flashed_messages", ",", "config", "=", "self", ".", "config", ",", "# request, session and g are normally added with the", "# context processor for efficiency reasons but for imported", "# templates we also want the proxies in there.", "request", "=", "request", ",", "session", "=", "session", ",", "g", "=", "g", ")", "rv", ".", "filters", "[", "'tojson'", "]", "=", "json", ".", "tojson_filter", "return", "rv" ]
[ 678, 4 ]
[ 710, 17 ]
python
en
['en', 'et', 'en']
True
Flask.create_global_jinja_loader
(self)
Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It's discouraged to override this function. Instead one should override the :meth:`jinja_loader` function instead. The global loader dispatches between the loaders of the application and the individual blueprints. .. versionadded:: 0.7
Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It's discouraged to override this function. Instead one should override the :meth:`jinja_loader` function instead.
def create_global_jinja_loader(self): """Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It's discouraged to override this function. Instead one should override the :meth:`jinja_loader` function instead. The global loader dispatches between the loaders of the application and the individual blueprints. .. versionadded:: 0.7 """ return DispatchingJinjaLoader(self)
[ "def", "create_global_jinja_loader", "(", "self", ")", ":", "return", "DispatchingJinjaLoader", "(", "self", ")" ]
[ 712, 4 ]
[ 723, 43 ]
python
en
['en', 'en', 'en']
True
Flask.init_jinja_globals
(self)
Deprecated. Used to initialize the Jinja2 globals. .. versionadded:: 0.5 .. versionchanged:: 0.7 This method is deprecated with 0.7. Override :meth:`create_jinja_environment` instead.
Deprecated. Used to initialize the Jinja2 globals.
def init_jinja_globals(self): """Deprecated. Used to initialize the Jinja2 globals. .. versionadded:: 0.5 .. versionchanged:: 0.7 This method is deprecated with 0.7. Override :meth:`create_jinja_environment` instead. """
[ "def", "init_jinja_globals", "(", "self", ")", ":" ]
[ 725, 4 ]
[ 732, 11 ]
python
en
['en', 'en', 'en']
True
Flask.select_jinja_autoescape
(self, filename)
Returns ``True`` if autoescaping should be active for the given template name. If no template name is given, returns `True`. .. versionadded:: 0.5
Returns ``True`` if autoescaping should be active for the given template name. If no template name is given, returns `True`.
def select_jinja_autoescape(self, filename): """Returns ``True`` if autoescaping should be active for the given template name. If no template name is given, returns `True`. .. versionadded:: 0.5 """ if filename is None: return True return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))
[ "def", "select_jinja_autoescape", "(", "self", ",", "filename", ")", ":", "if", "filename", "is", "None", ":", "return", "True", "return", "filename", ".", "endswith", "(", "(", "'.html'", ",", "'.htm'", ",", "'.xml'", ",", "'.xhtml'", ")", ")" ]
[ 734, 4 ]
[ 742, 69 ]
python
en
['en', 'en', 'en']
True
Flask.update_template_context
(self, context)
Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. :param context: the context as a dictionary that is updated in place to add extra variables.
Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key.
def update_template_context(self, context): """Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. :param context: the context as a dictionary that is updated in place to add extra variables. """ funcs = self.template_context_processors[None] reqctx = _request_ctx_stack.top if reqctx is not None: bp = reqctx.request.blueprint if bp is not None and bp in self.template_context_processors: funcs = chain(funcs, self.template_context_processors[bp]) orig_ctx = context.copy() for func in funcs: context.update(func()) # make sure the original values win. This makes it possible to # easier add new variables in context processors without breaking # existing views. context.update(orig_ctx)
[ "def", "update_template_context", "(", "self", ",", "context", ")", ":", "funcs", "=", "self", ".", "template_context_processors", "[", "None", "]", "reqctx", "=", "_request_ctx_stack", ".", "top", "if", "reqctx", "is", "not", "None", ":", "bp", "=", "reqctx", ".", "request", ".", "blueprint", "if", "bp", "is", "not", "None", "and", "bp", "in", "self", ".", "template_context_processors", ":", "funcs", "=", "chain", "(", "funcs", ",", "self", ".", "template_context_processors", "[", "bp", "]", ")", "orig_ctx", "=", "context", ".", "copy", "(", ")", "for", "func", "in", "funcs", ":", "context", ".", "update", "(", "func", "(", ")", ")", "# make sure the original values win. This makes it possible to", "# easier add new variables in context processors without breaking", "# existing views.", "context", ".", "update", "(", "orig_ctx", ")" ]
[ 744, 4 ]
[ 767, 32 ]
python
en
['en', 'en', 'en']
True
Flask.make_shell_context
(self)
Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. .. versionadded:: 0.11
Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
def make_shell_context(self): """Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. .. versionadded:: 0.11 """ rv = {'app': self, 'g': g} for processor in self.shell_context_processors: rv.update(processor()) return rv
[ "def", "make_shell_context", "(", "self", ")", ":", "rv", "=", "{", "'app'", ":", "self", ",", "'g'", ":", "g", "}", "for", "processor", "in", "self", ".", "shell_context_processors", ":", "rv", ".", "update", "(", "processor", "(", ")", ")", "return", "rv" ]
[ 769, 4 ]
[ 779, 17 ]
python
en
['en', 'en', 'en']
True
Flask.run
(self, host=None, port=None, debug=None, **options)
Runs the application on a local development server. Do not use ``run()`` in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see :ref:`deployment` for WSGI server recommendations. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass ``use_evalex=False`` as parameter. This will keep the debugger's traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the :command:`flask` command line script's ``run`` support. .. admonition:: Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. Setting ``use_debugger`` to ``True`` without being in debug mode won't catch any exceptions because there won't be any to catch. .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to have the server available externally as well. Defaults to ``'127.0.0.1'``. :param port: the port of the webserver. Defaults to ``5000`` or the port defined in the ``SERVER_NAME`` config variable if present. :param debug: if given, enable or disable debug mode. See :attr:`debug`. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information.
Runs the application on a local development server.
def run(self, host=None, port=None, debug=None, **options): """Runs the application on a local development server. Do not use ``run()`` in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see :ref:`deployment` for WSGI server recommendations. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass ``use_evalex=False`` as parameter. This will keep the debugger's traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the :command:`flask` command line script's ``run`` support. .. admonition:: Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. Setting ``use_debugger`` to ``True`` without being in debug mode won't catch any exceptions because there won't be any to catch. .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to have the server available externally as well. Defaults to ``'127.0.0.1'``. :param port: the port of the webserver. Defaults to ``5000`` or the port defined in the ``SERVER_NAME`` config variable if present. :param debug: if given, enable or disable debug mode. See :attr:`debug`. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information. """ from werkzeug.serving import run_simple if host is None: host = '127.0.0.1' if port is None: server_name = self.config['SERVER_NAME'] if server_name and ':' in server_name: port = int(server_name.rsplit(':', 1)[1]) else: port = 5000 if debug is not None: self.debug = bool(debug) options.setdefault('use_reloader', self.debug) options.setdefault('use_debugger', self.debug) try: run_simple(host, port, self, **options) finally: # reset the first request information if the development server # reset normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False
[ "def", "run", "(", "self", ",", "host", "=", "None", ",", "port", "=", "None", ",", "debug", "=", "None", ",", "*", "*", "options", ")", ":", "from", "werkzeug", ".", "serving", "import", "run_simple", "if", "host", "is", "None", ":", "host", "=", "'127.0.0.1'", "if", "port", "is", "None", ":", "server_name", "=", "self", ".", "config", "[", "'SERVER_NAME'", "]", "if", "server_name", "and", "':'", "in", "server_name", ":", "port", "=", "int", "(", "server_name", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "1", "]", ")", "else", ":", "port", "=", "5000", "if", "debug", "is", "not", "None", ":", "self", ".", "debug", "=", "bool", "(", "debug", ")", "options", ".", "setdefault", "(", "'use_reloader'", ",", "self", ".", "debug", ")", "options", ".", "setdefault", "(", "'use_debugger'", ",", "self", ".", "debug", ")", "try", ":", "run_simple", "(", "host", ",", "port", ",", "self", ",", "*", "*", "options", ")", "finally", ":", "# reset the first request information if the development server", "# reset normally. This makes it possible to restart the server", "# without reloader and that stuff from an interactive shell.", "self", ".", "_got_first_request", "=", "False" ]
[ 781, 4 ]
[ 845, 43 ]
python
en
['en', 'en', 'en']
True
Flask.test_client
(self, use_cookies=True, **kwargs)
Creates a test client for this application. For information about unit testing head over to :ref:`testing`. Note that if you are testing for assertions or exceptions in your application code, you must set ``app.testing = True`` in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the :attr:`testing` attribute. For example:: app.testing = True client = app.test_client() The test client can be used in a ``with`` block to defer the closing down of the context until the end of the ``with`` block. This is useful if you want to access the context locals for testing:: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' Additionally, you may pass optional keyword arguments that will then be passed to the application's :attr:`test_client_class` constructor. For example:: from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....') See :class:`~flask.testing.FlaskClient` for more information. .. versionchanged:: 0.4 added support for ``with`` block usage for the client. .. versionadded:: 0.7 The `use_cookies` parameter was added as well as the ability to override the client to be used by setting the :attr:`test_client_class` attribute. .. versionchanged:: 0.11 Added `**kwargs` to support passing additional keyword arguments to the constructor of :attr:`test_client_class`.
Creates a test client for this application. For information about unit testing head over to :ref:`testing`.
def test_client(self, use_cookies=True, **kwargs): """Creates a test client for this application. For information about unit testing head over to :ref:`testing`. Note that if you are testing for assertions or exceptions in your application code, you must set ``app.testing = True`` in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the :attr:`testing` attribute. For example:: app.testing = True client = app.test_client() The test client can be used in a ``with`` block to defer the closing down of the context until the end of the ``with`` block. This is useful if you want to access the context locals for testing:: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' Additionally, you may pass optional keyword arguments that will then be passed to the application's :attr:`test_client_class` constructor. For example:: from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....') See :class:`~flask.testing.FlaskClient` for more information. .. versionchanged:: 0.4 added support for ``with`` block usage for the client. .. versionadded:: 0.7 The `use_cookies` parameter was added as well as the ability to override the client to be used by setting the :attr:`test_client_class` attribute. .. versionchanged:: 0.11 Added `**kwargs` to support passing additional keyword arguments to the constructor of :attr:`test_client_class`. """ cls = self.test_client_class if cls is None: from flask.testing import FlaskClient as cls return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)
[ "def", "test_client", "(", "self", ",", "use_cookies", "=", "True", ",", "*", "*", "kwargs", ")", ":", "cls", "=", "self", ".", "test_client_class", "if", "cls", "is", "None", ":", "from", "flask", ".", "testing", "import", "FlaskClient", "as", "cls", "return", "cls", "(", "self", ",", "self", ".", "response_class", ",", "use_cookies", "=", "use_cookies", ",", "*", "*", "kwargs", ")" ]
[ 847, 4 ]
[ 901, 80 ]
python
en
['en', 'en', 'en']
True
Flask.open_session
(self, request)
Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param request: an instance of :attr:`request_class`.
Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. Instead of overriding this method we recommend replacing the :class:`session_interface`.
def open_session(self, request): """Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param request: an instance of :attr:`request_class`. """ return self.session_interface.open_session(self, request)
[ "def", "open_session", "(", "self", ",", "request", ")", ":", "return", "self", ".", "session_interface", ".", "open_session", "(", "self", ",", "request", ")" ]
[ 903, 4 ]
[ 911, 65 ]
python
en
['en', 'en', 'en']
True
Flask.save_session
(self, session, response)
Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param session: the session to be saved (a :class:`~werkzeug.contrib.securecookie.SecureCookie` object) :param response: an instance of :attr:`response_class`
Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. Instead of overriding this method we recommend replacing the :class:`session_interface`.
def save_session(self, session, response): """Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. Instead of overriding this method we recommend replacing the :class:`session_interface`. :param session: the session to be saved (a :class:`~werkzeug.contrib.securecookie.SecureCookie` object) :param response: an instance of :attr:`response_class` """ return self.session_interface.save_session(self, session, response)
[ "def", "save_session", "(", "self", ",", "session", ",", "response", ")", ":", "return", "self", ".", "session_interface", ".", "save_session", "(", "self", ",", "session", ",", "response", ")" ]
[ 913, 4 ]
[ 923, 75 ]
python
en
['en', 'en', 'en']
True
Flask.make_null_session
(self)
Creates a new instance of a missing session. Instead of overriding this method we recommend replacing the :class:`session_interface`. .. versionadded:: 0.7
Creates a new instance of a missing session. Instead of overriding this method we recommend replacing the :class:`session_interface`.
def make_null_session(self): """Creates a new instance of a missing session. Instead of overriding this method we recommend replacing the :class:`session_interface`. .. versionadded:: 0.7 """ return self.session_interface.make_null_session(self)
[ "def", "make_null_session", "(", "self", ")", ":", "return", "self", ".", "session_interface", ".", "make_null_session", "(", "self", ")" ]
[ 925, 4 ]
[ 931, 61 ]
python
en
['en', 'en', 'en']
True
Flask.register_blueprint
(self, blueprint, **options)
Registers a blueprint on the application. .. versionadded:: 0.7
Registers a blueprint on the application.
def register_blueprint(self, blueprint, **options): """Registers a blueprint on the application. .. versionadded:: 0.7 """ first_registration = False if blueprint.name in self.blueprints: assert self.blueprints[blueprint.name] is blueprint, \ 'A blueprint\'s name collision occurred between %r and ' \ '%r. Both share the same name "%s". Blueprints that ' \ 'are created on the fly need unique names.' % \ (blueprint, self.blueprints[blueprint.name], blueprint.name) else: self.blueprints[blueprint.name] = blueprint self._blueprint_order.append(blueprint) first_registration = True blueprint.register(self, options, first_registration)
[ "def", "register_blueprint", "(", "self", ",", "blueprint", ",", "*", "*", "options", ")", ":", "first_registration", "=", "False", "if", "blueprint", ".", "name", "in", "self", ".", "blueprints", ":", "assert", "self", ".", "blueprints", "[", "blueprint", ".", "name", "]", "is", "blueprint", ",", "'A blueprint\\'s name collision occurred between %r and '", "'%r. Both share the same name \"%s\". Blueprints that '", "'are created on the fly need unique names.'", "%", "(", "blueprint", ",", "self", ".", "blueprints", "[", "blueprint", ".", "name", "]", ",", "blueprint", ".", "name", ")", "else", ":", "self", ".", "blueprints", "[", "blueprint", ".", "name", "]", "=", "blueprint", "self", ".", "_blueprint_order", ".", "append", "(", "blueprint", ")", "first_registration", "=", "True", "blueprint", ".", "register", "(", "self", ",", "options", ",", "first_registration", ")" ]
[ 934, 4 ]
[ 950, 61 ]
python
en
['en', 'en', 'en']
True
Flask.iter_blueprints
(self)
Iterates over all blueprints by the order they were registered. .. versionadded:: 0.11
Iterates over all blueprints by the order they were registered.
def iter_blueprints(self): """Iterates over all blueprints by the order they were registered. .. versionadded:: 0.11 """ return iter(self._blueprint_order)
[ "def", "iter_blueprints", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_blueprint_order", ")" ]
[ 952, 4 ]
[ 957, 42 ]
python
en
['en', 'en', 'en']
True
Flask.add_url_rule
(self, rule, endpoint=None, view_func=None, **options)
Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index Internally :meth:`route` invokes :meth:`add_url_rule` so if you want to customize the behavior via subclassing you only need to change this method. For more information refer to :ref:`url-route-registrations`. .. versionchanged:: 0.2 `view_func` parameter added. .. versionchanged:: 0.6 ``OPTIONS`` is added automatically as method. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling.
Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint.
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index Internally :meth:`route` invokes :meth:`add_url_rule` so if you want to customize the behavior via subclassing you only need to change this method. For more information refer to :ref:`url-route-registrations`. .. versionchanged:: 0.2 `view_func` parameter added. .. versionchanged:: 0.6 ``OPTIONS`` is added automatically as method. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options['endpoint'] = endpoint methods = options.pop('methods', None) # if the methods are not given and the view_func object knows its # methods we can use that instead. If neither exists, we go with # a tuple of only ``GET`` as default. if methods is None: methods = getattr(view_func, 'methods', None) or ('GET',) if isinstance(methods, string_types): raise TypeError('Allowed methods have to be iterables of strings, ' 'for example: @app.route(..., methods=["POST"])') methods = set(item.upper() for item in methods) # Methods that should always be added required_methods = set(getattr(view_func, 'required_methods', ())) # starting with Flask 0.8 the view_func object can disable and # force-enable the automatic options handling. provide_automatic_options = getattr(view_func, 'provide_automatic_options', None) if provide_automatic_options is None: if 'OPTIONS' not in methods: provide_automatic_options = True required_methods.add('OPTIONS') else: provide_automatic_options = False # Add the required methods now. methods |= required_methods rule = self.url_rule_class(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options self.url_map.add(rule) if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError('View function mapping is overwriting an ' 'existing endpoint function: %s' % endpoint) self.view_functions[endpoint] = view_func
[ "def", "add_url_rule", "(", "self", ",", "rule", ",", "endpoint", "=", "None", ",", "view_func", "=", "None", ",", "*", "*", "options", ")", ":", "if", "endpoint", "is", "None", ":", "endpoint", "=", "_endpoint_from_view_func", "(", "view_func", ")", "options", "[", "'endpoint'", "]", "=", "endpoint", "methods", "=", "options", ".", "pop", "(", "'methods'", ",", "None", ")", "# if the methods are not given and the view_func object knows its", "# methods we can use that instead. If neither exists, we go with", "# a tuple of only ``GET`` as default.", "if", "methods", "is", "None", ":", "methods", "=", "getattr", "(", "view_func", ",", "'methods'", ",", "None", ")", "or", "(", "'GET'", ",", ")", "if", "isinstance", "(", "methods", ",", "string_types", ")", ":", "raise", "TypeError", "(", "'Allowed methods have to be iterables of strings, '", "'for example: @app.route(..., methods=[\"POST\"])'", ")", "methods", "=", "set", "(", "item", ".", "upper", "(", ")", "for", "item", "in", "methods", ")", "# Methods that should always be added", "required_methods", "=", "set", "(", "getattr", "(", "view_func", ",", "'required_methods'", ",", "(", ")", ")", ")", "# starting with Flask 0.8 the view_func object can disable and", "# force-enable the automatic options handling.", "provide_automatic_options", "=", "getattr", "(", "view_func", ",", "'provide_automatic_options'", ",", "None", ")", "if", "provide_automatic_options", "is", "None", ":", "if", "'OPTIONS'", "not", "in", "methods", ":", "provide_automatic_options", "=", "True", "required_methods", ".", "add", "(", "'OPTIONS'", ")", "else", ":", "provide_automatic_options", "=", "False", "# Add the required methods now.", "methods", "|=", "required_methods", "rule", "=", "self", ".", "url_rule_class", "(", "rule", ",", "methods", "=", "methods", ",", "*", "*", "options", ")", "rule", ".", "provide_automatic_options", "=", "provide_automatic_options", "self", ".", "url_map", ".", "add", "(", "rule", ")", "if", "view_func", "is", "not", "None", ":", "old_func", "=", "self", ".", "view_functions", ".", "get", "(", "endpoint", ")", "if", "old_func", "is", "not", "None", "and", "old_func", "!=", "view_func", ":", "raise", "AssertionError", "(", "'View function mapping is overwriting an '", "'existing endpoint function: %s'", "%", "endpoint", ")", "self", ".", "view_functions", "[", "endpoint", "]", "=", "view_func" ]
[ 960, 4 ]
[ 1051, 53 ]
python
en
['en', 'en', 'en']
True
Flask.route
(self, rule, **options)
A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' For more information refer to :ref:`url-route-registrations`. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling.
A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage::
def route(self, rule, **options): """A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' For more information refer to :ref:`url-route-registrations`. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
[ "def", "route", "(", "self", ",", "rule", ",", "*", "*", "options", ")", ":", "def", "decorator", "(", "f", ")", ":", "endpoint", "=", "options", ".", "pop", "(", "'endpoint'", ",", "None", ")", "self", ".", "add_url_rule", "(", "rule", ",", "endpoint", ",", "f", ",", "*", "*", "options", ")", "return", "f", "return", "decorator" ]
[ 1053, 4 ]
[ 1081, 24 ]
python
en
['en', 'en', 'en']
True
Flask.endpoint
(self, endpoint)
A decorator to register a function as an endpoint. Example:: @app.endpoint('example.endpoint') def example(): return "example" :param endpoint: the name of the endpoint
A decorator to register a function as an endpoint. Example::
def endpoint(self, endpoint): """A decorator to register a function as an endpoint. Example:: @app.endpoint('example.endpoint') def example(): return "example" :param endpoint: the name of the endpoint """ def decorator(f): self.view_functions[endpoint] = f return f return decorator
[ "def", "endpoint", "(", "self", ",", "endpoint", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "view_functions", "[", "endpoint", "]", "=", "f", "return", "f", "return", "decorator" ]
[ 1084, 4 ]
[ 1097, 24 ]
python
en
['en', 'en', 'en']
True
Flask._get_exc_class_and_code
(exc_class_or_code)
Ensure that we register only exceptions as handler keys
Ensure that we register only exceptions as handler keys
def _get_exc_class_and_code(exc_class_or_code): """Ensure that we register only exceptions as handler keys""" if isinstance(exc_class_or_code, integer_types): exc_class = default_exceptions[exc_class_or_code] else: exc_class = exc_class_or_code assert issubclass(exc_class, Exception) if issubclass(exc_class, HTTPException): return exc_class, exc_class.code else: return exc_class, None
[ "def", "_get_exc_class_and_code", "(", "exc_class_or_code", ")", ":", "if", "isinstance", "(", "exc_class_or_code", ",", "integer_types", ")", ":", "exc_class", "=", "default_exceptions", "[", "exc_class_or_code", "]", "else", ":", "exc_class", "=", "exc_class_or_code", "assert", "issubclass", "(", "exc_class", ",", "Exception", ")", "if", "issubclass", "(", "exc_class", ",", "HTTPException", ")", ":", "return", "exc_class", ",", "exc_class", ".", "code", "else", ":", "return", "exc_class", ",", "None" ]
[ 1100, 4 ]
[ 1112, 34 ]
python
en
['en', 'en', 'en']
True
Flask.errorhandler
(self, code_or_exception)
A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 You can also register a function as error handler without using the :meth:`errorhandler` decorator. The following example is equivalent to the one above:: def page_not_found(error): return 'This page does not exist', 404 app.error_handler_spec[None][404] = page_not_found Setting error handlers via assignments to :attr:`error_handler_spec` however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types. The first ``None`` refers to the active blueprint. If the error handler should be application wide ``None`` shall be used. .. versionadded:: 0.7 Use :meth:`register_error_handler` instead of modifying :attr:`error_handler_spec` directly, for application wide error handlers. .. versionadded:: 0.7 One can now additionally also register custom exception types that do not necessarily have to be a subclass of the :class:`~werkzeug.exceptions.HTTPException` class. :param code_or_exception: the code as integer for the handler, or an arbitrary exception
A decorator that is used to register a function given an error code. Example::
def errorhandler(self, code_or_exception): """A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 You can also register a function as error handler without using the :meth:`errorhandler` decorator. The following example is equivalent to the one above:: def page_not_found(error): return 'This page does not exist', 404 app.error_handler_spec[None][404] = page_not_found Setting error handlers via assignments to :attr:`error_handler_spec` however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types. The first ``None`` refers to the active blueprint. If the error handler should be application wide ``None`` shall be used. .. versionadded:: 0.7 Use :meth:`register_error_handler` instead of modifying :attr:`error_handler_spec` directly, for application wide error handlers. .. versionadded:: 0.7 One can now additionally also register custom exception types that do not necessarily have to be a subclass of the :class:`~werkzeug.exceptions.HTTPException` class. :param code_or_exception: the code as integer for the handler, or an arbitrary exception """ def decorator(f): self._register_error_handler(None, code_or_exception, f) return f return decorator
[ "def", "errorhandler", "(", "self", ",", "code_or_exception", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "_register_error_handler", "(", "None", ",", "code_or_exception", ",", "f", ")", "return", "f", "return", "decorator" ]
[ 1115, 4 ]
[ 1160, 24 ]
python
en
['en', 'en', 'en']
True
Flask.register_error_handler
(self, code_or_exception, f)
Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage. .. versionadded:: 0.7
Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage.
def register_error_handler(self, code_or_exception, f): """Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage. .. versionadded:: 0.7 """ self._register_error_handler(None, code_or_exception, f)
[ "def", "register_error_handler", "(", "self", ",", "code_or_exception", ",", "f", ")", ":", "self", ".", "_register_error_handler", "(", "None", ",", "code_or_exception", ",", "f", ")" ]
[ 1162, 4 ]
[ 1169, 64 ]
python
en
['en', 'de', 'en']
True
Flask._register_error_handler
(self, key, code_or_exception, f)
:type key: None|str :type code_or_exception: int|T<=Exception :type f: callable
:type key: None|str :type code_or_exception: int|T<=Exception :type f: callable
def _register_error_handler(self, key, code_or_exception, f): """ :type key: None|str :type code_or_exception: int|T<=Exception :type f: callable """ if isinstance(code_or_exception, HTTPException): # old broken behavior raise ValueError( 'Tried to register a handler for an exception instance {0!r}. ' 'Handlers can only be registered for exception classes or HTTP error codes.' .format(code_or_exception)) exc_class, code = self._get_exc_class_and_code(code_or_exception) handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {}) handlers[exc_class] = f
[ "def", "_register_error_handler", "(", "self", ",", "key", ",", "code_or_exception", ",", "f", ")", ":", "if", "isinstance", "(", "code_or_exception", ",", "HTTPException", ")", ":", "# old broken behavior", "raise", "ValueError", "(", "'Tried to register a handler for an exception instance {0!r}. '", "'Handlers can only be registered for exception classes or HTTP error codes.'", ".", "format", "(", "code_or_exception", ")", ")", "exc_class", ",", "code", "=", "self", ".", "_get_exc_class_and_code", "(", "code_or_exception", ")", "handlers", "=", "self", ".", "error_handler_spec", ".", "setdefault", "(", "key", ",", "{", "}", ")", ".", "setdefault", "(", "code", ",", "{", "}", ")", "handlers", "[", "exc_class", "]", "=", "f" ]
[ 1172, 4 ]
[ 1187, 31 ]
python
en
['en', 'error', 'th']
False
Flask.template_filter
(self, name=None)
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :param name: the optional name of the filter, otherwise the function name will be used.
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example::
def template_filter(self, name=None): """A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f): self.add_template_filter(f, name=name) return f return decorator
[ "def", "template_filter", "(", "self", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "add_template_filter", "(", "f", ",", "name", "=", "name", ")", "return", "f", "return", "decorator" ]
[ 1190, 4 ]
[ 1205, 24 ]
python
en
['en', 'en', 'en']
True
Flask.add_template_filter
(self, f, name=None)
Register a custom template filter. Works exactly like the :meth:`template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used.
Register a custom template filter. Works exactly like the :meth:`template_filter` decorator.
def add_template_filter(self, f, name=None): """Register a custom template filter. Works exactly like the :meth:`template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used. """ self.jinja_env.filters[name or f.__name__] = f
[ "def", "add_template_filter", "(", "self", ",", "f", ",", "name", "=", "None", ")", ":", "self", ".", "jinja_env", ".", "filters", "[", "name", "or", "f", ".", "__name__", "]", "=", "f" ]
[ 1208, 4 ]
[ 1215, 54 ]
python
en
['en', 'en', 'en']
True
Flask.template_test
(self, name=None)
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:: @app.template_test() def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used.
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example::
def template_test(self, name=None): """A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:: @app.template_test() def is_prime(n): if n == 2: return True for i in range(2, int(math.ceil(math.sqrt(n))) + 1): if n % i == 0: return False return True .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ def decorator(f): self.add_template_test(f, name=name) return f return decorator
[ "def", "template_test", "(", "self", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "add_template_test", "(", "f", ",", "name", "=", "name", ")", "return", "f", "return", "decorator" ]
[ 1218, 4 ]
[ 1240, 24 ]
python
en
['en', 'en', 'en']
True
Flask.add_template_test
(self, f, name=None)
Register a custom template test. Works exactly like the :meth:`template_test` decorator. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used.
Register a custom template test. Works exactly like the :meth:`template_test` decorator.
def add_template_test(self, f, name=None): """Register a custom template test. Works exactly like the :meth:`template_test` decorator. .. versionadded:: 0.10 :param name: the optional name of the test, otherwise the function name will be used. """ self.jinja_env.tests[name or f.__name__] = f
[ "def", "add_template_test", "(", "self", ",", "f", ",", "name", "=", "None", ")", ":", "self", ".", "jinja_env", ".", "tests", "[", "name", "or", "f", ".", "__name__", "]", "=", "f" ]
[ 1243, 4 ]
[ 1252, 52 ]
python
en
['en', 'en', 'en']
True
Flask.template_global
(self, name=None)
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: @app.template_global() def double(n): return 2 * n .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used.
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example::
def template_global(self, name=None): """A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: @app.template_global() def double(n): return 2 * n .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used. """ def decorator(f): self.add_template_global(f, name=name) return f return decorator
[ "def", "template_global", "(", "self", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "add_template_global", "(", "f", ",", "name", "=", "name", ")", "return", "f", "return", "decorator" ]
[ 1255, 4 ]
[ 1272, 24 ]
python
en
['en', 'en', 'en']
True
Flask.add_template_global
(self, f, name=None)
Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used.
Register a custom template global function. Works exactly like the :meth:`template_global` decorator.
def add_template_global(self, f, name=None): """Register a custom template global function. Works exactly like the :meth:`template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global function, otherwise the function name will be used. """ self.jinja_env.globals[name or f.__name__] = f
[ "def", "add_template_global", "(", "self", ",", "f", ",", "name", "=", "None", ")", ":", "self", ".", "jinja_env", ".", "globals", "[", "name", "or", "f", ".", "__name__", "]", "=", "f" ]
[ 1275, 4 ]
[ 1284, 54 ]
python
en
['en', 'en', 'en']
True
Flask.before_request
(self, f)
Registers a function to run before each request. The function will be called without any arguments. If the function returns a non-None value, it's handled as if it was the return value from the view and further request handling is stopped.
Registers a function to run before each request.
def before_request(self, f): """Registers a function to run before each request. The function will be called without any arguments. If the function returns a non-None value, it's handled as if it was the return value from the view and further request handling is stopped. """ self.before_request_funcs.setdefault(None, []).append(f) return f
[ "def", "before_request", "(", "self", ",", "f", ")", ":", "self", ".", "before_request_funcs", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", "return", "f" ]
[ 1287, 4 ]
[ 1296, 16 ]
python
en
['en', 'en', 'en']
True
Flask.before_first_request
(self, f)
Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. .. versionadded:: 0.8
Registers a function to be run before the first request to this instance of the application.
def before_first_request(self, f): """Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. .. versionadded:: 0.8 """ self.before_first_request_funcs.append(f) return f
[ "def", "before_first_request", "(", "self", ",", "f", ")", ":", "self", ".", "before_first_request_funcs", ".", "append", "(", "f", ")", "return", "f" ]
[ 1299, 4 ]
[ 1309, 16 ]
python
en
['en', 'en', 'en']
True
Flask.after_request
(self, f)
Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred.
Register a function to be run after each request.
def after_request(self, f): """Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred. """ self.after_request_funcs.setdefault(None, []).append(f) return f
[ "def", "after_request", "(", "self", ",", "f", ")", ":", "self", ".", "after_request_funcs", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", "return", "f" ]
[ 1312, 4 ]
[ 1323, 16 ]
python
en
['en', 'en', 'en']
True
Flask.teardown_request
(self, f)
Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of a exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.
def teardown_request(self, f): """Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of a exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. """ self.teardown_request_funcs.setdefault(None, []).append(f) return f
[ "def", "teardown_request", "(", "self", ",", "f", ")", ":", "self", ".", "teardown_request_funcs", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", "return", "f" ]
[ 1326, 4 ]
[ 1362, 16 ]
python
en
['en', 'en', 'en']
True
Flask.teardown_appcontext
(self, f)
Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example:: ctx = app.app_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. versionadded:: 0.9
Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.
def teardown_appcontext(self, f): """Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example:: ctx = app.app_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. versionadded:: 0.9 """ self.teardown_appcontext_funcs.append(f) return f
[ "def", "teardown_appcontext", "(", "self", ",", "f", ")", ":", "self", ".", "teardown_appcontext_funcs", ".", "append", "(", "f", ")", "return", "f" ]
[ 1365, 4 ]
[ 1393, 16 ]
python
en
['en', 'en', 'en']
True
Flask.context_processor
(self, f)
Registers a template context processor function.
Registers a template context processor function.
def context_processor(self, f): """Registers a template context processor function.""" self.template_context_processors[None].append(f) return f
[ "def", "context_processor", "(", "self", ",", "f", ")", ":", "self", ".", "template_context_processors", "[", "None", "]", ".", "append", "(", "f", ")", "return", "f" ]
[ 1396, 4 ]
[ 1399, 16 ]
python
en
['en', 'en', 'en']
True
Flask.shell_context_processor
(self, f)
Registers a shell context processor function. .. versionadded:: 0.11
Registers a shell context processor function.
def shell_context_processor(self, f): """Registers a shell context processor function. .. versionadded:: 0.11 """ self.shell_context_processors.append(f) return f
[ "def", "shell_context_processor", "(", "self", ",", "f", ")", ":", "self", ".", "shell_context_processors", ".", "append", "(", "f", ")", "return", "f" ]
[ 1402, 4 ]
[ 1408, 16 ]
python
en
['en', 'en', 'en']
True
Flask.url_value_preprocessor
(self, f)
Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided.
Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided.
def url_value_preprocessor(self, f): """Registers a function as URL value preprocessor for all view functions of the application. It's called before the view functions are called and can modify the url values provided. """ self.url_value_preprocessors.setdefault(None, []).append(f) return f
[ "def", "url_value_preprocessor", "(", "self", ",", "f", ")", ":", "self", ".", "url_value_preprocessors", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", "return", "f" ]
[ 1411, 4 ]
[ 1417, 16 ]
python
en
['en', 'en', 'en']
True
Flask.url_defaults
(self, f)
Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place.
Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place.
def url_defaults(self, f): """Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place. """ self.url_default_functions.setdefault(None, []).append(f) return f
[ "def", "url_defaults", "(", "self", ",", "f", ")", ":", "self", ".", "url_default_functions", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", "return", "f" ]
[ 1420, 4 ]
[ 1426, 16 ]
python
en
['en', 'en', 'en']
True
Flask._find_error_handler
(self, e)
Finds a registered error handler for the request’s blueprint. Otherwise falls back to the app, returns None if not a suitable handler is found.
Finds a registered error handler for the request’s blueprint. Otherwise falls back to the app, returns None if not a suitable handler is found.
def _find_error_handler(self, e): """Finds a registered error handler for the request’s blueprint. Otherwise falls back to the app, returns None if not a suitable handler is found. """ exc_class, code = self._get_exc_class_and_code(type(e)) def find_handler(handler_map): if not handler_map: return for cls in exc_class.__mro__: handler = handler_map.get(cls) if handler is not None: # cache for next time exc_class is raised handler_map[exc_class] = handler return handler # try blueprint handlers handler = find_handler(self.error_handler_spec .get(request.blueprint, {}) .get(code)) if handler is not None: return handler # fall back to app handlers return find_handler(self.error_handler_spec[None].get(code))
[ "def", "_find_error_handler", "(", "self", ",", "e", ")", ":", "exc_class", ",", "code", "=", "self", ".", "_get_exc_class_and_code", "(", "type", "(", "e", ")", ")", "def", "find_handler", "(", "handler_map", ")", ":", "if", "not", "handler_map", ":", "return", "for", "cls", "in", "exc_class", ".", "__mro__", ":", "handler", "=", "handler_map", ".", "get", "(", "cls", ")", "if", "handler", "is", "not", "None", ":", "# cache for next time exc_class is raised", "handler_map", "[", "exc_class", "]", "=", "handler", "return", "handler", "# try blueprint handlers", "handler", "=", "find_handler", "(", "self", ".", "error_handler_spec", ".", "get", "(", "request", ".", "blueprint", ",", "{", "}", ")", ".", "get", "(", "code", ")", ")", "if", "handler", "is", "not", "None", ":", "return", "handler", "# fall back to app handlers", "return", "find_handler", "(", "self", ".", "error_handler_spec", "[", "None", "]", ".", "get", "(", "code", ")", ")" ]
[ 1428, 4 ]
[ 1453, 68 ]
python
en
['en', 'da', 'en']
True
Flask.handle_http_exception
(self, e)
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
def handle_http_exception(self, e): """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3 """ # Proxy exceptions don't have error codes. We want to always return # those unchanged as errors if e.code is None: return e handler = self._find_error_handler(e) if handler is None: return e return handler(e)
[ "def", "handle_http_exception", "(", "self", ",", "e", ")", ":", "# Proxy exceptions don't have error codes. We want to always return", "# those unchanged as errors", "if", "e", ".", "code", "is", "None", ":", "return", "e", "handler", "=", "self", ".", "_find_error_handler", "(", "e", ")", "if", "handler", "is", "None", ":", "return", "e", "return", "handler", "(", "e", ")" ]
[ 1455, 4 ]
[ 1470, 25 ]
python
en
['en', 'en', 'en']
True
Flask.trap_http_exception
(self, e)
Checks if an HTTP exception should be trapped or not. By default this will return ``False`` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. This is called for all HTTP exceptions raised by a view function. If it returns ``True`` for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions. .. versionadded:: 0.8
Checks if an HTTP exception should be trapped or not. By default this will return ``False`` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
def trap_http_exception(self, e): """Checks if an HTTP exception should be trapped or not. By default this will return ``False`` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. This is called for all HTTP exceptions raised by a view function. If it returns ``True`` for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions. .. versionadded:: 0.8 """ if self.config['TRAP_HTTP_EXCEPTIONS']: return True if self.config['TRAP_BAD_REQUEST_ERRORS']: return isinstance(e, BadRequest) return False
[ "def", "trap_http_exception", "(", "self", ",", "e", ")", ":", "if", "self", ".", "config", "[", "'TRAP_HTTP_EXCEPTIONS'", "]", ":", "return", "True", "if", "self", ".", "config", "[", "'TRAP_BAD_REQUEST_ERRORS'", "]", ":", "return", "isinstance", "(", "e", ",", "BadRequest", ")", "return", "False" ]
[ 1472, 4 ]
[ 1490, 20 ]
python
en
['en', 'en', 'en']
True
Flask.handle_user_exception
(self, e)
This method is called whenever an exception occurs that should be handled. A special case are :class:`~werkzeug.exception.HTTPException`\s which are forwarded by this function to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback. .. versionadded:: 0.7
This method is called whenever an exception occurs that should be handled. A special case are :class:`~werkzeug.exception.HTTPException`\s which are forwarded by this function to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback.
def handle_user_exception(self, e): """This method is called whenever an exception occurs that should be handled. A special case are :class:`~werkzeug.exception.HTTPException`\s which are forwarded by this function to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback. .. versionadded:: 0.7 """ exc_type, exc_value, tb = sys.exc_info() assert exc_value is e # ensure not to trash sys.exc_info() at that point in case someone # wants the traceback preserved in handle_http_exception. Of course # we cannot prevent users from trashing it themselves in a custom # trap_http_exception method so that's their fault then. if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(e) handler = self._find_error_handler(e) if handler is None: reraise(exc_type, exc_value, tb) return handler(e)
[ "def", "handle_user_exception", "(", "self", ",", "e", ")", ":", "exc_type", ",", "exc_value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "assert", "exc_value", "is", "e", "# ensure not to trash sys.exc_info() at that point in case someone", "# wants the traceback preserved in handle_http_exception. Of course", "# we cannot prevent users from trashing it themselves in a custom", "# trap_http_exception method so that's their fault then.", "if", "isinstance", "(", "e", ",", "HTTPException", ")", "and", "not", "self", ".", "trap_http_exception", "(", "e", ")", ":", "return", "self", ".", "handle_http_exception", "(", "e", ")", "handler", "=", "self", ".", "_find_error_handler", "(", "e", ")", "if", "handler", "is", "None", ":", "reraise", "(", "exc_type", ",", "exc_value", ",", "tb", ")", "return", "handler", "(", "e", ")" ]
[ 1492, 4 ]
[ 1517, 25 ]
python
en
['en', 'en', 'en']
True
Flask.handle_exception
(self, e)
Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed. .. versionadded:: 0.3
Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed.
def handle_exception(self, e): """Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed. .. versionadded:: 0.3 """ exc_type, exc_value, tb = sys.exc_info() got_request_exception.send(self, exception=e) handler = self._find_error_handler(InternalServerError()) if self.propagate_exceptions: # if we want to repropagate the exception, we can attempt to # raise it with the whole traceback in case we can do that # (the function was actually called from the except part) # otherwise, we just raise the error again if exc_value is e: reraise(exc_type, exc_value, tb) else: raise e self.log_exception((exc_type, exc_value, tb)) if handler is None: return InternalServerError() return self.finalize_request(handler(e), from_error_handler=True)
[ "def", "handle_exception", "(", "self", ",", "e", ")", ":", "exc_type", ",", "exc_value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "got_request_exception", ".", "send", "(", "self", ",", "exception", "=", "e", ")", "handler", "=", "self", ".", "_find_error_handler", "(", "InternalServerError", "(", ")", ")", "if", "self", ".", "propagate_exceptions", ":", "# if we want to repropagate the exception, we can attempt to", "# raise it with the whole traceback in case we can do that", "# (the function was actually called from the except part)", "# otherwise, we just raise the error again", "if", "exc_value", "is", "e", ":", "reraise", "(", "exc_type", ",", "exc_value", ",", "tb", ")", "else", ":", "raise", "e", "self", ".", "log_exception", "(", "(", "exc_type", ",", "exc_value", ",", "tb", ")", ")", "if", "handler", "is", "None", ":", "return", "InternalServerError", "(", ")", "return", "self", ".", "finalize_request", "(", "handler", "(", "e", ")", ",", "from_error_handler", "=", "True", ")" ]
[ 1519, 4 ]
[ 1546, 73 ]
python
en
['en', 'en', 'en']
True
Flask.log_exception
(self, exc_info)
Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8
Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`.
def log_exception(self, exc_info): """Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8 """ self.logger.error('Exception on %s [%s]' % ( request.path, request.method ), exc_info=exc_info)
[ "def", "log_exception", "(", "self", ",", "exc_info", ")", ":", "self", ".", "logger", ".", "error", "(", "'Exception on %s [%s]'", "%", "(", "request", ".", "path", ",", "request", ".", "method", ")", ",", "exc_info", "=", "exc_info", ")" ]
[ 1548, 4 ]
[ 1559, 29 ]
python
en
['en', 'en', 'en']
True
Flask.raise_routing_exception
(self, request)
Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising a different error instead to help debug situations. :internal:
Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising a different error instead to help debug situations.
def raise_routing_exception(self, request): """Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising a different error instead to help debug situations. :internal: """ if not self.debug \ or not isinstance(request.routing_exception, RequestRedirect) \ or request.method in ('GET', 'HEAD', 'OPTIONS'): raise request.routing_exception from .debughelpers import FormDataRoutingRedirect raise FormDataRoutingRedirect(request)
[ "def", "raise_routing_exception", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "debug", "or", "not", "isinstance", "(", "request", ".", "routing_exception", ",", "RequestRedirect", ")", "or", "request", ".", "method", "in", "(", "'GET'", ",", "'HEAD'", ",", "'OPTIONS'", ")", ":", "raise", "request", ".", "routing_exception", "from", ".", "debughelpers", "import", "FormDataRoutingRedirect", "raise", "FormDataRoutingRedirect", "(", "request", ")" ]
[ 1561, 4 ]
[ 1575, 46 ]
python
en
['en', 'en', 'en']
True
Flask.dispatch_request
(self)
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This no longer does the exception handling, this code was moved to the new :meth:`full_dispatch_request`.
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`.
def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This no longer does the exception handling, this code was moved to the new :meth:`full_dispatch_request`. """ req = _request_ctx_stack.top.request if req.routing_exception is not None: self.raise_routing_exception(req) rule = req.url_rule # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if getattr(rule, 'provide_automatic_options', False) \ and req.method == 'OPTIONS': return self.make_default_options_response() # otherwise dispatch to the handler for that endpoint return self.view_functions[rule.endpoint](**req.view_args)
[ "def", "dispatch_request", "(", "self", ")", ":", "req", "=", "_request_ctx_stack", ".", "top", ".", "request", "if", "req", ".", "routing_exception", "is", "not", "None", ":", "self", ".", "raise_routing_exception", "(", "req", ")", "rule", "=", "req", ".", "url_rule", "# if we provide automatic options for this URL and the", "# request came with the OPTIONS method, reply automatically", "if", "getattr", "(", "rule", ",", "'provide_automatic_options'", ",", "False", ")", "and", "req", ".", "method", "==", "'OPTIONS'", ":", "return", "self", ".", "make_default_options_response", "(", ")", "# otherwise dispatch to the handler for that endpoint", "return", "self", ".", "view_functions", "[", "rule", ".", "endpoint", "]", "(", "*", "*", "req", ".", "view_args", ")" ]
[ 1577, 4 ]
[ 1597, 66 ]
python
en
['en', 'en', 'en']
True
Flask.full_dispatch_request
(self)
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
def full_dispatch_request(self): """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ self.try_trigger_before_first_request_functions() try: request_started.send(self) rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() except Exception as e: rv = self.handle_user_exception(e) return self.finalize_request(rv)
[ "def", "full_dispatch_request", "(", "self", ")", ":", "self", ".", "try_trigger_before_first_request_functions", "(", ")", "try", ":", "request_started", ".", "send", "(", "self", ")", "rv", "=", "self", ".", "preprocess_request", "(", ")", "if", "rv", "is", "None", ":", "rv", "=", "self", ".", "dispatch_request", "(", ")", "except", "Exception", "as", "e", ":", "rv", "=", "self", ".", "handle_user_exception", "(", "e", ")", "return", "self", ".", "finalize_request", "(", "rv", ")" ]
[ 1599, 4 ]
[ 1614, 40 ]
python
en
['en', 'en', 'en']
True
Flask.finalize_request
(self, rv, from_error_handler=False)
Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers. Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the `from_error_handler` flag. If enabled, failures in response processing will be logged and otherwise ignored. :internal:
Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers.
def finalize_request(self, rv, from_error_handler=False): """Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers. Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the `from_error_handler` flag. If enabled, failures in response processing will be logged and otherwise ignored. :internal: """ response = self.make_response(rv) try: response = self.process_response(response) request_finished.send(self, response=response) except Exception: if not from_error_handler: raise self.logger.exception('Request finalizing failed with an ' 'error while handling an error') return response
[ "def", "finalize_request", "(", "self", ",", "rv", ",", "from_error_handler", "=", "False", ")", ":", "response", "=", "self", ".", "make_response", "(", "rv", ")", "try", ":", "response", "=", "self", ".", "process_response", "(", "response", ")", "request_finished", ".", "send", "(", "self", ",", "response", "=", "response", ")", "except", "Exception", ":", "if", "not", "from_error_handler", ":", "raise", "self", ".", "logger", ".", "exception", "(", "'Request finalizing failed with an '", "'error while handling an error'", ")", "return", "response" ]
[ 1616, 4 ]
[ 1638, 23 ]
python
en
['en', 'en', 'en']
True
Flask.try_trigger_before_first_request_functions
(self)
Called before each request and will ensure that it triggers the :attr:`before_first_request_funcs` and only exactly once per application instance (which means process usually). :internal:
Called before each request and will ensure that it triggers the :attr:`before_first_request_funcs` and only exactly once per application instance (which means process usually).
def try_trigger_before_first_request_functions(self): """Called before each request and will ensure that it triggers the :attr:`before_first_request_funcs` and only exactly once per application instance (which means process usually). :internal: """ if self._got_first_request: return with self._before_request_lock: if self._got_first_request: return for func in self.before_first_request_funcs: func() self._got_first_request = True
[ "def", "try_trigger_before_first_request_functions", "(", "self", ")", ":", "if", "self", ".", "_got_first_request", ":", "return", "with", "self", ".", "_before_request_lock", ":", "if", "self", ".", "_got_first_request", ":", "return", "for", "func", "in", "self", ".", "before_first_request_funcs", ":", "func", "(", ")", "self", ".", "_got_first_request", "=", "True" ]
[ 1640, 4 ]
[ 1654, 42 ]
python
en
['en', 'en', 'en']
True
Flask.make_default_options_response
(self)
This method is called to create the default ``OPTIONS`` response. This can be changed through subclassing to change the default behavior of ``OPTIONS`` responses. .. versionadded:: 0.7
This method is called to create the default ``OPTIONS`` response. This can be changed through subclassing to change the default behavior of ``OPTIONS`` responses.
def make_default_options_response(self): """This method is called to create the default ``OPTIONS`` response. This can be changed through subclassing to change the default behavior of ``OPTIONS`` responses. .. versionadded:: 0.7 """ adapter = _request_ctx_stack.top.url_adapter if hasattr(adapter, 'allowed_methods'): methods = adapter.allowed_methods() else: # fallback for Werkzeug < 0.7 methods = [] try: adapter.match(method='--') except MethodNotAllowed as e: methods = e.valid_methods except HTTPException as e: pass rv = self.response_class() rv.allow.update(methods) return rv
[ "def", "make_default_options_response", "(", "self", ")", ":", "adapter", "=", "_request_ctx_stack", ".", "top", ".", "url_adapter", "if", "hasattr", "(", "adapter", ",", "'allowed_methods'", ")", ":", "methods", "=", "adapter", ".", "allowed_methods", "(", ")", "else", ":", "# fallback for Werkzeug < 0.7", "methods", "=", "[", "]", "try", ":", "adapter", ".", "match", "(", "method", "=", "'--'", ")", "except", "MethodNotAllowed", "as", "e", ":", "methods", "=", "e", ".", "valid_methods", "except", "HTTPException", "as", "e", ":", "pass", "rv", "=", "self", ".", "response_class", "(", ")", "rv", ".", "allow", ".", "update", "(", "methods", ")", "return", "rv" ]
[ 1656, 4 ]
[ 1677, 17 ]
python
en
['en', 'en', 'en']
True
Flask.should_ignore_error
(self, error)
This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns ``True`` then the teardown handlers will not be passed the error. .. versionadded:: 0.10
This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns ``True`` then the teardown handlers will not be passed the error.
def should_ignore_error(self, error): """This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns ``True`` then the teardown handlers will not be passed the error. .. versionadded:: 0.10 """ return False
[ "def", "should_ignore_error", "(", "self", ",", "error", ")", ":", "return", "False" ]
[ 1679, 4 ]
[ 1687, 20 ]
python
en
['en', 'en', 'en']
True
Flask.make_response
(self, rv)
Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`. The following types are allowed for `rv`: .. tabularcolumns:: |p{3.5cm}|p{9.5cm}| ======================= =========================================== :attr:`response_class` the object is returned unchanged :class:`str` a response object is created with the string as body :class:`unicode` a response object is created with the string encoded to utf-8 as body a WSGI function the function is called as WSGI application and buffered as response object :class:`tuple` A tuple in the form ``(response, status, headers)`` or ``(response, headers)`` where `response` is any of the types defined here, `status` is a string or an integer and `headers` is a list or a dictionary with header values. ======================= =========================================== :param rv: the return value from the view function .. versionchanged:: 0.9 Previously a tuple was interpreted as the arguments for the response object.
Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`.
def make_response(self, rv): """Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`. The following types are allowed for `rv`: .. tabularcolumns:: |p{3.5cm}|p{9.5cm}| ======================= =========================================== :attr:`response_class` the object is returned unchanged :class:`str` a response object is created with the string as body :class:`unicode` a response object is created with the string encoded to utf-8 as body a WSGI function the function is called as WSGI application and buffered as response object :class:`tuple` A tuple in the form ``(response, status, headers)`` or ``(response, headers)`` where `response` is any of the types defined here, `status` is a string or an integer and `headers` is a list or a dictionary with header values. ======================= =========================================== :param rv: the return value from the view function .. versionchanged:: 0.9 Previously a tuple was interpreted as the arguments for the response object. """ status_or_headers = headers = None if isinstance(rv, tuple): rv, status_or_headers, headers = rv + (None,) * (3 - len(rv)) if rv is None: raise ValueError('View function did not return a response') if isinstance(status_or_headers, (dict, list)): headers, status_or_headers = status_or_headers, None if not isinstance(rv, self.response_class): # When we create a response object directly, we let the constructor # set the headers and status. We do this because there can be # some extra logic involved when creating these objects with # specific values (like default content type selection). if isinstance(rv, (text_type, bytes, bytearray)): rv = self.response_class(rv, headers=headers, status=status_or_headers) headers = status_or_headers = None else: rv = self.response_class.force_type(rv, request.environ) if status_or_headers is not None: if isinstance(status_or_headers, string_types): rv.status = status_or_headers else: rv.status_code = status_or_headers if headers: rv.headers.extend(headers) return rv
[ "def", "make_response", "(", "self", ",", "rv", ")", ":", "status_or_headers", "=", "headers", "=", "None", "if", "isinstance", "(", "rv", ",", "tuple", ")", ":", "rv", ",", "status_or_headers", ",", "headers", "=", "rv", "+", "(", "None", ",", ")", "*", "(", "3", "-", "len", "(", "rv", ")", ")", "if", "rv", "is", "None", ":", "raise", "ValueError", "(", "'View function did not return a response'", ")", "if", "isinstance", "(", "status_or_headers", ",", "(", "dict", ",", "list", ")", ")", ":", "headers", ",", "status_or_headers", "=", "status_or_headers", ",", "None", "if", "not", "isinstance", "(", "rv", ",", "self", ".", "response_class", ")", ":", "# When we create a response object directly, we let the constructor", "# set the headers and status. We do this because there can be", "# some extra logic involved when creating these objects with", "# specific values (like default content type selection).", "if", "isinstance", "(", "rv", ",", "(", "text_type", ",", "bytes", ",", "bytearray", ")", ")", ":", "rv", "=", "self", ".", "response_class", "(", "rv", ",", "headers", "=", "headers", ",", "status", "=", "status_or_headers", ")", "headers", "=", "status_or_headers", "=", "None", "else", ":", "rv", "=", "self", ".", "response_class", ".", "force_type", "(", "rv", ",", "request", ".", "environ", ")", "if", "status_or_headers", "is", "not", "None", ":", "if", "isinstance", "(", "status_or_headers", ",", "string_types", ")", ":", "rv", ".", "status", "=", "status_or_headers", "else", ":", "rv", ".", "status_code", "=", "status_or_headers", "if", "headers", ":", "rv", ".", "headers", ".", "extend", "(", "headers", ")", "return", "rv" ]
[ 1689, 4 ]
[ 1749, 17 ]
python
en
['en', 'en', 'en']
True
Flask.create_url_adapter
(self, request)
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now also be called without a request object when the URL adapter is created for the application context.
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now also be called without a request object when the URL adapter is created for the application context. """ if request is not None: return self.url_map.bind_to_environ(request.environ, server_name=self.config['SERVER_NAME']) # We need at the very least the server name to be set for this # to work. if self.config['SERVER_NAME'] is not None: return self.url_map.bind( self.config['SERVER_NAME'], script_name=self.config['APPLICATION_ROOT'] or '/', url_scheme=self.config['PREFERRED_URL_SCHEME'])
[ "def", "create_url_adapter", "(", "self", ",", "request", ")", ":", "if", "request", "is", "not", "None", ":", "return", "self", ".", "url_map", ".", "bind_to_environ", "(", "request", ".", "environ", ",", "server_name", "=", "self", ".", "config", "[", "'SERVER_NAME'", "]", ")", "# We need at the very least the server name to be set for this", "# to work.", "if", "self", ".", "config", "[", "'SERVER_NAME'", "]", "is", "not", "None", ":", "return", "self", ".", "url_map", ".", "bind", "(", "self", ".", "config", "[", "'SERVER_NAME'", "]", ",", "script_name", "=", "self", ".", "config", "[", "'APPLICATION_ROOT'", "]", "or", "'/'", ",", "url_scheme", "=", "self", ".", "config", "[", "'PREFERRED_URL_SCHEME'", "]", ")" ]
[ 1751, 4 ]
[ 1771, 63 ]
python
en
['en', 'en', 'en']
True
Flask.inject_url_defaults
(self, endpoint, values)
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
def inject_url_defaults(self, endpoint, values): """Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7 """ funcs = self.url_default_functions.get(None, ()) if '.' in endpoint: bp = endpoint.rsplit('.', 1)[0] funcs = chain(funcs, self.url_default_functions.get(bp, ())) for func in funcs: func(endpoint, values)
[ "def", "inject_url_defaults", "(", "self", ",", "endpoint", ",", "values", ")", ":", "funcs", "=", "self", ".", "url_default_functions", ".", "get", "(", "None", ",", "(", ")", ")", "if", "'.'", "in", "endpoint", ":", "bp", "=", "endpoint", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "funcs", "=", "chain", "(", "funcs", ",", "self", ".", "url_default_functions", ".", "get", "(", "bp", ",", "(", ")", ")", ")", "for", "func", "in", "funcs", ":", "func", "(", "endpoint", ",", "values", ")" ]
[ 1773, 4 ]
[ 1785, 34 ]
python
en
['en', 'en', 'en']
True
Flask.handle_url_build_error
(self, error, endpoint, values)
Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
def handle_url_build_error(self, error, endpoint, values): """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`. """ exc_type, exc_value, tb = sys.exc_info() for handler in self.url_build_error_handlers: try: rv = handler(error, endpoint, values) if rv is not None: return rv except BuildError as e: # make error available outside except block (py3) error = e # At this point we want to reraise the exception. If the error is # still the same one we can reraise it with the original traceback, # otherwise we raise it from here. if error is exc_value: reraise(exc_type, exc_value, tb) raise error
[ "def", "handle_url_build_error", "(", "self", ",", "error", ",", "endpoint", ",", "values", ")", ":", "exc_type", ",", "exc_value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "for", "handler", "in", "self", ".", "url_build_error_handlers", ":", "try", ":", "rv", "=", "handler", "(", "error", ",", "endpoint", ",", "values", ")", "if", "rv", "is", "not", "None", ":", "return", "rv", "except", "BuildError", "as", "e", ":", "# make error available outside except block (py3)", "error", "=", "e", "# At this point we want to reraise the exception. If the error is", "# still the same one we can reraise it with the original traceback,", "# otherwise we raise it from here.", "if", "error", "is", "exc_value", ":", "reraise", "(", "exc_type", ",", "exc_value", ",", "tb", ")", "raise", "error" ]
[ 1787, 4 ]
[ 1805, 19 ]
python
de
['en', 'de', 'nl']
False
Flask.preprocess_request
(self)
Called before the actual request dispatching and will call each :meth:`before_request` decorated function, passing no arguments. If any of these functions returns a value, it's handled as if it was the return value from the view and further request handling is stopped. This also triggers the :meth:`url_value_preprocessor` functions before the actual :meth:`before_request` functions are called.
Called before the actual request dispatching and will call each :meth:`before_request` decorated function, passing no arguments. If any of these functions returns a value, it's handled as if it was the return value from the view and further request handling is stopped.
def preprocess_request(self): """Called before the actual request dispatching and will call each :meth:`before_request` decorated function, passing no arguments. If any of these functions returns a value, it's handled as if it was the return value from the view and further request handling is stopped. This also triggers the :meth:`url_value_preprocessor` functions before the actual :meth:`before_request` functions are called. """ bp = _request_ctx_stack.top.request.blueprint funcs = self.url_value_preprocessors.get(None, ()) if bp is not None and bp in self.url_value_preprocessors: funcs = chain(funcs, self.url_value_preprocessors[bp]) for func in funcs: func(request.endpoint, request.view_args) funcs = self.before_request_funcs.get(None, ()) if bp is not None and bp in self.before_request_funcs: funcs = chain(funcs, self.before_request_funcs[bp]) for func in funcs: rv = func() if rv is not None: return rv
[ "def", "preprocess_request", "(", "self", ")", ":", "bp", "=", "_request_ctx_stack", ".", "top", ".", "request", ".", "blueprint", "funcs", "=", "self", ".", "url_value_preprocessors", ".", "get", "(", "None", ",", "(", ")", ")", "if", "bp", "is", "not", "None", "and", "bp", "in", "self", ".", "url_value_preprocessors", ":", "funcs", "=", "chain", "(", "funcs", ",", "self", ".", "url_value_preprocessors", "[", "bp", "]", ")", "for", "func", "in", "funcs", ":", "func", "(", "request", ".", "endpoint", ",", "request", ".", "view_args", ")", "funcs", "=", "self", ".", "before_request_funcs", ".", "get", "(", "None", ",", "(", ")", ")", "if", "bp", "is", "not", "None", "and", "bp", "in", "self", ".", "before_request_funcs", ":", "funcs", "=", "chain", "(", "funcs", ",", "self", ".", "before_request_funcs", "[", "bp", "]", ")", "for", "func", "in", "funcs", ":", "rv", "=", "func", "(", ")", "if", "rv", "is", "not", "None", ":", "return", "rv" ]
[ 1807, 4 ]
[ 1832, 25 ]
python
en
['en', 'en', 'en']
True
Flask.process_response
(self, response)
Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions. .. versionchanged:: 0.5 As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration. :param response: a :attr:`response_class` object. :return: a new response object or the same, has to be an instance of :attr:`response_class`.
Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions.
def process_response(self, response): """Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions. .. versionchanged:: 0.5 As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration. :param response: a :attr:`response_class` object. :return: a new response object or the same, has to be an instance of :attr:`response_class`. """ ctx = _request_ctx_stack.top bp = ctx.request.blueprint funcs = ctx._after_request_functions if bp is not None and bp in self.after_request_funcs: funcs = chain(funcs, reversed(self.after_request_funcs[bp])) if None in self.after_request_funcs: funcs = chain(funcs, reversed(self.after_request_funcs[None])) for handler in funcs: response = handler(response) if not self.session_interface.is_null_session(ctx.session): self.save_session(ctx.session, response) return response
[ "def", "process_response", "(", "self", ",", "response", ")", ":", "ctx", "=", "_request_ctx_stack", ".", "top", "bp", "=", "ctx", ".", "request", ".", "blueprint", "funcs", "=", "ctx", ".", "_after_request_functions", "if", "bp", "is", "not", "None", "and", "bp", "in", "self", ".", "after_request_funcs", ":", "funcs", "=", "chain", "(", "funcs", ",", "reversed", "(", "self", ".", "after_request_funcs", "[", "bp", "]", ")", ")", "if", "None", "in", "self", ".", "after_request_funcs", ":", "funcs", "=", "chain", "(", "funcs", ",", "reversed", "(", "self", ".", "after_request_funcs", "[", "None", "]", ")", ")", "for", "handler", "in", "funcs", ":", "response", "=", "handler", "(", "response", ")", "if", "not", "self", ".", "session_interface", ".", "is_null_session", "(", "ctx", ".", "session", ")", ":", "self", ".", "save_session", "(", "ctx", ".", "session", ",", "response", ")", "return", "response" ]
[ 1834, 4 ]
[ 1858, 23 ]
python
en
['en', 'en', 'en']
True
Flask.do_teardown_request
(self, exc=_sentinel)
Called after the actual request dispatching and will call every as :meth:`teardown_request` decorated function. This is not actually called by the :class:`Flask` object itself but is always triggered when the request context is popped. That way we have a tighter control over certain resources under testing environments. .. versionchanged:: 0.9 Added the `exc` argument. Previously this was always using the current exception information.
Called after the actual request dispatching and will call every as :meth:`teardown_request` decorated function. This is not actually called by the :class:`Flask` object itself but is always triggered when the request context is popped. That way we have a tighter control over certain resources under testing environments.
def do_teardown_request(self, exc=_sentinel): """Called after the actual request dispatching and will call every as :meth:`teardown_request` decorated function. This is not actually called by the :class:`Flask` object itself but is always triggered when the request context is popped. That way we have a tighter control over certain resources under testing environments. .. versionchanged:: 0.9 Added the `exc` argument. Previously this was always using the current exception information. """ if exc is _sentinel: exc = sys.exc_info()[1] funcs = reversed(self.teardown_request_funcs.get(None, ())) bp = _request_ctx_stack.top.request.blueprint if bp is not None and bp in self.teardown_request_funcs: funcs = chain(funcs, reversed(self.teardown_request_funcs[bp])) for func in funcs: func(exc) request_tearing_down.send(self, exc=exc)
[ "def", "do_teardown_request", "(", "self", ",", "exc", "=", "_sentinel", ")", ":", "if", "exc", "is", "_sentinel", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "funcs", "=", "reversed", "(", "self", ".", "teardown_request_funcs", ".", "get", "(", "None", ",", "(", ")", ")", ")", "bp", "=", "_request_ctx_stack", ".", "top", ".", "request", ".", "blueprint", "if", "bp", "is", "not", "None", "and", "bp", "in", "self", ".", "teardown_request_funcs", ":", "funcs", "=", "chain", "(", "funcs", ",", "reversed", "(", "self", ".", "teardown_request_funcs", "[", "bp", "]", ")", ")", "for", "func", "in", "funcs", ":", "func", "(", "exc", ")", "request_tearing_down", ".", "send", "(", "self", ",", "exc", "=", "exc", ")" ]
[ 1860, 4 ]
[ 1879, 48 ]
python
en
['en', 'en', 'en']
True
Flask.do_teardown_appcontext
(self, exc=_sentinel)
Called when an application context is popped. This works pretty much the same as :meth:`do_teardown_request` but for the application context. .. versionadded:: 0.9
Called when an application context is popped. This works pretty much the same as :meth:`do_teardown_request` but for the application context.
def do_teardown_appcontext(self, exc=_sentinel): """Called when an application context is popped. This works pretty much the same as :meth:`do_teardown_request` but for the application context. .. versionadded:: 0.9 """ if exc is _sentinel: exc = sys.exc_info()[1] for func in reversed(self.teardown_appcontext_funcs): func(exc) appcontext_tearing_down.send(self, exc=exc)
[ "def", "do_teardown_appcontext", "(", "self", ",", "exc", "=", "_sentinel", ")", ":", "if", "exc", "is", "_sentinel", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "for", "func", "in", "reversed", "(", "self", ".", "teardown_appcontext_funcs", ")", ":", "func", "(", "exc", ")", "appcontext_tearing_down", ".", "send", "(", "self", ",", "exc", "=", "exc", ")" ]
[ 1881, 4 ]
[ 1892, 51 ]
python
en
['en', 'en', 'en']
True
Flask.app_context
(self)
Binds the application only. For as long as the application is bound to the current context the :data:`flask.current_app` points to that application. An application context is automatically created when a request context is pushed if necessary. Example usage:: with app.app_context(): ... .. versionadded:: 0.9
Binds the application only. For as long as the application is bound to the current context the :data:`flask.current_app` points to that application. An application context is automatically created when a request context is pushed if necessary.
def app_context(self): """Binds the application only. For as long as the application is bound to the current context the :data:`flask.current_app` points to that application. An application context is automatically created when a request context is pushed if necessary. Example usage:: with app.app_context(): ... .. versionadded:: 0.9 """ return AppContext(self)
[ "def", "app_context", "(", "self", ")", ":", "return", "AppContext", "(", "self", ")" ]
[ 1894, 4 ]
[ 1907, 31 ]
python
en
['en', 'en', 'en']
True
Flask.request_context
(self, environ)
Creates a :class:`~flask.ctx.RequestContext` from the given environment and binds it to the current context. This must be used in combination with the ``with`` statement because the request is only bound to the current context for the duration of the ``with`` block. Example usage:: with app.request_context(environ): do_something_with(request) The object returned can also be used without the ``with`` statement which is useful for working in the shell. The example above is doing exactly the same as this code:: ctx = app.request_context(environ) ctx.push() try: do_something_with(request) finally: ctx.pop() .. versionchanged:: 0.3 Added support for non-with statement usage and ``with`` statement is now passed the ctx object. :param environ: a WSGI environment
Creates a :class:`~flask.ctx.RequestContext` from the given environment and binds it to the current context. This must be used in combination with the ``with`` statement because the request is only bound to the current context for the duration of the ``with`` block.
def request_context(self, environ): """Creates a :class:`~flask.ctx.RequestContext` from the given environment and binds it to the current context. This must be used in combination with the ``with`` statement because the request is only bound to the current context for the duration of the ``with`` block. Example usage:: with app.request_context(environ): do_something_with(request) The object returned can also be used without the ``with`` statement which is useful for working in the shell. The example above is doing exactly the same as this code:: ctx = app.request_context(environ) ctx.push() try: do_something_with(request) finally: ctx.pop() .. versionchanged:: 0.3 Added support for non-with statement usage and ``with`` statement is now passed the ctx object. :param environ: a WSGI environment """ return RequestContext(self, environ)
[ "def", "request_context", "(", "self", ",", "environ", ")", ":", "return", "RequestContext", "(", "self", ",", "environ", ")" ]
[ 1909, 4 ]
[ 1937, 44 ]
python
en
['en', 'en', 'en']
True
Flask.test_request_context
(self, *args, **kwargs)
Creates a WSGI environment from the given values (see :class:`werkzeug.test.EnvironBuilder` for more information, this function accepts the same arguments).
Creates a WSGI environment from the given values (see :class:`werkzeug.test.EnvironBuilder` for more information, this function accepts the same arguments).
def test_request_context(self, *args, **kwargs): """Creates a WSGI environment from the given values (see :class:`werkzeug.test.EnvironBuilder` for more information, this function accepts the same arguments). """ from flask.testing import make_test_environ_builder builder = make_test_environ_builder(self, *args, **kwargs) try: return self.request_context(builder.get_environ()) finally: builder.close()
[ "def", "test_request_context", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "flask", ".", "testing", "import", "make_test_environ_builder", "builder", "=", "make_test_environ_builder", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "return", "self", ".", "request_context", "(", "builder", ".", "get_environ", "(", ")", ")", "finally", ":", "builder", ".", "close", "(", ")" ]
[ 1939, 4 ]
[ 1949, 27 ]
python
en
['en', 'en', 'en']
True
Flask.wsgi_app
(self, environ, start_response)
The actual WSGI application. This is not implemented in `__call__` so that middlewares can be applied without losing a reference to the class. So instead of doing this:: app = MyMiddleware(app) It's a better idea to do this instead:: app.wsgi_app = MyMiddleware(app.wsgi_app) Then you still have the original application object around and can continue to call methods on it. .. versionchanged:: 0.7 The behavior of the before and after request callbacks was changed under error conditions and a new callback was added that will always execute at the end of the request, independent on if an error occurred or not. See :ref:`callbacks-and-errors`. :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
The actual WSGI application. This is not implemented in `__call__` so that middlewares can be applied without losing a reference to the class. So instead of doing this::
def wsgi_app(self, environ, start_response): """The actual WSGI application. This is not implemented in `__call__` so that middlewares can be applied without losing a reference to the class. So instead of doing this:: app = MyMiddleware(app) It's a better idea to do this instead:: app.wsgi_app = MyMiddleware(app.wsgi_app) Then you still have the original application object around and can continue to call methods on it. .. versionchanged:: 0.7 The behavior of the before and after request callbacks was changed under error conditions and a new callback was added that will always execute at the end of the request, independent on if an error occurred or not. See :ref:`callbacks-and-errors`. :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 """ ctx = self.request_context(environ) ctx.push() error = None try: try: response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: error = sys.exc_info()[1] raise return response(environ, start_response) finally: if self.should_ignore_error(error): error = None ctx.auto_pop(error)
[ "def", "wsgi_app", "(", "self", ",", "environ", ",", "start_response", ")", ":", "ctx", "=", "self", ".", "request_context", "(", "environ", ")", "ctx", ".", "push", "(", ")", "error", "=", "None", "try", ":", "try", ":", "response", "=", "self", ".", "full_dispatch_request", "(", ")", "except", "Exception", "as", "e", ":", "error", "=", "e", "response", "=", "self", ".", "handle_exception", "(", "e", ")", "except", ":", "error", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "raise", "return", "response", "(", "environ", ",", "start_response", ")", "finally", ":", "if", "self", ".", "should_ignore_error", "(", "error", ")", ":", "error", "=", "None", "ctx", ".", "auto_pop", "(", "error", ")" ]
[ 1951, 4 ]
[ 1992, 31 ]
python
en
['en', 'en', 'en']
True
Flask.__call__
(self, environ, start_response)
Shortcut for :attr:`wsgi_app`.
Shortcut for :attr:`wsgi_app`.
def __call__(self, environ, start_response): """Shortcut for :attr:`wsgi_app`.""" return self.wsgi_app(environ, start_response)
[ "def", "__call__", "(", "self", ",", "environ", ",", "start_response", ")", ":", "return", "self", ".", "wsgi_app", "(", "environ", ",", "start_response", ")" ]
[ 1994, 4 ]
[ 1996, 53 ]
python
en
['en', 'sv', 'en']
True
extract_resources
(taxonomy_filepath)
Reads a .json representing a taxonomy and returns a data structure representing their hierarchical relationship :param taxonomy_file: a string representing a path to a .json file :return: Node representing root of taxonomic tree
Reads a .json representing a taxonomy and returns a data structure representing their hierarchical relationship :param taxonomy_file: a string representing a path to a .json file :return: Node representing root of taxonomic tree
def extract_resources(taxonomy_filepath): """ Reads a .json representing a taxonomy and returns a data structure representing their hierarchical relationship :param taxonomy_file: a string representing a path to a .json file :return: Node representing root of taxonomic tree """ try: with open(taxonomy_filepath, 'r') as fp: json_str = fp.read() json_data = json.loads(json_str) root = DictImporter().import_(json_data) finally: fp.close() return root
[ "def", "extract_resources", "(", "taxonomy_filepath", ")", ":", "try", ":", "with", "open", "(", "taxonomy_filepath", ",", "'r'", ")", "as", "fp", ":", "json_str", "=", "fp", ".", "read", "(", ")", "json_data", "=", "json", ".", "loads", "(", "json_str", ")", "root", "=", "DictImporter", "(", ")", ".", "import_", "(", "json_data", ")", "finally", ":", "fp", ".", "close", "(", ")", "return", "root" ]
[ 50, 0 ]
[ 66, 15 ]
python
en
['en', 'error', 'th']
False
read_users
(users_fp)
Reads a .csv from @user_fp representing users into a list of dictionaries, each elt of which represents a user :param user_fp: a .csv file where each line represents a user :return: a list of dictionaries
Reads a .csv from
def read_users(users_fp): """ Reads a .csv from @user_fp representing users into a list of dictionaries, each elt of which represents a user :param user_fp: a .csv file where each line represents a user :return: a list of dictionaries """ users = [] with open(users_fp, 'r') as fp: fields = fp.readline().rstrip().split(",") for line in fp: user = dict(zip(fields, line.rstrip().split(","))) users.append(user) return users
[ "def", "read_users", "(", "users_fp", ")", ":", "users", "=", "[", "]", "with", "open", "(", "users_fp", ",", "'r'", ")", "as", "fp", ":", "fields", "=", "fp", ".", "readline", "(", ")", ".", "rstrip", "(", ")", ".", "split", "(", "\",\"", ")", "for", "line", "in", "fp", ":", "user", "=", "dict", "(", "zip", "(", "fields", ",", "line", ".", "rstrip", "(", ")", ".", "split", "(", "\",\"", ")", ")", ")", "users", ".", "append", "(", "user", ")", "return", "users" ]
[ 69, 0 ]
[ 82, 16 ]
python
en
['en', 'error', 'th']
False
sleep_then_publish_burst
(burst, publisher, topic_path)
:param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return:
def sleep_then_publish_burst(burst, publisher, topic_path): """ :param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return: """ sleep_secs = random.uniform(0, max_lag_millis/1000) time.sleep(sleep_secs) publish_burst(burst, publisher, topic_path)
[ "def", "sleep_then_publish_burst", "(", "burst", ",", "publisher", ",", "topic_path", ")", ":", "sleep_secs", "=", "random", ".", "uniform", "(", "0", ",", "max_lag_millis", "/", "1000", ")", "time", ".", "sleep", "(", "sleep_secs", ")", "publish_burst", "(", "burst", ",", "publisher", ",", "topic_path", ")" ]
[ 84, 0 ]
[ 96, 47 ]
python
en
['en', 'error', 'th']
False
publish_burst
(burst, publisher, topic_path)
Publishes and prints each event :param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return:
Publishes and prints each event :param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return:
def publish_burst(burst, publisher, topic_path): """ Publishes and prints each event :param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return: """ for event_dict in burst: json_str = json.dumps(event_dict) data = json_str.encode('utf-8') publisher.publish(topic_path, data=data, timestamp=event_dict['timestamp'])
[ "def", "publish_burst", "(", "burst", ",", "publisher", ",", "topic_path", ")", ":", "for", "event_dict", "in", "burst", ":", "json_str", "=", "json", ".", "dumps", "(", "event_dict", ")", "data", "=", "json_str", ".", "encode", "(", "'utf-8'", ")", "publisher", ".", "publish", "(", "topic_path", ",", "data", "=", "data", ",", "timestamp", "=", "event_dict", "[", "'timestamp'", "]", ")" ]
[ 98, 0 ]
[ 111, 83 ]
python
en
['en', 'error', 'th']
False
create_user_process
(user, root)
Code for continuously-running process representing a user publishing events to pubsub :param user: a dictionary representing characteristics of the user :param root: an instance of AnyNode representing the home page of a website :param num_events_counter: a variable shared among all processes used to track the number of events published :return:
Code for continuously-running process representing a user publishing events to pubsub :param user: a dictionary representing characteristics of the user :param root: an instance of AnyNode representing the home page of a website :param num_events_counter: a variable shared among all processes used to track the number of events published :return:
def create_user_process(user, root): """ Code for continuously-running process representing a user publishing events to pubsub :param user: a dictionary representing characteristics of the user :param root: an instance of AnyNode representing the home page of a website :param num_events_counter: a variable shared among all processes used to track the number of events published :return: """ publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_name) user['page'] = root user['is_online'] = True user['offline_events'] = [] while True: time_between_events = random.uniform(0, avg_secs_between_events * 2) time.sleep(time_between_events) prob = random.random() event = generate_event(user) if user['is_online']: if prob < online_to_offline_probability: user['is_online'] = False user['offline_events'] = [event] else: sleep_then_publish_burst([event], publisher, topic_path) else: user['offline_events'].append(event) if prob < offline_to_online_probability: user['is_online'] = True sleep_then_publish_burst(user['offline_events'], publisher, topic_path) user['offline_events'] = []
[ "def", "create_user_process", "(", "user", ",", "root", ")", ":", "publisher", "=", "pubsub_v1", ".", "PublisherClient", "(", ")", "topic_path", "=", "publisher", ".", "topic_path", "(", "project_id", ",", "topic_name", ")", "user", "[", "'page'", "]", "=", "root", "user", "[", "'is_online'", "]", "=", "True", "user", "[", "'offline_events'", "]", "=", "[", "]", "while", "True", ":", "time_between_events", "=", "random", ".", "uniform", "(", "0", ",", "avg_secs_between_events", "*", "2", ")", "time", ".", "sleep", "(", "time_between_events", ")", "prob", "=", "random", ".", "random", "(", ")", "event", "=", "generate_event", "(", "user", ")", "if", "user", "[", "'is_online'", "]", ":", "if", "prob", "<", "online_to_offline_probability", ":", "user", "[", "'is_online'", "]", "=", "False", "user", "[", "'offline_events'", "]", "=", "[", "event", "]", "else", ":", "sleep_then_publish_burst", "(", "[", "event", "]", ",", "publisher", ",", "topic_path", ")", "else", ":", "user", "[", "'offline_events'", "]", ".", "append", "(", "event", ")", "if", "prob", "<", "offline_to_online_probability", ":", "user", "[", "'is_online'", "]", "=", "True", "sleep_then_publish_burst", "(", "user", "[", "'offline_events'", "]", ",", "publisher", ",", "topic_path", ")", "user", "[", "'offline_events'", "]", "=", "[", "]" ]
[ 113, 0 ]
[ 145, 43 ]
python
en
['en', 'error', 'th']
False
generate_event
(user)
Returns a dictionary representing an event :param user: :return:
Returns a dictionary representing an event :param user: :return:
def generate_event(user): """ Returns a dictionary representing an event :param user: :return: """ user['page'] = get_next_page(user) uri = str(user['page'].name) event_time = datetime.now(tz=timezone.utc) current_time_str = event_time.strftime('%Y-%m-%dT%H:%M:%S.%fZ') file_size_bytes = random.choice(range(min_file_size_bytes, max_file_size_bytes)) http_request = "\"{} {} HTTP/1.0\"".format(random.choice(verbs), uri) http_response = random.choice(responses) event_values = [user['ip'], user['id'], float(user['lat']), float(user['lng']), current_time_str, http_request, http_response, file_size_bytes, user['user_agent']] return dict(zip(log_fields, event_values))
[ "def", "generate_event", "(", "user", ")", ":", "user", "[", "'page'", "]", "=", "get_next_page", "(", "user", ")", "uri", "=", "str", "(", "user", "[", "'page'", "]", ".", "name", ")", "event_time", "=", "datetime", ".", "now", "(", "tz", "=", "timezone", ".", "utc", ")", "current_time_str", "=", "event_time", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S.%fZ'", ")", "file_size_bytes", "=", "random", ".", "choice", "(", "range", "(", "min_file_size_bytes", ",", "max_file_size_bytes", ")", ")", "http_request", "=", "\"\\\"{} {} HTTP/1.0\\\"\"", ".", "format", "(", "random", ".", "choice", "(", "verbs", ")", ",", "uri", ")", "http_response", "=", "random", ".", "choice", "(", "responses", ")", "event_values", "=", "[", "user", "[", "'ip'", "]", ",", "user", "[", "'id'", "]", ",", "float", "(", "user", "[", "'lat'", "]", ")", ",", "float", "(", "user", "[", "'lng'", "]", ")", ",", "current_time_str", ",", "http_request", ",", "http_response", ",", "file_size_bytes", ",", "user", "[", "'user_agent'", "]", "]", "return", "dict", "(", "zip", "(", "log_fields", ",", "event_values", ")", ")" ]
[ 147, 0 ]
[ 163, 46 ]
python
en
['en', 'error', 'th']
False
get_next_page
(user)
Consults the user's representation of the web site taxonomy to determine the next page that they visit :param user: :return:
Consults the user's representation of the web site taxonomy to determine the next page that they visit :param user: :return:
def get_next_page(user): """ Consults the user's representation of the web site taxonomy to determine the next page that they visit :param user: :return: """ possible_next_pages = [user['page']] if not user['page'].is_leaf: possible_next_pages += list(user['page'].children) if (user['page'].parent != None): possible_next_pages += [user['page'].parent] next_page = random.choice(possible_next_pages) return next_page
[ "def", "get_next_page", "(", "user", ")", ":", "possible_next_pages", "=", "[", "user", "[", "'page'", "]", "]", "if", "not", "user", "[", "'page'", "]", ".", "is_leaf", ":", "possible_next_pages", "+=", "list", "(", "user", "[", "'page'", "]", ".", "children", ")", "if", "(", "user", "[", "'page'", "]", ".", "parent", "!=", "None", ")", ":", "possible_next_pages", "+=", "[", "user", "[", "'page'", "]", ".", "parent", "]", "next_page", "=", "random", ".", "choice", "(", "possible_next_pages", ")", "return", "next_page" ]
[ 165, 0 ]
[ 177, 20 ]
python
en
['en', 'error', 'th']
False
ItemAttributeKNN.__init__
(self, train_file=None, test_file=None, output_file=None, metadata_file=None, similarity_file=None, k_neighbors=30, as_similar_first=True, metadata_as_binary=False, metadata_similarity_sep='\t', similarity_metric="cosine", sep='\t', output_sep='\t')
Item Attribute KNN for Rating Prediction This algorithm predicts a rank for each user based on the similar items that he/her consumed, using a metadata or similarity pre-computed file Usage:: >> ItemAttributeKNN(train, test, similarity_file=sim_matrix, as_similar_first=True).compute() >> ItemAttributeKNN(train, test, metadata_file=metadata, as_similar_first=False).compute() :param train_file: File which contains the train set. This file needs to have at least 3 columns (user item feedback_value). :type train_file: str, default None :param test_file: File which contains the test set. This file needs to have at least 3 columns (user item feedback_value). :type test_file: str, default None :param output_file: File with dir to write the final predictions :type output_file: str, default None :param metadata_file: File which contains the metadata set. This file needs to have at least 2 columns (item metadata). :type metadata_file: str, default None :param similarity_file: File which contains the similarity set. This file needs to have at least 3 columns (item item similarity). :type similarity_file: str, default None :param k_neighbors: Number of neighbors to use. If None, k_neighbor = int(sqrt(n_users)) :type k_neighbors: int, default None :param as_similar_first: If True, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. :type as_similar_first: bool, default True :param metadata_as_binary: f True, the explicit value will be transform to binary :type metadata_as_binary: bool, default False :param metadata_similarity_sep: Delimiter for similarity or metadata file :type metadata_similarity_sep: str, default '\t' :param similarity_metric: Pairwise metric to compute the similarity between the items. Reference about distances: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.pdist.html :type similarity_metric: str, default cosine :param sep: Delimiter for input files file :type sep: str, default '\t' :param output_sep: Delimiter for output file :type output_sep: str, default '\t'
Item Attribute KNN for Rating Prediction
def __init__(self, train_file=None, test_file=None, output_file=None, metadata_file=None, similarity_file=None, k_neighbors=30, as_similar_first=True, metadata_as_binary=False, metadata_similarity_sep='\t', similarity_metric="cosine", sep='\t', output_sep='\t'): """ Item Attribute KNN for Rating Prediction This algorithm predicts a rank for each user based on the similar items that he/her consumed, using a metadata or similarity pre-computed file Usage:: >> ItemAttributeKNN(train, test, similarity_file=sim_matrix, as_similar_first=True).compute() >> ItemAttributeKNN(train, test, metadata_file=metadata, as_similar_first=False).compute() :param train_file: File which contains the train set. This file needs to have at least 3 columns (user item feedback_value). :type train_file: str, default None :param test_file: File which contains the test set. This file needs to have at least 3 columns (user item feedback_value). :type test_file: str, default None :param output_file: File with dir to write the final predictions :type output_file: str, default None :param metadata_file: File which contains the metadata set. This file needs to have at least 2 columns (item metadata). :type metadata_file: str, default None :param similarity_file: File which contains the similarity set. This file needs to have at least 3 columns (item item similarity). :type similarity_file: str, default None :param k_neighbors: Number of neighbors to use. If None, k_neighbor = int(sqrt(n_users)) :type k_neighbors: int, default None :param as_similar_first: If True, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. :type as_similar_first: bool, default True :param metadata_as_binary: f True, the explicit value will be transform to binary :type metadata_as_binary: bool, default False :param metadata_similarity_sep: Delimiter for similarity or metadata file :type metadata_similarity_sep: str, default '\t' :param similarity_metric: Pairwise metric to compute the similarity between the items. Reference about distances: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.pdist.html :type similarity_metric: str, default cosine :param sep: Delimiter for input files file :type sep: str, default '\t' :param output_sep: Delimiter for output file :type output_sep: str, default '\t' """ super(ItemAttributeKNN, self).__init__(train_file=train_file, test_file=test_file, output_file=output_file, k_neighbors=k_neighbors, as_similar_first=as_similar_first, sep=sep, output_sep=output_sep, similarity_metric=similarity_metric) self.recommender_name = 'Item Attribute KNN Algorithm' self.metadata_file = metadata_file self.similarity_file = similarity_file self.metadata_as_binary = metadata_as_binary self.metadata_similarity_sep = metadata_similarity_sep
[ "def", "__init__", "(", "self", ",", "train_file", "=", "None", ",", "test_file", "=", "None", ",", "output_file", "=", "None", ",", "metadata_file", "=", "None", ",", "similarity_file", "=", "None", ",", "k_neighbors", "=", "30", ",", "as_similar_first", "=", "True", ",", "metadata_as_binary", "=", "False", ",", "metadata_similarity_sep", "=", "'\\t'", ",", "similarity_metric", "=", "\"cosine\"", ",", "sep", "=", "'\\t'", ",", "output_sep", "=", "'\\t'", ")", ":", "super", "(", "ItemAttributeKNN", ",", "self", ")", ".", "__init__", "(", "train_file", "=", "train_file", ",", "test_file", "=", "test_file", ",", "output_file", "=", "output_file", ",", "k_neighbors", "=", "k_neighbors", ",", "as_similar_first", "=", "as_similar_first", ",", "sep", "=", "sep", ",", "output_sep", "=", "output_sep", ",", "similarity_metric", "=", "similarity_metric", ")", "self", ".", "recommender_name", "=", "'Item Attribute KNN Algorithm'", "self", ".", "metadata_file", "=", "metadata_file", "self", ".", "similarity_file", "=", "similarity_file", "self", ".", "metadata_as_binary", "=", "metadata_as_binary", "self", ".", "metadata_similarity_sep", "=", "metadata_similarity_sep" ]
[ 23, 4 ]
[ 91, 62 ]
python
en
['en', 'error', 'th']
False
ItemAttributeKNN.init_model
(self)
Method to fit the model. Create and calculate a similarity matrix by metadata file or a pre-computed similarity matrix
Method to fit the model. Create and calculate a similarity matrix by metadata file or a pre-computed similarity matrix
def init_model(self): """ Method to fit the model. Create and calculate a similarity matrix by metadata file or a pre-computed similarity matrix """ self.similar_items = defaultdict(list) # Set the value for k if self.k_neighbors is None: self.k_neighbors = int(np.sqrt(len(self.items))) if self.metadata_file is not None: metadata = ReadFile(self.metadata_file, sep=self.metadata_similarity_sep, as_binary=self.metadata_as_binary ).read_metadata_or_similarity() self.matrix = np.zeros((len(self.items), len(metadata['col_2']))) meta_to_meta_id = {} for m, data in enumerate(metadata['col_2']): meta_to_meta_id[data] = m for item in metadata['col_1']: for m in metadata['dict'][item]: self.matrix[self.item_to_item_id[item], meta_to_meta_id[m]] = metadata['dict'][item][m] # create header info for metadata sparsity = (1 - (metadata['number_interactions'] / (len(metadata['col_1']) * len(metadata['col_2'])))) * 100 self.extra_info_header = ">> metadata:: %d items and %d metadata (%d interactions) | sparsity:: %.2f%%" % \ (len(metadata['col_1']), len(metadata['col_2']), metadata['number_interactions'], sparsity) # Create similarity matrix based on metadata or similarity file. Transpose=False, because it is an # item x metadata matrix self.si_matrix = self.compute_similarity(transpose=False) elif self.similarity_file is not None: similarity = ReadFile(self.similarity_file, sep=self.metadata_similarity_sep, as_binary=False ).read_metadata_or_similarity() self.si_matrix = np.zeros((len(self.items), len(self.items))) # Fill similarity matrix for i in similarity['col_1']: for i_j in similarity['dict'][i]: self.si_matrix[self.item_to_item_id[i], self.item_to_item_id[int(i_j)]] = similarity['dict'][i][i_j] # Remove NaNs self.si_matrix[np.isnan(self.si_matrix)] = 0.0 else: raise ValueError("This algorithm needs a similarity matrix or a metadata file!") # Create original matrix user x item for prediction process self.create_matrix() for i_id, item in enumerate(self.items): self.similar_items[i_id] = sorted(range(len(self.si_matrix[i_id])), key=lambda k: -self.si_matrix[i_id][k])[1:self.k_neighbors + 1]
[ "def", "init_model", "(", "self", ")", ":", "self", ".", "similar_items", "=", "defaultdict", "(", "list", ")", "# Set the value for k", "if", "self", ".", "k_neighbors", "is", "None", ":", "self", ".", "k_neighbors", "=", "int", "(", "np", ".", "sqrt", "(", "len", "(", "self", ".", "items", ")", ")", ")", "if", "self", ".", "metadata_file", "is", "not", "None", ":", "metadata", "=", "ReadFile", "(", "self", ".", "metadata_file", ",", "sep", "=", "self", ".", "metadata_similarity_sep", ",", "as_binary", "=", "self", ".", "metadata_as_binary", ")", ".", "read_metadata_or_similarity", "(", ")", "self", ".", "matrix", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ".", "items", ")", ",", "len", "(", "metadata", "[", "'col_2'", "]", ")", ")", ")", "meta_to_meta_id", "=", "{", "}", "for", "m", ",", "data", "in", "enumerate", "(", "metadata", "[", "'col_2'", "]", ")", ":", "meta_to_meta_id", "[", "data", "]", "=", "m", "for", "item", "in", "metadata", "[", "'col_1'", "]", ":", "for", "m", "in", "metadata", "[", "'dict'", "]", "[", "item", "]", ":", "self", ".", "matrix", "[", "self", ".", "item_to_item_id", "[", "item", "]", ",", "meta_to_meta_id", "[", "m", "]", "]", "=", "metadata", "[", "'dict'", "]", "[", "item", "]", "[", "m", "]", "# create header info for metadata", "sparsity", "=", "(", "1", "-", "(", "metadata", "[", "'number_interactions'", "]", "/", "(", "len", "(", "metadata", "[", "'col_1'", "]", ")", "*", "len", "(", "metadata", "[", "'col_2'", "]", ")", ")", ")", ")", "*", "100", "self", ".", "extra_info_header", "=", "\">> metadata:: %d items and %d metadata (%d interactions) | sparsity:: %.2f%%\"", "%", "(", "len", "(", "metadata", "[", "'col_1'", "]", ")", ",", "len", "(", "metadata", "[", "'col_2'", "]", ")", ",", "metadata", "[", "'number_interactions'", "]", ",", "sparsity", ")", "# Create similarity matrix based on metadata or similarity file. Transpose=False, because it is an", "# item x metadata matrix", "self", ".", "si_matrix", "=", "self", ".", "compute_similarity", "(", "transpose", "=", "False", ")", "elif", "self", ".", "similarity_file", "is", "not", "None", ":", "similarity", "=", "ReadFile", "(", "self", ".", "similarity_file", ",", "sep", "=", "self", ".", "metadata_similarity_sep", ",", "as_binary", "=", "False", ")", ".", "read_metadata_or_similarity", "(", ")", "self", ".", "si_matrix", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ".", "items", ")", ",", "len", "(", "self", ".", "items", ")", ")", ")", "# Fill similarity matrix", "for", "i", "in", "similarity", "[", "'col_1'", "]", ":", "for", "i_j", "in", "similarity", "[", "'dict'", "]", "[", "i", "]", ":", "self", ".", "si_matrix", "[", "self", ".", "item_to_item_id", "[", "i", "]", ",", "self", ".", "item_to_item_id", "[", "int", "(", "i_j", ")", "]", "]", "=", "similarity", "[", "'dict'", "]", "[", "i", "]", "[", "i_j", "]", "# Remove NaNs", "self", ".", "si_matrix", "[", "np", ".", "isnan", "(", "self", ".", "si_matrix", ")", "]", "=", "0.0", "else", ":", "raise", "ValueError", "(", "\"This algorithm needs a similarity matrix or a metadata file!\"", ")", "# Create original matrix user x item for prediction process", "self", ".", "create_matrix", "(", ")", "for", "i_id", ",", "item", "in", "enumerate", "(", "self", ".", "items", ")", ":", "self", ".", "similar_items", "[", "i_id", "]", "=", "sorted", "(", "range", "(", "len", "(", "self", ".", "si_matrix", "[", "i_id", "]", ")", ")", ",", "key", "=", "lambda", "k", ":", "-", "self", ".", "si_matrix", "[", "i_id", "]", "[", "k", "]", ")", "[", "1", ":", "self", ".", "k_neighbors", "+", "1", "]" ]
[ 93, 4 ]
[ 153, 109 ]
python
en
['en', 'error', 'th']
False
_match_vcs_scheme
(url: str)
Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match.
Look for VCS schemes in the URL.
def _match_vcs_scheme(url: str) -> Optional[str]: """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ for scheme in vcs.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme return None
[ "def", "_match_vcs_scheme", "(", "url", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "for", "scheme", "in", "vcs", ".", "schemes", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "scheme", ")", "and", "url", "[", "len", "(", "scheme", ")", "]", "in", "'+:'", ":", "return", "scheme", "return", "None" ]
[ 48, 0 ]
[ 56, 15 ]
python
en
['en', 'en', 'en']
True
_ensure_html_header
(response: Response)
Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html.
Check the Content-Type header to ensure the response contains HTML.
def _ensure_html_header(response: Response) -> None: """Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. """ content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/html"): raise _NotHTML(content_type, response.request.method)
[ "def", "_ensure_html_header", "(", "response", ":", "Response", ")", "->", "None", ":", "content_type", "=", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"\"", ")", "if", "not", "content_type", ".", "lower", "(", ")", ".", "startswith", "(", "\"text/html\"", ")", ":", "raise", "_NotHTML", "(", "content_type", ",", "response", ".", "request", ".", "method", ")" ]
[ 66, 0 ]
[ 73, 61 ]
python
en
['en', 'en', 'en']
True
_ensure_html_response
(url: str, session: PipSession)
Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html.
Send a HEAD request to the URL, and ensure the response contains HTML.
def _ensure_html_response(url: str, session: PipSession) -> None: """Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. """ scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) if scheme not in {'http', 'https'}: raise _NotHTTP() resp = session.head(url, allow_redirects=True) raise_for_status(resp) _ensure_html_header(resp)
[ "def", "_ensure_html_response", "(", "url", ":", "str", ",", "session", ":", "PipSession", ")", "->", "None", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", "if", "scheme", "not", "in", "{", "'http'", ",", "'https'", "}", ":", "raise", "_NotHTTP", "(", ")", "resp", "=", "session", ".", "head", "(", "url", ",", "allow_redirects", "=", "True", ")", "raise_for_status", "(", "resp", ")", "_ensure_html_header", "(", "resp", ")" ]
[ 80, 0 ]
[ 93, 29 ]
python
en
['en', 'en', 'en']
True
_get_html_response
(url: str, session: PipSession)
Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise.
Access an HTML page with GET, and return the response.
def _get_html_response(url: str, session: PipSession) -> Response: """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. """ if is_archive_file(Link(url).filename): _ensure_html_response(url, session=session) logger.debug('Getting page %s', redact_auth_from_url(url)) resp = session.get( url, headers={ "Accept": "text/html", # We don't want to blindly returned cached data for # /simple/, because authors generally expecting that # twine upload && pip install will function, but if # they've done a pip install in the last ~10 minutes # it won't. Thus by setting this to zero we will not # blindly use any cached data, however the benefit of # using max-age=0 instead of no-cache, is that we will # still support conditional requests, so we will still # minimize traffic sent in cases where the page hasn't # changed at all, we will just always incur the round # trip for the conditional GET now instead of only # once per 10 minutes. # For more information, please see pypa/pip#5670. "Cache-Control": "max-age=0", }, ) raise_for_status(resp) # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement of an url. Unless we issue a HEAD request on every # url we cannot know ahead of time for sure if something is HTML # or not. However we can check after we've downloaded it. _ensure_html_header(resp) return resp
[ "def", "_get_html_response", "(", "url", ":", "str", ",", "session", ":", "PipSession", ")", "->", "Response", ":", "if", "is_archive_file", "(", "Link", "(", "url", ")", ".", "filename", ")", ":", "_ensure_html_response", "(", "url", ",", "session", "=", "session", ")", "logger", ".", "debug", "(", "'Getting page %s'", ",", "redact_auth_from_url", "(", "url", ")", ")", "resp", "=", "session", ".", "get", "(", "url", ",", "headers", "=", "{", "\"Accept\"", ":", "\"text/html\"", ",", "# We don't want to blindly returned cached data for", "# /simple/, because authors generally expecting that", "# twine upload && pip install will function, but if", "# they've done a pip install in the last ~10 minutes", "# it won't. Thus by setting this to zero we will not", "# blindly use any cached data, however the benefit of", "# using max-age=0 instead of no-cache, is that we will", "# still support conditional requests, so we will still", "# minimize traffic sent in cases where the page hasn't", "# changed at all, we will just always incur the round", "# trip for the conditional GET now instead of only", "# once per 10 minutes.", "# For more information, please see pypa/pip#5670.", "\"Cache-Control\"", ":", "\"max-age=0\"", ",", "}", ",", ")", "raise_for_status", "(", "resp", ")", "# The check for archives above only works if the url ends with", "# something that looks like an archive. However that is not a", "# requirement of an url. Unless we issue a HEAD request on every", "# url we cannot know ahead of time for sure if something is HTML", "# or not. However we can check after we've downloaded it.", "_ensure_html_header", "(", "resp", ")", "return", "resp" ]
[ 96, 0 ]
[ 143, 15 ]
python
en
['en', 'en', 'en']
True